physfs.c 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266
  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. #define __PHYSICSFS_INTERNAL__
  11. #include "physfs_internal.h"
  12. #if defined(_MSC_VER)
  13. #include <stdarg.h>
  14. /* this code came from https://stackoverflow.com/a/8712996 */
  15. int __PHYSFS_msvc_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap)
  16. {
  17. int count = -1;
  18. if (size != 0)
  19. count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap);
  20. if (count == -1)
  21. count = _vscprintf(format, ap);
  22. return count;
  23. }
  24. int __PHYSFS_msvc_snprintf(char *outBuf, size_t size, const char *format, ...)
  25. {
  26. int count;
  27. va_list ap;
  28. va_start(ap, format);
  29. count = __PHYSFS_msvc_vsnprintf(outBuf, size, format, ap);
  30. va_end(ap);
  31. return count;
  32. }
  33. #endif
  34. typedef struct __PHYSFS_DIRHANDLE__
  35. {
  36. void *opaque; /* Instance data unique to the archiver. */
  37. char *dirName; /* Path to archive in platform-dependent notation. */
  38. char *mountPoint; /* Mountpoint in virtual file tree. */
  39. const PHYSFS_Archiver *funcs; /* Ptr to archiver info for this handle. */
  40. struct __PHYSFS_DIRHANDLE__ *next; /* linked list stuff. */
  41. } DirHandle;
  42. typedef struct __PHYSFS_FILEHANDLE__
  43. {
  44. PHYSFS_Io *io; /* Instance data unique to the archiver for this file. */
  45. PHYSFS_uint8 forReading; /* Non-zero if reading, zero if write/append */
  46. const DirHandle *dirHandle; /* Archiver instance that created this */
  47. PHYSFS_uint8 *buffer; /* Buffer, if set (NULL otherwise). Don't touch! */
  48. size_t bufsize; /* Bufsize, if set (0 otherwise). Don't touch! */
  49. size_t buffill; /* Buffer fill size. Don't touch! */
  50. size_t bufpos; /* Buffer position. Don't touch! */
  51. struct __PHYSFS_FILEHANDLE__ *next; /* linked list stuff. */
  52. } FileHandle;
  53. typedef struct __PHYSFS_ERRSTATETYPE__
  54. {
  55. void *tid;
  56. PHYSFS_ErrorCode code;
  57. struct __PHYSFS_ERRSTATETYPE__ *next;
  58. } ErrState;
  59. /* General PhysicsFS state ... */
  60. static int initialized = 0;
  61. static ErrState *errorStates = NULL;
  62. static DirHandle *searchPath = NULL;
  63. static DirHandle *writeDir = NULL;
  64. static FileHandle *openWriteList = NULL;
  65. static FileHandle *openReadList = NULL;
  66. static char *baseDir = NULL;
  67. static char *userDir = NULL;
  68. static char *prefDir = NULL;
  69. static int allowSymLinks = 0;
  70. static PHYSFS_Archiver **archivers = NULL;
  71. static PHYSFS_ArchiveInfo **archiveInfo = NULL;
  72. static volatile size_t numArchivers = 0;
  73. /* mutexes ... */
  74. static void *errorLock = NULL; /* protects error message list. */
  75. static void *stateLock = NULL; /* protects other PhysFS static state. */
  76. /* allocator ... */
  77. static int externalAllocator = 0;
  78. PHYSFS_Allocator allocator;
  79. #ifdef PHYSFS_NEED_ATOMIC_OP_FALLBACK
  80. static inline int __PHYSFS_atomicAdd(int *ptrval, const int val)
  81. {
  82. int retval;
  83. __PHYSFS_platformGrabMutex(stateLock);
  84. retval = *ptrval;
  85. *ptrval = retval + val;
  86. __PHYSFS_platformReleaseMutex(stateLock);
  87. return retval;
  88. } /* __PHYSFS_atomicAdd */
  89. int __PHYSFS_ATOMIC_INCR(int *ptrval)
  90. {
  91. return __PHYSFS_atomicAdd(ptrval, 1);
  92. } /* __PHYSFS_ATOMIC_INCR */
  93. int __PHYSFS_ATOMIC_DECR(int *ptrval)
  94. {
  95. return __PHYSFS_atomicAdd(ptrval, -1);
  96. } /* __PHYSFS_ATOMIC_DECR */
  97. #endif
  98. /* PHYSFS_Io implementation for i/o to physical filesystem... */
  99. /* !!! FIXME: maybe refcount the paths in a string pool? */
  100. typedef struct __PHYSFS_NativeIoInfo
  101. {
  102. void *handle;
  103. const char *path;
  104. int mode; /* 'r', 'w', or 'a' */
  105. } NativeIoInfo;
  106. static PHYSFS_sint64 nativeIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  107. {
  108. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  109. return __PHYSFS_platformRead(info->handle, buf, len);
  110. } /* nativeIo_read */
  111. static PHYSFS_sint64 nativeIo_write(PHYSFS_Io *io, const void *buffer,
  112. PHYSFS_uint64 len)
  113. {
  114. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  115. return __PHYSFS_platformWrite(info->handle, buffer, len);
  116. } /* nativeIo_write */
  117. static int nativeIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  118. {
  119. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  120. return __PHYSFS_platformSeek(info->handle, offset);
  121. } /* nativeIo_seek */
  122. static PHYSFS_sint64 nativeIo_tell(PHYSFS_Io *io)
  123. {
  124. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  125. return __PHYSFS_platformTell(info->handle);
  126. } /* nativeIo_tell */
  127. static PHYSFS_sint64 nativeIo_length(PHYSFS_Io *io)
  128. {
  129. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  130. return __PHYSFS_platformFileLength(info->handle);
  131. } /* nativeIo_length */
  132. static PHYSFS_Io *nativeIo_duplicate(PHYSFS_Io *io)
  133. {
  134. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  135. return __PHYSFS_createNativeIo(info->path, info->mode);
  136. } /* nativeIo_duplicate */
  137. static int nativeIo_flush(PHYSFS_Io *io)
  138. {
  139. return __PHYSFS_platformFlush(io->opaque);
  140. } /* nativeIo_flush */
  141. static void nativeIo_destroy(PHYSFS_Io *io)
  142. {
  143. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  144. __PHYSFS_platformClose(info->handle);
  145. allocator.Free((void *) info->path);
  146. allocator.Free(info);
  147. allocator.Free(io);
  148. } /* nativeIo_destroy */
  149. static const PHYSFS_Io __PHYSFS_nativeIoInterface =
  150. {
  151. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  152. nativeIo_read,
  153. nativeIo_write,
  154. nativeIo_seek,
  155. nativeIo_tell,
  156. nativeIo_length,
  157. nativeIo_duplicate,
  158. nativeIo_flush,
  159. nativeIo_destroy
  160. };
  161. PHYSFS_Io *__PHYSFS_createNativeIo(const char *path, const int mode)
  162. {
  163. PHYSFS_Io *io = NULL;
  164. NativeIoInfo *info = NULL;
  165. void *handle = NULL;
  166. char *pathdup = NULL;
  167. assert((mode == 'r') || (mode == 'w') || (mode == 'a'));
  168. io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  169. GOTO_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  170. info = (NativeIoInfo *) allocator.Malloc(sizeof (NativeIoInfo));
  171. GOTO_IF(!info, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  172. pathdup = (char *) allocator.Malloc(strlen(path) + 1);
  173. GOTO_IF(!pathdup, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  174. if (mode == 'r')
  175. handle = __PHYSFS_platformOpenRead(path);
  176. else if (mode == 'w')
  177. handle = __PHYSFS_platformOpenWrite(path);
  178. else if (mode == 'a')
  179. handle = __PHYSFS_platformOpenAppend(path);
  180. GOTO_IF_ERRPASS(!handle, createNativeIo_failed);
  181. strcpy(pathdup, path);
  182. info->handle = handle;
  183. info->path = pathdup;
  184. info->mode = mode;
  185. memcpy(io, &__PHYSFS_nativeIoInterface, sizeof (*io));
  186. io->opaque = info;
  187. return io;
  188. createNativeIo_failed:
  189. if (handle != NULL) __PHYSFS_platformClose(handle);
  190. if (pathdup != NULL) allocator.Free(pathdup);
  191. if (info != NULL) allocator.Free(info);
  192. if (io != NULL) allocator.Free(io);
  193. return NULL;
  194. } /* __PHYSFS_createNativeIo */
  195. /* PHYSFS_Io implementation for i/o to a memory buffer... */
  196. typedef struct __PHYSFS_MemoryIoInfo
  197. {
  198. const PHYSFS_uint8 *buf;
  199. PHYSFS_uint64 len;
  200. PHYSFS_uint64 pos;
  201. PHYSFS_Io *parent;
  202. int refcount;
  203. void (*destruct)(void *);
  204. } MemoryIoInfo;
  205. static PHYSFS_sint64 memoryIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  206. {
  207. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  208. const PHYSFS_uint64 avail = info->len - info->pos;
  209. assert(avail <= info->len);
  210. if (avail == 0)
  211. return 0; /* we're at EOF; nothing to do. */
  212. if (len > avail)
  213. len = avail;
  214. memcpy(buf, info->buf + info->pos, (size_t) len);
  215. info->pos += len;
  216. return len;
  217. } /* memoryIo_read */
  218. static PHYSFS_sint64 memoryIo_write(PHYSFS_Io *io, const void *buffer,
  219. PHYSFS_uint64 len)
  220. {
  221. BAIL(PHYSFS_ERR_OPEN_FOR_READING, -1);
  222. } /* memoryIo_write */
  223. static int memoryIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  224. {
  225. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  226. BAIL_IF(offset > info->len, PHYSFS_ERR_PAST_EOF, 0);
  227. info->pos = offset;
  228. return 1;
  229. } /* memoryIo_seek */
  230. static PHYSFS_sint64 memoryIo_tell(PHYSFS_Io *io)
  231. {
  232. const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  233. return (PHYSFS_sint64) info->pos;
  234. } /* memoryIo_tell */
  235. static PHYSFS_sint64 memoryIo_length(PHYSFS_Io *io)
  236. {
  237. const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  238. return (PHYSFS_sint64) info->len;
  239. } /* memoryIo_length */
  240. static PHYSFS_Io *memoryIo_duplicate(PHYSFS_Io *io)
  241. {
  242. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  243. MemoryIoInfo *newinfo = NULL;
  244. PHYSFS_Io *parent = info->parent;
  245. PHYSFS_Io *retval = NULL;
  246. /* avoid deep copies. */
  247. assert((!parent) || (!((MemoryIoInfo *) parent->opaque)->parent) );
  248. /* share the buffer between duplicates. */
  249. if (parent != NULL) /* dup the parent, increment its refcount. */
  250. return parent->duplicate(parent);
  251. /* we're the parent. */
  252. retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  253. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  254. newinfo = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
  255. if (!newinfo)
  256. {
  257. allocator.Free(retval);
  258. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  259. } /* if */
  260. __PHYSFS_ATOMIC_INCR(&info->refcount);
  261. memset(newinfo, '\0', sizeof (*info));
  262. newinfo->buf = info->buf;
  263. newinfo->len = info->len;
  264. newinfo->pos = 0;
  265. newinfo->parent = io;
  266. newinfo->refcount = 0;
  267. newinfo->destruct = NULL;
  268. memcpy(retval, io, sizeof (*retval));
  269. retval->opaque = newinfo;
  270. return retval;
  271. } /* memoryIo_duplicate */
  272. static int memoryIo_flush(PHYSFS_Io *io) { return 1; /* it's read-only. */ }
  273. static void memoryIo_destroy(PHYSFS_Io *io)
  274. {
  275. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  276. PHYSFS_Io *parent = info->parent;
  277. if (parent != NULL)
  278. {
  279. assert(info->buf == ((MemoryIoInfo *) info->parent->opaque)->buf);
  280. assert(info->len == ((MemoryIoInfo *) info->parent->opaque)->len);
  281. assert(info->refcount == 0);
  282. assert(info->destruct == NULL);
  283. allocator.Free(info);
  284. allocator.Free(io);
  285. parent->destroy(parent); /* decrements refcount. */
  286. return;
  287. } /* if */
  288. /* we _are_ the parent. */
  289. assert(info->refcount > 0); /* even in a race, we hold a reference. */
  290. if (__PHYSFS_ATOMIC_DECR(&info->refcount) == 0)
  291. {
  292. void (*destruct)(void *) = info->destruct;
  293. void *buf = (void *) info->buf;
  294. io->opaque = NULL; /* kill this here in case of race. */
  295. allocator.Free(info);
  296. allocator.Free(io);
  297. if (destruct != NULL)
  298. destruct(buf);
  299. } /* if */
  300. } /* memoryIo_destroy */
  301. static const PHYSFS_Io __PHYSFS_memoryIoInterface =
  302. {
  303. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  304. memoryIo_read,
  305. memoryIo_write,
  306. memoryIo_seek,
  307. memoryIo_tell,
  308. memoryIo_length,
  309. memoryIo_duplicate,
  310. memoryIo_flush,
  311. memoryIo_destroy
  312. };
  313. PHYSFS_Io *__PHYSFS_createMemoryIo(const void *buf, PHYSFS_uint64 len,
  314. void (*destruct)(void *))
  315. {
  316. PHYSFS_Io *io = NULL;
  317. MemoryIoInfo *info = NULL;
  318. io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  319. GOTO_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
  320. info = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
  321. GOTO_IF(!info, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
  322. memset(info, '\0', sizeof (*info));
  323. info->buf = (const PHYSFS_uint8 *) buf;
  324. info->len = len;
  325. info->pos = 0;
  326. info->parent = NULL;
  327. info->refcount = 1;
  328. info->destruct = destruct;
  329. memcpy(io, &__PHYSFS_memoryIoInterface, sizeof (*io));
  330. io->opaque = info;
  331. return io;
  332. createMemoryIo_failed:
  333. if (info != NULL) allocator.Free(info);
  334. if (io != NULL) allocator.Free(io);
  335. return NULL;
  336. } /* __PHYSFS_createMemoryIo */
  337. /* PHYSFS_Io implementation for i/o to a PHYSFS_File... */
  338. static PHYSFS_sint64 handleIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  339. {
  340. return PHYSFS_readBytes((PHYSFS_File *) io->opaque, buf, len);
  341. } /* handleIo_read */
  342. static PHYSFS_sint64 handleIo_write(PHYSFS_Io *io, const void *buffer,
  343. PHYSFS_uint64 len)
  344. {
  345. return PHYSFS_writeBytes((PHYSFS_File *) io->opaque, buffer, len);
  346. } /* handleIo_write */
  347. static int handleIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  348. {
  349. return PHYSFS_seek((PHYSFS_File *) io->opaque, offset);
  350. } /* handleIo_seek */
  351. static PHYSFS_sint64 handleIo_tell(PHYSFS_Io *io)
  352. {
  353. return PHYSFS_tell((PHYSFS_File *) io->opaque);
  354. } /* handleIo_tell */
  355. static PHYSFS_sint64 handleIo_length(PHYSFS_Io *io)
  356. {
  357. return PHYSFS_fileLength((PHYSFS_File *) io->opaque);
  358. } /* handleIo_length */
  359. static PHYSFS_Io *handleIo_duplicate(PHYSFS_Io *io)
  360. {
  361. /*
  362. * There's no duplicate at the PHYSFS_File level, so we break the
  363. * abstraction. We're allowed to: we're physfs.c!
  364. */
  365. FileHandle *origfh = (FileHandle *) io->opaque;
  366. FileHandle *newfh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  367. PHYSFS_Io *retval = NULL;
  368. GOTO_IF(!newfh, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  369. memset(newfh, '\0', sizeof (*newfh));
  370. retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  371. GOTO_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  372. #if 0 /* we don't buffer the duplicate, at least not at the moment. */
  373. if (origfh->buffer != NULL)
  374. {
  375. newfh->buffer = (PHYSFS_uint8 *) allocator.Malloc(origfh->bufsize);
  376. if (!newfh->buffer)
  377. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  378. newfh->bufsize = origfh->bufsize;
  379. } /* if */
  380. #endif
  381. newfh->io = origfh->io->duplicate(origfh->io);
  382. GOTO_IF_ERRPASS(!newfh->io, handleIo_dupe_failed);
  383. newfh->forReading = origfh->forReading;
  384. newfh->dirHandle = origfh->dirHandle;
  385. __PHYSFS_platformGrabMutex(stateLock);
  386. if (newfh->forReading)
  387. {
  388. newfh->next = openReadList;
  389. openReadList = newfh;
  390. } /* if */
  391. else
  392. {
  393. newfh->next = openWriteList;
  394. openWriteList = newfh;
  395. } /* else */
  396. __PHYSFS_platformReleaseMutex(stateLock);
  397. memcpy(retval, io, sizeof (PHYSFS_Io));
  398. retval->opaque = newfh;
  399. return retval;
  400. handleIo_dupe_failed:
  401. if (newfh)
  402. {
  403. if (newfh->io != NULL) newfh->io->destroy(newfh->io);
  404. if (newfh->buffer != NULL) allocator.Free(newfh->buffer);
  405. allocator.Free(newfh);
  406. } /* if */
  407. return NULL;
  408. } /* handleIo_duplicate */
  409. static int handleIo_flush(PHYSFS_Io *io)
  410. {
  411. return PHYSFS_flush((PHYSFS_File *) io->opaque);
  412. } /* handleIo_flush */
  413. static void handleIo_destroy(PHYSFS_Io *io)
  414. {
  415. if (io->opaque != NULL)
  416. PHYSFS_close((PHYSFS_File *) io->opaque);
  417. allocator.Free(io);
  418. } /* handleIo_destroy */
  419. static const PHYSFS_Io __PHYSFS_handleIoInterface =
  420. {
  421. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  422. handleIo_read,
  423. handleIo_write,
  424. handleIo_seek,
  425. handleIo_tell,
  426. handleIo_length,
  427. handleIo_duplicate,
  428. handleIo_flush,
  429. handleIo_destroy
  430. };
  431. static PHYSFS_Io *__PHYSFS_createHandleIo(PHYSFS_File *f)
  432. {
  433. PHYSFS_Io *io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  434. BAIL_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  435. memcpy(io, &__PHYSFS_handleIoInterface, sizeof (*io));
  436. io->opaque = f;
  437. return io;
  438. } /* __PHYSFS_createHandleIo */
  439. /* functions ... */
  440. typedef struct
  441. {
  442. char **list;
  443. PHYSFS_uint32 size;
  444. PHYSFS_ErrorCode errcode;
  445. } EnumStringListCallbackData;
  446. static void enumStringListCallback(void *data, const char *str)
  447. {
  448. void *ptr;
  449. char *newstr;
  450. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  451. if (pecd->errcode)
  452. return;
  453. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  454. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  455. if (ptr != NULL)
  456. pecd->list = (char **) ptr;
  457. if ((ptr == NULL) || (newstr == NULL))
  458. {
  459. pecd->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  460. pecd->list[pecd->size] = NULL;
  461. PHYSFS_freeList(pecd->list);
  462. return;
  463. } /* if */
  464. strcpy(newstr, str);
  465. pecd->list[pecd->size] = newstr;
  466. pecd->size++;
  467. } /* enumStringListCallback */
  468. static char **doEnumStringList(void (*func)(PHYSFS_StringCallback, void *))
  469. {
  470. EnumStringListCallbackData ecd;
  471. memset(&ecd, '\0', sizeof (ecd));
  472. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  473. BAIL_IF(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  474. func(enumStringListCallback, &ecd);
  475. if (ecd.errcode)
  476. {
  477. PHYSFS_setErrorCode(ecd.errcode);
  478. return NULL;
  479. } /* if */
  480. ecd.list[ecd.size] = NULL;
  481. return ecd.list;
  482. } /* doEnumStringList */
  483. static void __PHYSFS_bubble_sort(void *a, size_t lo, size_t hi,
  484. int (*cmpfn)(void *, size_t, size_t),
  485. void (*swapfn)(void *, size_t, size_t))
  486. {
  487. size_t i;
  488. int sorted;
  489. do
  490. {
  491. sorted = 1;
  492. for (i = lo; i < hi; i++)
  493. {
  494. if (cmpfn(a, i, i + 1) > 0)
  495. {
  496. swapfn(a, i, i + 1);
  497. sorted = 0;
  498. } /* if */
  499. } /* for */
  500. } while (!sorted);
  501. } /* __PHYSFS_bubble_sort */
  502. static void __PHYSFS_quick_sort(void *a, size_t lo, size_t hi,
  503. int (*cmpfn)(void *, size_t, size_t),
  504. void (*swapfn)(void *, size_t, size_t))
  505. {
  506. size_t i;
  507. size_t j;
  508. size_t v;
  509. if ((hi - lo) <= PHYSFS_QUICKSORT_THRESHOLD)
  510. __PHYSFS_bubble_sort(a, lo, hi, cmpfn, swapfn);
  511. else
  512. {
  513. i = (hi + lo) / 2;
  514. if (cmpfn(a, lo, i) > 0) swapfn(a, lo, i);
  515. if (cmpfn(a, lo, hi) > 0) swapfn(a, lo, hi);
  516. if (cmpfn(a, i, hi) > 0) swapfn(a, i, hi);
  517. j = hi - 1;
  518. swapfn(a, i, j);
  519. i = lo;
  520. v = j;
  521. while (1)
  522. {
  523. while(cmpfn(a, ++i, v) < 0) { /* do nothing */ }
  524. while(cmpfn(a, --j, v) > 0) { /* do nothing */ }
  525. if (j < i)
  526. break;
  527. swapfn(a, i, j);
  528. } /* while */
  529. if (i != (hi-1))
  530. swapfn(a, i, hi-1);
  531. __PHYSFS_quick_sort(a, lo, j, cmpfn, swapfn);
  532. __PHYSFS_quick_sort(a, i+1, hi, cmpfn, swapfn);
  533. } /* else */
  534. } /* __PHYSFS_quick_sort */
  535. void __PHYSFS_sort(void *entries, size_t max,
  536. int (*cmpfn)(void *, size_t, size_t),
  537. void (*swapfn)(void *, size_t, size_t))
  538. {
  539. /*
  540. * Quicksort w/ Bubblesort fallback algorithm inspired by code from here:
  541. * https://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
  542. */
  543. if (max > 0)
  544. __PHYSFS_quick_sort(entries, 0, max - 1, cmpfn, swapfn);
  545. } /* __PHYSFS_sort */
  546. static ErrState *findErrorForCurrentThread(void)
  547. {
  548. ErrState *i;
  549. void *tid;
  550. if (errorLock != NULL)
  551. __PHYSFS_platformGrabMutex(errorLock);
  552. if (errorStates != NULL)
  553. {
  554. tid = __PHYSFS_platformGetThreadID();
  555. for (i = errorStates; i != NULL; i = i->next)
  556. {
  557. if (i->tid == tid)
  558. {
  559. if (errorLock != NULL)
  560. __PHYSFS_platformReleaseMutex(errorLock);
  561. return i;
  562. } /* if */
  563. } /* for */
  564. } /* if */
  565. if (errorLock != NULL)
  566. __PHYSFS_platformReleaseMutex(errorLock);
  567. return NULL; /* no error available. */
  568. } /* findErrorForCurrentThread */
  569. /* this doesn't reset the error state. */
  570. static inline PHYSFS_ErrorCode currentErrorCode(void)
  571. {
  572. const ErrState *err = findErrorForCurrentThread();
  573. return err ? err->code : PHYSFS_ERR_OK;
  574. } /* currentErrorCode */
  575. PHYSFS_ErrorCode PHYSFS_getLastErrorCode(void)
  576. {
  577. ErrState *err = findErrorForCurrentThread();
  578. const PHYSFS_ErrorCode retval = (err) ? err->code : PHYSFS_ERR_OK;
  579. if (err)
  580. err->code = PHYSFS_ERR_OK;
  581. return retval;
  582. } /* PHYSFS_getLastErrorCode */
  583. PHYSFS_DECL const char *PHYSFS_getErrorByCode(PHYSFS_ErrorCode code)
  584. {
  585. switch (code)
  586. {
  587. case PHYSFS_ERR_OK: return "no error";
  588. case PHYSFS_ERR_OTHER_ERROR: return "unknown error";
  589. case PHYSFS_ERR_OUT_OF_MEMORY: return "out of memory";
  590. case PHYSFS_ERR_NOT_INITIALIZED: return "not initialized";
  591. case PHYSFS_ERR_IS_INITIALIZED: return "already initialized";
  592. case PHYSFS_ERR_ARGV0_IS_NULL: return "argv[0] is NULL";
  593. case PHYSFS_ERR_UNSUPPORTED: return "unsupported";
  594. case PHYSFS_ERR_PAST_EOF: return "past end of file";
  595. case PHYSFS_ERR_FILES_STILL_OPEN: return "files still open";
  596. case PHYSFS_ERR_INVALID_ARGUMENT: return "invalid argument";
  597. case PHYSFS_ERR_NOT_MOUNTED: return "not mounted";
  598. case PHYSFS_ERR_NOT_FOUND: return "not found";
  599. case PHYSFS_ERR_SYMLINK_FORBIDDEN: return "symlinks are forbidden";
  600. case PHYSFS_ERR_NO_WRITE_DIR: return "write directory is not set";
  601. case PHYSFS_ERR_OPEN_FOR_READING: return "file open for reading";
  602. case PHYSFS_ERR_OPEN_FOR_WRITING: return "file open for writing";
  603. case PHYSFS_ERR_NOT_A_FILE: return "not a file";
  604. case PHYSFS_ERR_READ_ONLY: return "read-only filesystem";
  605. case PHYSFS_ERR_CORRUPT: return "corrupted";
  606. case PHYSFS_ERR_SYMLINK_LOOP: return "infinite symbolic link loop";
  607. case PHYSFS_ERR_IO: return "i/o error";
  608. case PHYSFS_ERR_PERMISSION: return "permission denied";
  609. case PHYSFS_ERR_NO_SPACE: return "no space available for writing";
  610. case PHYSFS_ERR_BAD_FILENAME: return "filename is illegal or insecure";
  611. case PHYSFS_ERR_BUSY: return "tried to modify a file the OS needs";
  612. case PHYSFS_ERR_DIR_NOT_EMPTY: return "directory isn't empty";
  613. case PHYSFS_ERR_OS_ERROR: return "OS reported an error";
  614. case PHYSFS_ERR_DUPLICATE: return "duplicate resource";
  615. case PHYSFS_ERR_BAD_PASSWORD: return "bad password";
  616. case PHYSFS_ERR_APP_CALLBACK: return "app callback reported error";
  617. } /* switch */
  618. return NULL; /* don't know this error code. */
  619. } /* PHYSFS_getErrorByCode */
  620. void PHYSFS_setErrorCode(PHYSFS_ErrorCode errcode)
  621. {
  622. ErrState *err;
  623. if (!errcode)
  624. return;
  625. err = findErrorForCurrentThread();
  626. if (err == NULL)
  627. {
  628. err = (ErrState *) allocator.Malloc(sizeof (ErrState));
  629. if (err == NULL)
  630. return; /* uhh...? */
  631. memset(err, '\0', sizeof (ErrState));
  632. err->tid = __PHYSFS_platformGetThreadID();
  633. if (errorLock != NULL)
  634. __PHYSFS_platformGrabMutex(errorLock);
  635. err->next = errorStates;
  636. errorStates = err;
  637. if (errorLock != NULL)
  638. __PHYSFS_platformReleaseMutex(errorLock);
  639. } /* if */
  640. err->code = errcode;
  641. } /* PHYSFS_setErrorCode */
  642. const char *PHYSFS_getLastError(void)
  643. {
  644. const PHYSFS_ErrorCode err = PHYSFS_getLastErrorCode();
  645. return (err) ? PHYSFS_getErrorByCode(err) : NULL;
  646. } /* PHYSFS_getLastError */
  647. /* MAKE SURE that errorLock is held before calling this! */
  648. static void freeErrorStates(void)
  649. {
  650. ErrState *i;
  651. ErrState *next;
  652. for (i = errorStates; i != NULL; i = next)
  653. {
  654. next = i->next;
  655. allocator.Free(i);
  656. } /* for */
  657. errorStates = NULL;
  658. } /* freeErrorStates */
  659. void PHYSFS_getLinkedVersion(PHYSFS_Version *ver)
  660. {
  661. if (ver != NULL)
  662. {
  663. ver->major = PHYSFS_VER_MAJOR;
  664. ver->minor = PHYSFS_VER_MINOR;
  665. ver->patch = PHYSFS_VER_PATCH;
  666. } /* if */
  667. } /* PHYSFS_getLinkedVersion */
  668. static const char *find_filename_extension(const char *fname)
  669. {
  670. const char *retval = NULL;
  671. if (fname != NULL)
  672. {
  673. const char *p = strchr(fname, '.');
  674. retval = p;
  675. while (p != NULL)
  676. {
  677. p = strchr(p + 1, '.');
  678. if (p != NULL)
  679. retval = p;
  680. } /* while */
  681. if (retval != NULL)
  682. retval++; /* skip '.' */
  683. } /* if */
  684. return retval;
  685. } /* find_filename_extension */
  686. static DirHandle *tryOpenDir(PHYSFS_Io *io, const PHYSFS_Archiver *funcs,
  687. const char *d, int forWriting)
  688. {
  689. DirHandle *retval = NULL;
  690. void *opaque = NULL;
  691. if (io != NULL)
  692. BAIL_IF_ERRPASS(!io->seek(io, 0), NULL);
  693. opaque = funcs->openArchive(io, d, forWriting);
  694. if (opaque != NULL)
  695. {
  696. retval = (DirHandle *) allocator.Malloc(sizeof (DirHandle));
  697. if (retval == NULL)
  698. funcs->closeArchive(opaque);
  699. else
  700. {
  701. memset(retval, '\0', sizeof (DirHandle));
  702. retval->mountPoint = NULL;
  703. retval->funcs = funcs;
  704. retval->opaque = opaque;
  705. } /* else */
  706. } /* if */
  707. return retval;
  708. } /* tryOpenDir */
  709. static DirHandle *openDirectory(PHYSFS_Io *io, const char *d, int forWriting)
  710. {
  711. DirHandle *retval = NULL;
  712. PHYSFS_Archiver **i;
  713. const char *ext;
  714. int created_io = 0;
  715. assert((io != NULL) || (d != NULL));
  716. if (io == NULL)
  717. {
  718. /* DIR gets first shot (unlike the rest, it doesn't deal with files). */
  719. retval = tryOpenDir(io, &__PHYSFS_Archiver_DIR, d, forWriting);
  720. if (retval != NULL)
  721. return retval;
  722. io = __PHYSFS_createNativeIo(d, forWriting ? 'w' : 'r');
  723. BAIL_IF_ERRPASS(!io, 0);
  724. created_io = 1;
  725. } /* if */
  726. ext = find_filename_extension(d);
  727. if (ext != NULL)
  728. {
  729. /* Look for archivers with matching file extensions first... */
  730. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  731. {
  732. if (PHYSFS_utf8stricmp(ext, (*i)->info.extension) == 0)
  733. retval = tryOpenDir(io, *i, d, forWriting);
  734. } /* for */
  735. /* failing an exact file extension match, try all the others... */
  736. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  737. {
  738. if (PHYSFS_utf8stricmp(ext, (*i)->info.extension) != 0)
  739. retval = tryOpenDir(io, *i, d, forWriting);
  740. } /* for */
  741. } /* if */
  742. else /* no extension? Try them all. */
  743. {
  744. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  745. retval = tryOpenDir(io, *i, d, forWriting);
  746. } /* else */
  747. if ((!retval) && (created_io))
  748. io->destroy(io);
  749. BAIL_IF(!retval, PHYSFS_ERR_UNSUPPORTED, NULL);
  750. return retval;
  751. } /* openDirectory */
  752. /*
  753. * Make a platform-independent path string sane. Doesn't actually check the
  754. * file hierarchy, it just cleans up the string.
  755. * (dst) must be a buffer at least as big as (src), as this is where the
  756. * cleaned up string is deposited.
  757. * If there are illegal bits in the path (".." entries, etc) then we
  758. * return zero and (dst) is undefined. Non-zero if the path was sanitized.
  759. */
  760. static int sanitizePlatformIndependentPath(const char *src, char *dst)
  761. {
  762. char *prev;
  763. char ch;
  764. while (*src == '/') /* skip initial '/' chars... */
  765. src++;
  766. prev = dst;
  767. do
  768. {
  769. ch = *(src++);
  770. if ((ch == ':') || (ch == '\\')) /* illegal chars in a physfs path. */
  771. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  772. if (ch == '/') /* path separator. */
  773. {
  774. *dst = '\0'; /* "." and ".." are illegal pathnames. */
  775. if ((strcmp(prev, ".") == 0) || (strcmp(prev, "..") == 0))
  776. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  777. while (*src == '/') /* chop out doubles... */
  778. src++;
  779. if (*src == '\0') /* ends with a pathsep? */
  780. break; /* we're done, don't add final pathsep to dst. */
  781. prev = dst + 1;
  782. } /* if */
  783. *(dst++) = ch;
  784. } while (ch != '\0');
  785. return 1;
  786. } /* sanitizePlatformIndependentPath */
  787. /*
  788. * Figure out if (fname) is part of (h)'s mountpoint. (fname) must be an
  789. * output from sanitizePlatformIndependentPath(), so that it is in a known
  790. * state.
  791. *
  792. * This only finds legitimate segments of a mountpoint. If the mountpoint is
  793. * "/a/b/c" and (fname) is "/a/b/c", "/", or "/a/b/c/d", then the results are
  794. * all zero. "/a/b" will succeed, though.
  795. */
  796. static int partOfMountPoint(DirHandle *h, char *fname)
  797. {
  798. int rc;
  799. size_t len, mntpntlen;
  800. if (h->mountPoint == NULL)
  801. return 0;
  802. else if (*fname == '\0')
  803. return 1;
  804. len = strlen(fname);
  805. mntpntlen = strlen(h->mountPoint);
  806. if (len > mntpntlen) /* can't be a subset of mountpoint. */
  807. return 0;
  808. /* if true, must be not a match or a complete match, but not a subset. */
  809. if ((len + 1) == mntpntlen)
  810. return 0;
  811. rc = strncmp(fname, h->mountPoint, len); /* !!! FIXME: case insensitive? */
  812. if (rc != 0)
  813. return 0; /* not a match. */
  814. /* make sure /a/b matches /a/b/ and not /a/bc ... */
  815. return h->mountPoint[len] == '/';
  816. } /* partOfMountPoint */
  817. static DirHandle *createDirHandle(PHYSFS_Io *io, const char *newDir,
  818. const char *mountPoint, int forWriting)
  819. {
  820. DirHandle *dirHandle = NULL;
  821. char *tmpmntpnt = NULL;
  822. if (mountPoint != NULL)
  823. {
  824. const size_t len = strlen(mountPoint) + 1;
  825. tmpmntpnt = (char *) __PHYSFS_smallAlloc(len);
  826. GOTO_IF(!tmpmntpnt, PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  827. if (!sanitizePlatformIndependentPath(mountPoint, tmpmntpnt))
  828. goto badDirHandle;
  829. mountPoint = tmpmntpnt; /* sanitized version. */
  830. } /* if */
  831. dirHandle = openDirectory(io, newDir, forWriting);
  832. GOTO_IF_ERRPASS(!dirHandle, badDirHandle);
  833. if (newDir == NULL)
  834. dirHandle->dirName = NULL;
  835. else
  836. {
  837. dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
  838. if (!dirHandle->dirName)
  839. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  840. strcpy(dirHandle->dirName, newDir);
  841. } /* else */
  842. if ((mountPoint != NULL) && (*mountPoint != '\0'))
  843. {
  844. dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
  845. if (!dirHandle->mountPoint)
  846. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  847. strcpy(dirHandle->mountPoint, mountPoint);
  848. strcat(dirHandle->mountPoint, "/");
  849. } /* if */
  850. __PHYSFS_smallFree(tmpmntpnt);
  851. return dirHandle;
  852. badDirHandle:
  853. if (dirHandle != NULL)
  854. {
  855. dirHandle->funcs->closeArchive(dirHandle->opaque);
  856. allocator.Free(dirHandle->dirName);
  857. allocator.Free(dirHandle->mountPoint);
  858. allocator.Free(dirHandle);
  859. } /* if */
  860. __PHYSFS_smallFree(tmpmntpnt);
  861. return NULL;
  862. } /* createDirHandle */
  863. /* MAKE SURE you've got the stateLock held before calling this! */
  864. static int freeDirHandle(DirHandle *dh, FileHandle *openList)
  865. {
  866. FileHandle *i;
  867. if (dh == NULL)
  868. return 1;
  869. for (i = openList; i != NULL; i = i->next)
  870. BAIL_IF(i->dirHandle == dh, PHYSFS_ERR_FILES_STILL_OPEN, 0);
  871. dh->funcs->closeArchive(dh->opaque);
  872. allocator.Free(dh->dirName);
  873. allocator.Free(dh->mountPoint);
  874. allocator.Free(dh);
  875. return 1;
  876. } /* freeDirHandle */
  877. static char *calculateBaseDir(const char *argv0)
  878. {
  879. const char dirsep = __PHYSFS_platformDirSeparator;
  880. char *retval = NULL;
  881. char *ptr = NULL;
  882. /* Give the platform layer first shot at this. */
  883. retval = __PHYSFS_platformCalcBaseDir(argv0);
  884. if (retval != NULL)
  885. return retval;
  886. /* We need argv0 to go on. */
  887. BAIL_IF(argv0 == NULL, PHYSFS_ERR_ARGV0_IS_NULL, NULL);
  888. ptr = strrchr(argv0, dirsep);
  889. if (ptr != NULL)
  890. {
  891. const size_t size = ((size_t) (ptr - argv0)) + 1;
  892. retval = (char *) allocator.Malloc(size + 1);
  893. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  894. memcpy(retval, argv0, size);
  895. retval[size] = '\0';
  896. return retval;
  897. } /* if */
  898. /* argv0 wasn't helpful. */
  899. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  900. } /* calculateBaseDir */
  901. static int initializeMutexes(void)
  902. {
  903. errorLock = __PHYSFS_platformCreateMutex();
  904. if (errorLock == NULL)
  905. goto initializeMutexes_failed;
  906. stateLock = __PHYSFS_platformCreateMutex();
  907. if (stateLock == NULL)
  908. goto initializeMutexes_failed;
  909. return 1; /* success. */
  910. initializeMutexes_failed:
  911. if (errorLock != NULL)
  912. __PHYSFS_platformDestroyMutex(errorLock);
  913. if (stateLock != NULL)
  914. __PHYSFS_platformDestroyMutex(stateLock);
  915. errorLock = stateLock = NULL;
  916. return 0; /* failed. */
  917. } /* initializeMutexes */
  918. static int doRegisterArchiver(const PHYSFS_Archiver *_archiver);
  919. static int initStaticArchivers(void)
  920. {
  921. #define REGISTER_STATIC_ARCHIVER(arc) { \
  922. if (!doRegisterArchiver(&__PHYSFS_Archiver_##arc)) { \
  923. return 0; \
  924. } \
  925. }
  926. #if PHYSFS_SUPPORTS_ZIP
  927. REGISTER_STATIC_ARCHIVER(ZIP);
  928. #endif
  929. #if PHYSFS_SUPPORTS_7Z
  930. REGISTER_STATIC_ARCHIVER(7Z);
  931. #endif
  932. #if PHYSFS_SUPPORTS_GRP
  933. REGISTER_STATIC_ARCHIVER(GRP);
  934. #endif
  935. #if PHYSFS_SUPPORTS_QPAK
  936. REGISTER_STATIC_ARCHIVER(QPAK);
  937. #endif
  938. #if PHYSFS_SUPPORTS_HOG
  939. REGISTER_STATIC_ARCHIVER(HOG);
  940. #endif
  941. #if PHYSFS_SUPPORTS_MVL
  942. REGISTER_STATIC_ARCHIVER(MVL);
  943. #endif
  944. #if PHYSFS_SUPPORTS_WAD
  945. REGISTER_STATIC_ARCHIVER(WAD);
  946. #endif
  947. #if PHYSFS_SUPPORTS_SLB
  948. REGISTER_STATIC_ARCHIVER(SLB);
  949. #endif
  950. #if PHYSFS_SUPPORTS_ISO9660
  951. REGISTER_STATIC_ARCHIVER(ISO9660);
  952. #endif
  953. #if PHYSFS_SUPPORTS_VDF
  954. REGISTER_STATIC_ARCHIVER(VDF)
  955. #endif
  956. #undef REGISTER_STATIC_ARCHIVER
  957. return 1;
  958. } /* initStaticArchivers */
  959. static void setDefaultAllocator(void);
  960. static int doDeinit(void);
  961. int PHYSFS_init(const char *argv0)
  962. {
  963. BAIL_IF(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
  964. if (!externalAllocator)
  965. setDefaultAllocator();
  966. if ((allocator.Init != NULL) && (!allocator.Init())) return 0;
  967. if (!__PHYSFS_platformInit())
  968. {
  969. if (allocator.Deinit != NULL) allocator.Deinit();
  970. return 0;
  971. } /* if */
  972. /* everything below here can be cleaned up safely by doDeinit(). */
  973. if (!initializeMutexes()) goto initFailed;
  974. baseDir = calculateBaseDir(argv0);
  975. if (!baseDir) goto initFailed;
  976. userDir = __PHYSFS_platformCalcUserDir();
  977. if (!userDir) goto initFailed;
  978. /* Platform layer is required to append a dirsep. */
  979. assert(baseDir[strlen(baseDir) - 1] == __PHYSFS_platformDirSeparator);
  980. assert(userDir[strlen(userDir) - 1] == __PHYSFS_platformDirSeparator);
  981. if (!initStaticArchivers()) goto initFailed;
  982. initialized = 1;
  983. /* This makes sure that the error subsystem is initialized. */
  984. PHYSFS_setErrorCode(PHYSFS_getLastErrorCode());
  985. return 1;
  986. initFailed:
  987. doDeinit();
  988. return 0;
  989. } /* PHYSFS_init */
  990. /* MAKE SURE you hold stateLock before calling this! */
  991. static int closeFileHandleList(FileHandle **list)
  992. {
  993. FileHandle *i;
  994. FileHandle *next = NULL;
  995. for (i = *list; i != NULL; i = next)
  996. {
  997. PHYSFS_Io *io = i->io;
  998. next = i->next;
  999. if (io->flush && !io->flush(io))
  1000. {
  1001. *list = i;
  1002. return 0;
  1003. } /* if */
  1004. io->destroy(io);
  1005. allocator.Free(i);
  1006. } /* for */
  1007. *list = NULL;
  1008. return 1;
  1009. } /* closeFileHandleList */
  1010. /* MAKE SURE you hold the stateLock before calling this! */
  1011. static void freeSearchPath(void)
  1012. {
  1013. DirHandle *i;
  1014. DirHandle *next = NULL;
  1015. closeFileHandleList(&openReadList);
  1016. if (searchPath != NULL)
  1017. {
  1018. for (i = searchPath; i != NULL; i = next)
  1019. {
  1020. next = i->next;
  1021. freeDirHandle(i, openReadList);
  1022. } /* for */
  1023. searchPath = NULL;
  1024. } /* if */
  1025. } /* freeSearchPath */
  1026. /* MAKE SURE you hold stateLock before calling this! */
  1027. static int archiverInUse(const PHYSFS_Archiver *arc, const DirHandle *list)
  1028. {
  1029. const DirHandle *i;
  1030. for (i = list; i != NULL; i = i->next)
  1031. {
  1032. if (i->funcs == arc)
  1033. return 1;
  1034. } /* for */
  1035. return 0; /* not in use */
  1036. } /* archiverInUse */
  1037. /* MAKE SURE you hold stateLock before calling this! */
  1038. static int doDeregisterArchiver(const size_t idx)
  1039. {
  1040. const size_t len = (numArchivers - idx) * sizeof (void *);
  1041. PHYSFS_ArchiveInfo *info = archiveInfo[idx];
  1042. PHYSFS_Archiver *arc = archivers[idx];
  1043. /* make sure nothing is still using this archiver */
  1044. if (archiverInUse(arc, searchPath) || archiverInUse(arc, writeDir))
  1045. BAIL(PHYSFS_ERR_FILES_STILL_OPEN, 0);
  1046. allocator.Free((void *) info->extension);
  1047. allocator.Free((void *) info->description);
  1048. allocator.Free((void *) info->author);
  1049. allocator.Free((void *) info->url);
  1050. allocator.Free((void *) arc);
  1051. memmove(&archiveInfo[idx], &archiveInfo[idx+1], len);
  1052. memmove(&archivers[idx], &archivers[idx+1], len);
  1053. assert(numArchivers > 0);
  1054. numArchivers--;
  1055. return 1;
  1056. } /* doDeregisterArchiver */
  1057. /* Does NOT hold the state lock; we're shutting down. */
  1058. static void freeArchivers(void)
  1059. {
  1060. while (numArchivers > 0)
  1061. {
  1062. if (!doDeregisterArchiver(numArchivers - 1))
  1063. assert(!"nothing should be mounted during shutdown.");
  1064. } /* while */
  1065. allocator.Free(archivers);
  1066. allocator.Free(archiveInfo);
  1067. archivers = NULL;
  1068. archiveInfo = NULL;
  1069. } /* freeArchivers */
  1070. static int doDeinit(void)
  1071. {
  1072. closeFileHandleList(&openWriteList);
  1073. BAIL_IF(!PHYSFS_setWriteDir(NULL), PHYSFS_ERR_FILES_STILL_OPEN, 0);
  1074. freeSearchPath();
  1075. freeArchivers();
  1076. freeErrorStates();
  1077. if (baseDir != NULL)
  1078. {
  1079. allocator.Free(baseDir);
  1080. baseDir = NULL;
  1081. } /* if */
  1082. if (userDir != NULL)
  1083. {
  1084. allocator.Free(userDir);
  1085. userDir = NULL;
  1086. } /* if */
  1087. if (prefDir != NULL)
  1088. {
  1089. allocator.Free(prefDir);
  1090. prefDir = NULL;
  1091. } /* if */
  1092. if (archiveInfo != NULL)
  1093. {
  1094. allocator.Free(archiveInfo);
  1095. archiveInfo = NULL;
  1096. } /* if */
  1097. if (archivers != NULL)
  1098. {
  1099. allocator.Free(archivers);
  1100. archivers = NULL;
  1101. } /* if */
  1102. allowSymLinks = 0;
  1103. initialized = 0;
  1104. if (errorLock) __PHYSFS_platformDestroyMutex(errorLock);
  1105. if (stateLock) __PHYSFS_platformDestroyMutex(stateLock);
  1106. if (allocator.Deinit != NULL)
  1107. allocator.Deinit();
  1108. errorLock = stateLock = NULL;
  1109. __PHYSFS_platformDeinit();
  1110. return 1;
  1111. } /* doDeinit */
  1112. int PHYSFS_deinit(void)
  1113. {
  1114. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1115. return doDeinit();
  1116. } /* PHYSFS_deinit */
  1117. int PHYSFS_isInit(void)
  1118. {
  1119. return initialized;
  1120. } /* PHYSFS_isInit */
  1121. char *__PHYSFS_strdup(const char *str)
  1122. {
  1123. char *retval = (char *) allocator.Malloc(strlen(str) + 1);
  1124. if (retval)
  1125. strcpy(retval, str);
  1126. return retval;
  1127. } /* __PHYSFS_strdup */
  1128. PHYSFS_uint32 __PHYSFS_hashString(const char *str, size_t len)
  1129. {
  1130. PHYSFS_uint32 hash = 5381;
  1131. while (len--)
  1132. hash = ((hash << 5) + hash) ^ *(str++);
  1133. return hash;
  1134. } /* __PHYSFS_hashString */
  1135. /* MAKE SURE you hold stateLock before calling this! */
  1136. static int doRegisterArchiver(const PHYSFS_Archiver *_archiver)
  1137. {
  1138. const PHYSFS_uint32 maxver = CURRENT_PHYSFS_ARCHIVER_API_VERSION;
  1139. const size_t len = (numArchivers + 2) * sizeof (void *);
  1140. PHYSFS_Archiver *archiver = NULL;
  1141. PHYSFS_ArchiveInfo *info = NULL;
  1142. const char *ext = NULL;
  1143. void *ptr = NULL;
  1144. size_t i;
  1145. BAIL_IF(!_archiver, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1146. BAIL_IF(_archiver->version > maxver, PHYSFS_ERR_UNSUPPORTED, 0);
  1147. BAIL_IF(!_archiver->info.extension, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1148. BAIL_IF(!_archiver->info.description, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1149. BAIL_IF(!_archiver->info.author, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1150. BAIL_IF(!_archiver->info.url, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1151. BAIL_IF(!_archiver->openArchive, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1152. BAIL_IF(!_archiver->enumerate, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1153. BAIL_IF(!_archiver->openRead, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1154. BAIL_IF(!_archiver->openWrite, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1155. BAIL_IF(!_archiver->openAppend, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1156. BAIL_IF(!_archiver->remove, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1157. BAIL_IF(!_archiver->mkdir, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1158. BAIL_IF(!_archiver->closeArchive, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1159. BAIL_IF(!_archiver->stat, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1160. ext = _archiver->info.extension;
  1161. for (i = 0; i < numArchivers; i++)
  1162. {
  1163. if (PHYSFS_utf8stricmp(archiveInfo[i]->extension, ext) == 0)
  1164. BAIL(PHYSFS_ERR_DUPLICATE, 0);
  1165. } /* for */
  1166. /* make a copy of the data. */
  1167. archiver = (PHYSFS_Archiver *) allocator.Malloc(sizeof (*archiver));
  1168. GOTO_IF(!archiver, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1169. /* Must copy sizeof (OLD_VERSION_OF_STRUCT) when version changes! */
  1170. memcpy(archiver, _archiver, sizeof (*archiver));
  1171. info = (PHYSFS_ArchiveInfo *) &archiver->info;
  1172. memset(info, '\0', sizeof (*info)); /* NULL in case an alloc fails. */
  1173. #define CPYSTR(item) \
  1174. info->item = __PHYSFS_strdup(_archiver->info.item); \
  1175. GOTO_IF(!info->item, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1176. CPYSTR(extension);
  1177. CPYSTR(description);
  1178. CPYSTR(author);
  1179. CPYSTR(url);
  1180. info->supportsSymlinks = _archiver->info.supportsSymlinks;
  1181. #undef CPYSTR
  1182. ptr = allocator.Realloc(archiveInfo, len);
  1183. GOTO_IF(!ptr, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1184. archiveInfo = (PHYSFS_ArchiveInfo **) ptr;
  1185. ptr = allocator.Realloc(archivers, len);
  1186. GOTO_IF(!ptr, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1187. archivers = (PHYSFS_Archiver **) ptr;
  1188. archiveInfo[numArchivers] = info;
  1189. archiveInfo[numArchivers + 1] = NULL;
  1190. archivers[numArchivers] = archiver;
  1191. archivers[numArchivers + 1] = NULL;
  1192. numArchivers++;
  1193. return 1;
  1194. regfailed:
  1195. if (info != NULL)
  1196. {
  1197. allocator.Free((void *) info->extension);
  1198. allocator.Free((void *) info->description);
  1199. allocator.Free((void *) info->author);
  1200. allocator.Free((void *) info->url);
  1201. } /* if */
  1202. allocator.Free(archiver);
  1203. return 0;
  1204. } /* doRegisterArchiver */
  1205. int PHYSFS_registerArchiver(const PHYSFS_Archiver *archiver)
  1206. {
  1207. int retval;
  1208. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1209. __PHYSFS_platformGrabMutex(stateLock);
  1210. retval = doRegisterArchiver(archiver);
  1211. __PHYSFS_platformReleaseMutex(stateLock);
  1212. return retval;
  1213. } /* PHYSFS_registerArchiver */
  1214. int PHYSFS_deregisterArchiver(const char *ext)
  1215. {
  1216. size_t i;
  1217. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1218. BAIL_IF(!ext, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1219. __PHYSFS_platformGrabMutex(stateLock);
  1220. for (i = 0; i < numArchivers; i++)
  1221. {
  1222. if (PHYSFS_utf8stricmp(archiveInfo[i]->extension, ext) == 0)
  1223. {
  1224. const int retval = doDeregisterArchiver(i);
  1225. __PHYSFS_platformReleaseMutex(stateLock);
  1226. return retval;
  1227. } /* if */
  1228. } /* for */
  1229. __PHYSFS_platformReleaseMutex(stateLock);
  1230. BAIL(PHYSFS_ERR_NOT_FOUND, 0);
  1231. } /* PHYSFS_deregisterArchiver */
  1232. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  1233. {
  1234. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
  1235. return (const PHYSFS_ArchiveInfo **) archiveInfo;
  1236. } /* PHYSFS_supportedArchiveTypes */
  1237. void PHYSFS_freeList(void *list)
  1238. {
  1239. void **i;
  1240. if (list != NULL)
  1241. {
  1242. for (i = (void **) list; *i != NULL; i++)
  1243. allocator.Free(*i);
  1244. allocator.Free(list);
  1245. } /* if */
  1246. } /* PHYSFS_freeList */
  1247. const char *PHYSFS_getDirSeparator(void)
  1248. {
  1249. static char retval[2] = { __PHYSFS_platformDirSeparator, '\0' };
  1250. return retval;
  1251. } /* PHYSFS_getDirSeparator */
  1252. char **PHYSFS_getCdRomDirs(void)
  1253. {
  1254. return doEnumStringList(__PHYSFS_platformDetectAvailableCDs);
  1255. } /* PHYSFS_getCdRomDirs */
  1256. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  1257. {
  1258. __PHYSFS_platformDetectAvailableCDs(callback, data);
  1259. } /* PHYSFS_getCdRomDirsCallback */
  1260. const char *PHYSFS_getPrefDir(const char *org, const char *app)
  1261. {
  1262. const char dirsep = __PHYSFS_platformDirSeparator;
  1263. PHYSFS_Stat statbuf;
  1264. char *ptr = NULL;
  1265. char *endstr = NULL;
  1266. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1267. BAIL_IF(!org, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1268. BAIL_IF(*org == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1269. BAIL_IF(!app, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1270. BAIL_IF(*app == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1271. allocator.Free(prefDir);
  1272. prefDir = __PHYSFS_platformCalcPrefDir(org, app);
  1273. BAIL_IF_ERRPASS(!prefDir, NULL);
  1274. assert(strlen(prefDir) > 0);
  1275. endstr = prefDir + (strlen(prefDir) - 1);
  1276. assert(*endstr == dirsep);
  1277. *endstr = '\0'; /* mask out the final dirsep for now. */
  1278. if (!__PHYSFS_platformStat(prefDir, &statbuf))
  1279. {
  1280. for (ptr = strchr(prefDir, dirsep); ptr; ptr = strchr(ptr+1, dirsep))
  1281. {
  1282. *ptr = '\0';
  1283. __PHYSFS_platformMkDir(prefDir);
  1284. *ptr = dirsep;
  1285. } /* for */
  1286. if (!__PHYSFS_platformMkDir(prefDir))
  1287. {
  1288. allocator.Free(prefDir);
  1289. prefDir = NULL;
  1290. } /* if */
  1291. } /* if */
  1292. *endstr = dirsep; /* readd the final dirsep. */
  1293. return prefDir;
  1294. } /* PHYSFS_getPrefDir */
  1295. const char *PHYSFS_getBaseDir(void)
  1296. {
  1297. return baseDir; /* this is calculated in PHYSFS_init()... */
  1298. } /* PHYSFS_getBaseDir */
  1299. const char *__PHYSFS_getUserDir(void) /* not deprecated internal version. */
  1300. {
  1301. return userDir; /* this is calculated in PHYSFS_init()... */
  1302. } /* __PHYSFS_getUserDir */
  1303. const char *PHYSFS_getUserDir(void)
  1304. {
  1305. return __PHYSFS_getUserDir();
  1306. } /* PHYSFS_getUserDir */
  1307. const char *PHYSFS_getWriteDir(void)
  1308. {
  1309. const char *retval = NULL;
  1310. __PHYSFS_platformGrabMutex(stateLock);
  1311. if (writeDir != NULL)
  1312. retval = writeDir->dirName;
  1313. __PHYSFS_platformReleaseMutex(stateLock);
  1314. return retval;
  1315. } /* PHYSFS_getWriteDir */
  1316. int PHYSFS_setWriteDir(const char *newDir)
  1317. {
  1318. int retval = 1;
  1319. __PHYSFS_platformGrabMutex(stateLock);
  1320. if (writeDir != NULL)
  1321. {
  1322. BAIL_IF_MUTEX_ERRPASS(!freeDirHandle(writeDir, openWriteList),
  1323. stateLock, 0);
  1324. writeDir = NULL;
  1325. } /* if */
  1326. if (newDir != NULL)
  1327. {
  1328. writeDir = createDirHandle(NULL, newDir, NULL, 1);
  1329. retval = (writeDir != NULL);
  1330. } /* if */
  1331. __PHYSFS_platformReleaseMutex(stateLock);
  1332. return retval;
  1333. } /* PHYSFS_setWriteDir */
  1334. static int doMount(PHYSFS_Io *io, const char *fname,
  1335. const char *mountPoint, int appendToPath)
  1336. {
  1337. DirHandle *dh;
  1338. DirHandle *prev = NULL;
  1339. DirHandle *i;
  1340. if (mountPoint == NULL)
  1341. mountPoint = "/";
  1342. __PHYSFS_platformGrabMutex(stateLock);
  1343. if (fname != NULL)
  1344. {
  1345. for (i = searchPath; i != NULL; i = i->next)
  1346. {
  1347. /* already in search path? */
  1348. if ((i->dirName != NULL) && (strcmp(fname, i->dirName) == 0))
  1349. BAIL_MUTEX_ERRPASS(stateLock, 1);
  1350. prev = i;
  1351. } /* for */
  1352. } /* if */
  1353. dh = createDirHandle(io, fname, mountPoint, 0);
  1354. BAIL_IF_MUTEX_ERRPASS(!dh, stateLock, 0);
  1355. if (appendToPath)
  1356. {
  1357. if (prev == NULL)
  1358. searchPath = dh;
  1359. else
  1360. prev->next = dh;
  1361. } /* if */
  1362. else
  1363. {
  1364. dh->next = searchPath;
  1365. searchPath = dh;
  1366. } /* else */
  1367. __PHYSFS_platformReleaseMutex(stateLock);
  1368. return 1;
  1369. } /* doMount */
  1370. int PHYSFS_mountIo(PHYSFS_Io *io, const char *fname,
  1371. const char *mountPoint, int appendToPath)
  1372. {
  1373. BAIL_IF(!io, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1374. BAIL_IF(io->version != 0, PHYSFS_ERR_UNSUPPORTED, 0);
  1375. return doMount(io, fname, mountPoint, appendToPath);
  1376. } /* PHYSFS_mountIo */
  1377. int PHYSFS_mountMemory(const void *buf, PHYSFS_uint64 len, void (*del)(void *),
  1378. const char *fname, const char *mountPoint,
  1379. int appendToPath)
  1380. {
  1381. int retval = 0;
  1382. PHYSFS_Io *io = NULL;
  1383. BAIL_IF(!buf, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1384. io = __PHYSFS_createMemoryIo(buf, len, del);
  1385. BAIL_IF_ERRPASS(!io, 0);
  1386. retval = doMount(io, fname, mountPoint, appendToPath);
  1387. if (!retval)
  1388. {
  1389. /* docs say not to call (del) in case of failure, so cheat. */
  1390. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  1391. info->destruct = NULL;
  1392. io->destroy(io);
  1393. } /* if */
  1394. return retval;
  1395. } /* PHYSFS_mountMemory */
  1396. int PHYSFS_mountHandle(PHYSFS_File *file, const char *fname,
  1397. const char *mountPoint, int appendToPath)
  1398. {
  1399. int retval = 0;
  1400. PHYSFS_Io *io = NULL;
  1401. BAIL_IF(file == NULL, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1402. io = __PHYSFS_createHandleIo(file);
  1403. BAIL_IF_ERRPASS(!io, 0);
  1404. retval = doMount(io, fname, mountPoint, appendToPath);
  1405. if (!retval)
  1406. {
  1407. /* docs say not to destruct in case of failure, so cheat. */
  1408. io->opaque = NULL;
  1409. io->destroy(io);
  1410. } /* if */
  1411. return retval;
  1412. } /* PHYSFS_mountHandle */
  1413. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  1414. {
  1415. BAIL_IF(!newDir, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1416. return doMount(NULL, newDir, mountPoint, appendToPath);
  1417. } /* PHYSFS_mount */
  1418. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  1419. {
  1420. return doMount(NULL, newDir, NULL, appendToPath);
  1421. } /* PHYSFS_addToSearchPath */
  1422. int PHYSFS_removeFromSearchPath(const char *oldDir)
  1423. {
  1424. return PHYSFS_unmount(oldDir);
  1425. } /* PHYSFS_removeFromSearchPath */
  1426. int PHYSFS_unmount(const char *oldDir)
  1427. {
  1428. DirHandle *i;
  1429. DirHandle *prev = NULL;
  1430. DirHandle *next = NULL;
  1431. BAIL_IF(oldDir == NULL, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1432. __PHYSFS_platformGrabMutex(stateLock);
  1433. for (i = searchPath; i != NULL; i = i->next)
  1434. {
  1435. if (strcmp(i->dirName, oldDir) == 0)
  1436. {
  1437. next = i->next;
  1438. BAIL_IF_MUTEX_ERRPASS(!freeDirHandle(i, openReadList),
  1439. stateLock, 0);
  1440. if (prev == NULL)
  1441. searchPath = next;
  1442. else
  1443. prev->next = next;
  1444. BAIL_MUTEX_ERRPASS(stateLock, 1);
  1445. } /* if */
  1446. prev = i;
  1447. } /* for */
  1448. BAIL_MUTEX(PHYSFS_ERR_NOT_MOUNTED, stateLock, 0);
  1449. } /* PHYSFS_unmount */
  1450. char **PHYSFS_getSearchPath(void)
  1451. {
  1452. return doEnumStringList(PHYSFS_getSearchPathCallback);
  1453. } /* PHYSFS_getSearchPath */
  1454. const char *PHYSFS_getMountPoint(const char *dir)
  1455. {
  1456. DirHandle *i;
  1457. __PHYSFS_platformGrabMutex(stateLock);
  1458. for (i = searchPath; i != NULL; i = i->next)
  1459. {
  1460. if (strcmp(i->dirName, dir) == 0)
  1461. {
  1462. const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
  1463. __PHYSFS_platformReleaseMutex(stateLock);
  1464. return retval;
  1465. } /* if */
  1466. } /* for */
  1467. __PHYSFS_platformReleaseMutex(stateLock);
  1468. BAIL(PHYSFS_ERR_NOT_MOUNTED, NULL);
  1469. } /* PHYSFS_getMountPoint */
  1470. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  1471. {
  1472. DirHandle *i;
  1473. __PHYSFS_platformGrabMutex(stateLock);
  1474. for (i = searchPath; i != NULL; i = i->next)
  1475. callback(data, i->dirName);
  1476. __PHYSFS_platformReleaseMutex(stateLock);
  1477. } /* PHYSFS_getSearchPathCallback */
  1478. /* Split out to avoid stack allocation in a loop. */
  1479. static void setSaneCfgAddPath(const char *i, const size_t l, const char *dirsep,
  1480. int archivesFirst)
  1481. {
  1482. const char *d = PHYSFS_getRealDir(i);
  1483. const size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
  1484. char *str = (char *) __PHYSFS_smallAlloc(allocsize);
  1485. if (str != NULL)
  1486. {
  1487. snprintf(str, allocsize, "%s%s%s", d, dirsep, i);
  1488. PHYSFS_mount(str, NULL, archivesFirst == 0);
  1489. __PHYSFS_smallFree(str);
  1490. } /* if */
  1491. } /* setSaneCfgAddPath */
  1492. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  1493. const char *archiveExt, int includeCdRoms,
  1494. int archivesFirst)
  1495. {
  1496. const char *dirsep = PHYSFS_getDirSeparator();
  1497. const char *basedir;
  1498. const char *prefdir;
  1499. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1500. prefdir = PHYSFS_getPrefDir(organization, appName);
  1501. BAIL_IF_ERRPASS(!prefdir, 0);
  1502. basedir = PHYSFS_getBaseDir();
  1503. BAIL_IF_ERRPASS(!basedir, 0);
  1504. BAIL_IF(!PHYSFS_setWriteDir(prefdir), PHYSFS_ERR_NO_WRITE_DIR, 0);
  1505. /* Put write dir first in search path... */
  1506. PHYSFS_mount(prefdir, NULL, 0);
  1507. /* Put base path on search path... */
  1508. PHYSFS_mount(basedir, NULL, 1);
  1509. /* handle CD-ROMs... */
  1510. if (includeCdRoms)
  1511. {
  1512. char **cds = PHYSFS_getCdRomDirs();
  1513. char **i;
  1514. for (i = cds; *i != NULL; i++)
  1515. PHYSFS_mount(*i, NULL, 1);
  1516. PHYSFS_freeList(cds);
  1517. } /* if */
  1518. /* Root out archives, and add them to search path... */
  1519. if (archiveExt != NULL)
  1520. {
  1521. /* !!! FIXME-3.0: turn this into a callback */
  1522. char **rc = PHYSFS_enumerateFiles("/");
  1523. char **i;
  1524. size_t extlen = strlen(archiveExt);
  1525. char *ext;
  1526. for (i = rc; *i != NULL; i++)
  1527. {
  1528. size_t l = strlen(*i);
  1529. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  1530. {
  1531. ext = (*i) + (l - extlen);
  1532. if (PHYSFS_utf8stricmp(ext, archiveExt) == 0)
  1533. setSaneCfgAddPath(*i, l, dirsep, archivesFirst);
  1534. } /* if */
  1535. } /* for */
  1536. PHYSFS_freeList(rc);
  1537. } /* if */
  1538. return 1;
  1539. } /* PHYSFS_setSaneConfig */
  1540. void PHYSFS_permitSymbolicLinks(int allow)
  1541. {
  1542. allowSymLinks = allow;
  1543. } /* PHYSFS_permitSymbolicLinks */
  1544. int PHYSFS_symbolicLinksPermitted(void)
  1545. {
  1546. return allowSymLinks;
  1547. } /* PHYSFS_symbolicLinksPermitted */
  1548. /*
  1549. * Verify that (fname) (in platform-independent notation), in relation
  1550. * to (h) is secure. That means that each element of fname is checked
  1551. * for symlinks (if they aren't permitted). This also allows for quick
  1552. * rejection of files that exist outside an archive's mountpoint.
  1553. *
  1554. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  1555. * at a time), you should always pass zero for "allowMissing" for efficiency.
  1556. *
  1557. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  1558. * since it will make sure that path names are in the right format for
  1559. * passing certain checks. It will also do checks for "insecure" pathnames
  1560. * like ".." which should be done once instead of once per archive. This also
  1561. * gives us license to treat (fname) as scratch space in this function.
  1562. *
  1563. * Returns non-zero if string is safe, zero if there's a security issue.
  1564. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  1565. * updated to point past any mount point elements so it is prepared to
  1566. * be used with the archiver directly.
  1567. */
  1568. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1569. {
  1570. char *fname = *_fname;
  1571. int retval = 1;
  1572. char *start;
  1573. char *end;
  1574. if (*fname == '\0') /* quick rejection. */
  1575. return 1;
  1576. /* !!! FIXME: This codeblock sucks. */
  1577. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1578. {
  1579. size_t mntpntlen = strlen(h->mountPoint);
  1580. size_t len = strlen(fname);
  1581. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1582. /* not under the mountpoint, so skip this archive. */
  1583. BAIL_IF(len < mntpntlen-1, PHYSFS_ERR_NOT_FOUND, 0);
  1584. /* !!! FIXME: Case insensitive? */
  1585. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1586. BAIL_IF(retval != 0, PHYSFS_ERR_NOT_FOUND, 0);
  1587. if (len > mntpntlen-1) /* corner case... */
  1588. BAIL_IF(fname[mntpntlen-1]!='/', PHYSFS_ERR_NOT_FOUND, 0);
  1589. fname += mntpntlen-1; /* move to start of actual archive path. */
  1590. if (*fname == '/')
  1591. fname++;
  1592. *_fname = fname; /* skip mountpoint for later use. */
  1593. retval = 1; /* may be reset, below. */
  1594. } /* if */
  1595. start = fname;
  1596. if (!allowSymLinks)
  1597. {
  1598. while (1)
  1599. {
  1600. PHYSFS_Stat statbuf;
  1601. int rc = 0;
  1602. end = strchr(start, '/');
  1603. if (end != NULL) *end = '\0';
  1604. rc = h->funcs->stat(h->opaque, fname, &statbuf);
  1605. if (rc)
  1606. rc = (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  1607. else if (currentErrorCode() == PHYSFS_ERR_NOT_FOUND)
  1608. retval = 0;
  1609. if (end != NULL) *end = '/';
  1610. /* insecure path (has a disallowed symlink in it)? */
  1611. BAIL_IF(rc, PHYSFS_ERR_SYMLINK_FORBIDDEN, 0);
  1612. /* break out early if path element is missing. */
  1613. if (!retval)
  1614. {
  1615. /*
  1616. * We need to clear it if it's the last element of the path,
  1617. * since this might be a non-existant file we're opening
  1618. * for writing...
  1619. */
  1620. if ((end == NULL) || (allowMissing))
  1621. retval = 1;
  1622. break;
  1623. } /* if */
  1624. if (end == NULL)
  1625. break;
  1626. start = end + 1;
  1627. } /* while */
  1628. } /* if */
  1629. return retval;
  1630. } /* verifyPath */
  1631. static int doMkdir(const char *_dname, char *dname)
  1632. {
  1633. DirHandle *h;
  1634. char *start;
  1635. char *end;
  1636. int retval = 0;
  1637. int exists = 1; /* force existance check on first path element. */
  1638. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPath(_dname, dname), 0);
  1639. __PHYSFS_platformGrabMutex(stateLock);
  1640. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1641. h = writeDir;
  1642. BAIL_IF_MUTEX_ERRPASS(!verifyPath(h, &dname, 1), stateLock, 0);
  1643. start = dname;
  1644. while (1)
  1645. {
  1646. end = strchr(start, '/');
  1647. if (end != NULL)
  1648. *end = '\0';
  1649. /* only check for existance if all parent dirs existed, too... */
  1650. if (exists)
  1651. {
  1652. PHYSFS_Stat statbuf;
  1653. const int rc = h->funcs->stat(h->opaque, dname, &statbuf);
  1654. if ((!rc) && (currentErrorCode() == PHYSFS_ERR_NOT_FOUND))
  1655. exists = 0;
  1656. retval = ((rc) && (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY));
  1657. } /* if */
  1658. if (!exists)
  1659. retval = h->funcs->mkdir(h->opaque, dname);
  1660. if (!retval)
  1661. break;
  1662. if (end == NULL)
  1663. break;
  1664. *end = '/';
  1665. start = end + 1;
  1666. } /* while */
  1667. __PHYSFS_platformReleaseMutex(stateLock);
  1668. return retval;
  1669. } /* doMkdir */
  1670. int PHYSFS_mkdir(const char *_dname)
  1671. {
  1672. int retval = 0;
  1673. char *dname;
  1674. size_t len;
  1675. BAIL_IF(!_dname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1676. len = strlen(_dname) + 1;
  1677. dname = (char *) __PHYSFS_smallAlloc(len);
  1678. BAIL_IF(!dname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1679. retval = doMkdir(_dname, dname);
  1680. __PHYSFS_smallFree(dname);
  1681. return retval;
  1682. } /* PHYSFS_mkdir */
  1683. static int doDelete(const char *_fname, char *fname)
  1684. {
  1685. int retval;
  1686. DirHandle *h;
  1687. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPath(_fname, fname), 0);
  1688. __PHYSFS_platformGrabMutex(stateLock);
  1689. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1690. h = writeDir;
  1691. BAIL_IF_MUTEX_ERRPASS(!verifyPath(h, &fname, 0), stateLock, 0);
  1692. retval = h->funcs->remove(h->opaque, fname);
  1693. __PHYSFS_platformReleaseMutex(stateLock);
  1694. return retval;
  1695. } /* doDelete */
  1696. int PHYSFS_delete(const char *_fname)
  1697. {
  1698. int retval;
  1699. char *fname;
  1700. size_t len;
  1701. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1702. len = strlen(_fname) + 1;
  1703. fname = (char *) __PHYSFS_smallAlloc(len);
  1704. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1705. retval = doDelete(_fname, fname);
  1706. __PHYSFS_smallFree(fname);
  1707. return retval;
  1708. } /* PHYSFS_delete */
  1709. const char *PHYSFS_getRealDir(const char *_fname)
  1710. {
  1711. const char *retval = NULL;
  1712. char *fname = NULL;
  1713. size_t len;
  1714. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1715. len = strlen(_fname) + 1;
  1716. fname = __PHYSFS_smallAlloc(len);
  1717. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  1718. if (sanitizePlatformIndependentPath(_fname, fname))
  1719. {
  1720. DirHandle *i;
  1721. __PHYSFS_platformGrabMutex(stateLock);
  1722. for (i = searchPath; i != NULL; i = i->next)
  1723. {
  1724. char *arcfname = fname;
  1725. if (partOfMountPoint(i, arcfname))
  1726. {
  1727. retval = i->dirName;
  1728. break;
  1729. } /* if */
  1730. else if (verifyPath(i, &arcfname, 0))
  1731. {
  1732. PHYSFS_Stat statbuf;
  1733. if (i->funcs->stat(i->opaque, arcfname, &statbuf))
  1734. {
  1735. retval = i->dirName;
  1736. break;
  1737. } /* if */
  1738. } /* if */
  1739. } /* for */
  1740. __PHYSFS_platformReleaseMutex(stateLock);
  1741. } /* if */
  1742. __PHYSFS_smallFree(fname);
  1743. return retval;
  1744. } /* PHYSFS_getRealDir */
  1745. static int locateInStringList(const char *str,
  1746. char **list,
  1747. PHYSFS_uint32 *pos)
  1748. {
  1749. PHYSFS_uint32 len = *pos;
  1750. PHYSFS_uint32 half_len;
  1751. PHYSFS_uint32 lo = 0;
  1752. PHYSFS_uint32 middle;
  1753. int cmp;
  1754. while (len > 0)
  1755. {
  1756. half_len = len >> 1;
  1757. middle = lo + half_len;
  1758. cmp = strcmp(list[middle], str);
  1759. if (cmp == 0) /* it's in the list already. */
  1760. return 1;
  1761. else if (cmp > 0)
  1762. len = half_len;
  1763. else
  1764. {
  1765. lo = middle + 1;
  1766. len -= half_len + 1;
  1767. } /* else */
  1768. } /* while */
  1769. *pos = lo;
  1770. return 0;
  1771. } /* locateInStringList */
  1772. static int enumFilesCallback(void *data, const char *origdir, const char *str)
  1773. {
  1774. PHYSFS_uint32 pos;
  1775. void *ptr;
  1776. char *newstr;
  1777. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1778. /*
  1779. * See if file is in the list already, and if not, insert it in there
  1780. * alphabetically...
  1781. */
  1782. pos = pecd->size;
  1783. if (locateInStringList(str, pecd->list, &pos))
  1784. return 1; /* already in the list, but keep going. */
  1785. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1786. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1787. if (ptr != NULL)
  1788. pecd->list = (char **) ptr;
  1789. if ((ptr == NULL) || (newstr == NULL))
  1790. {
  1791. if (newstr)
  1792. allocator.Free(newstr);
  1793. pecd->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1794. return -1; /* better luck next time. */
  1795. } /* if */
  1796. strcpy(newstr, str);
  1797. if (pos != pecd->size)
  1798. {
  1799. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1800. sizeof (char *) * ((pecd->size) - pos));
  1801. } /* if */
  1802. pecd->list[pos] = newstr;
  1803. pecd->size++;
  1804. return 1;
  1805. } /* enumFilesCallback */
  1806. char **PHYSFS_enumerateFiles(const char *path)
  1807. {
  1808. EnumStringListCallbackData ecd;
  1809. memset(&ecd, '\0', sizeof (ecd));
  1810. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1811. BAIL_IF(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  1812. if (!PHYSFS_enumerate(path, enumFilesCallback, &ecd))
  1813. {
  1814. const PHYSFS_ErrorCode errcode = currentErrorCode();
  1815. PHYSFS_uint32 i;
  1816. for (i = 0; i < ecd.size; i++)
  1817. allocator.Free(ecd.list[i]);
  1818. allocator.Free(ecd.list);
  1819. BAIL_IF(errcode == PHYSFS_ERR_APP_CALLBACK, ecd.errcode, NULL);
  1820. return NULL;
  1821. } /* if */
  1822. ecd.list[ecd.size] = NULL;
  1823. return ecd.list;
  1824. } /* PHYSFS_enumerateFiles */
  1825. /*
  1826. * Broke out to seperate function so we can use stack allocation gratuitously.
  1827. */
  1828. static int enumerateFromMountPoint(DirHandle *i, const char *arcfname,
  1829. PHYSFS_EnumerateCallback callback,
  1830. const char *_fname, void *data)
  1831. {
  1832. const size_t len = strlen(arcfname);
  1833. char *ptr = NULL;
  1834. char *end = NULL;
  1835. const size_t slen = strlen(i->mountPoint) + 1;
  1836. char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
  1837. int rc;
  1838. BAIL_IF(!mountPoint, PHYSFS_ERR_OUT_OF_MEMORY, -1);
  1839. strcpy(mountPoint, i->mountPoint);
  1840. ptr = mountPoint + ((len) ? len + 1 : 0);
  1841. end = strchr(ptr, '/');
  1842. assert(end); /* should always find a terminating '/'. */
  1843. *end = '\0';
  1844. rc = callback(data, _fname, ptr);
  1845. __PHYSFS_smallFree(mountPoint);
  1846. BAIL_IF(rc == -1, PHYSFS_ERR_APP_CALLBACK, -1);
  1847. return rc;
  1848. } /* enumerateFromMountPoint */
  1849. typedef struct SymlinkFilterData
  1850. {
  1851. PHYSFS_EnumerateCallback callback;
  1852. void *callbackData;
  1853. DirHandle *dirhandle;
  1854. PHYSFS_ErrorCode errcode;
  1855. } SymlinkFilterData;
  1856. /* !!! FIXME-3.0: broken if in a virtual mountpoint (stat call fails). */
  1857. static int enumCallbackFilterSymLinks(void *_data, const char *origdir,
  1858. const char *fname)
  1859. {
  1860. SymlinkFilterData *data = (SymlinkFilterData *) _data;
  1861. const DirHandle *dh = data->dirhandle;
  1862. PHYSFS_Stat statbuf;
  1863. const char *trimmedDir = (*origdir == '/') ? (origdir+1) : origdir;
  1864. const size_t slen = strlen(trimmedDir) + strlen(fname) + 2;
  1865. char *path = (char *) __PHYSFS_smallAlloc(slen);
  1866. int retval = 1;
  1867. if (path == NULL)
  1868. {
  1869. data->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1870. return -1;
  1871. } /* if */
  1872. snprintf(path, slen, "%s%s%s", trimmedDir, *trimmedDir ? "/" : "", fname);
  1873. if (!dh->funcs->stat(dh->opaque, path, &statbuf))
  1874. {
  1875. data->errcode = currentErrorCode();
  1876. retval = -1;
  1877. } /* if */
  1878. else
  1879. {
  1880. /* Pass it on to the application if it's not a symlink. */
  1881. if (statbuf.filetype != PHYSFS_FILETYPE_SYMLINK)
  1882. {
  1883. retval = data->callback(data->callbackData, origdir, fname);
  1884. if (retval == -1)
  1885. data->errcode = PHYSFS_ERR_APP_CALLBACK;
  1886. } /* if */
  1887. } /* else */
  1888. __PHYSFS_smallFree(path);
  1889. return retval;
  1890. } /* enumCallbackFilterSymLinks */
  1891. int PHYSFS_enumerate(const char *_fn, PHYSFS_EnumerateCallback cb, void *data)
  1892. {
  1893. int retval = 1;
  1894. size_t len;
  1895. char *fname;
  1896. BAIL_IF(!_fn, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1897. BAIL_IF(!cb, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1898. len = strlen(_fn) + 1;
  1899. fname = (char *) __PHYSFS_smallAlloc(len);
  1900. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1901. if (!sanitizePlatformIndependentPath(_fn, fname))
  1902. retval = 0;
  1903. else
  1904. {
  1905. DirHandle *i;
  1906. SymlinkFilterData filterdata;
  1907. __PHYSFS_platformGrabMutex(stateLock);
  1908. if (!allowSymLinks)
  1909. {
  1910. memset(&filterdata, '\0', sizeof (filterdata));
  1911. filterdata.callback = cb;
  1912. filterdata.callbackData = data;
  1913. } /* if */
  1914. for (i = searchPath; (retval > 0) && (i != NULL); i = i->next)
  1915. {
  1916. char *arcfname = fname;
  1917. if (partOfMountPoint(i, arcfname))
  1918. retval = enumerateFromMountPoint(i, arcfname, cb, _fn, data);
  1919. else if (verifyPath(i, &arcfname, 0))
  1920. {
  1921. if ((!allowSymLinks) && (i->funcs->info.supportsSymlinks))
  1922. {
  1923. filterdata.dirhandle = i;
  1924. filterdata.errcode = PHYSFS_ERR_OK;
  1925. retval = i->funcs->enumerate(i->opaque, arcfname,
  1926. enumCallbackFilterSymLinks,
  1927. _fn, &filterdata);
  1928. if (retval == -1)
  1929. {
  1930. if (currentErrorCode() == PHYSFS_ERR_APP_CALLBACK)
  1931. PHYSFS_setErrorCode(filterdata.errcode);
  1932. } /* if */
  1933. } /* if */
  1934. else
  1935. {
  1936. retval = i->funcs->enumerate(i->opaque, arcfname,
  1937. cb, _fn, data);
  1938. } /* else */
  1939. } /* else if */
  1940. } /* for */
  1941. __PHYSFS_platformReleaseMutex(stateLock);
  1942. } /* if */
  1943. __PHYSFS_smallFree(fname);
  1944. return (retval < 0) ? 0 : 1;
  1945. } /* PHYSFS_enumerate */
  1946. typedef struct
  1947. {
  1948. PHYSFS_EnumFilesCallback callback;
  1949. void *data;
  1950. } LegacyEnumFilesCallbackData;
  1951. static int enumFilesCallbackAlwaysSucceed(void *data, const char *origdir,
  1952. const char *fname)
  1953. {
  1954. LegacyEnumFilesCallbackData *cbdata = (LegacyEnumFilesCallbackData *) data;
  1955. cbdata->callback(cbdata->data, origdir, fname);
  1956. return 1;
  1957. } /* enumFilesCallbackAlwaysSucceed */
  1958. void PHYSFS_enumerateFilesCallback(const char *fname,
  1959. PHYSFS_EnumFilesCallback callback,
  1960. void *data)
  1961. {
  1962. LegacyEnumFilesCallbackData cbdata = { callback, data };
  1963. (void) PHYSFS_enumerate(fname, enumFilesCallbackAlwaysSucceed, &cbdata);
  1964. } /* PHYSFS_enumerateFilesCallback */
  1965. int PHYSFS_exists(const char *fname)
  1966. {
  1967. return (PHYSFS_getRealDir(fname) != NULL);
  1968. } /* PHYSFS_exists */
  1969. PHYSFS_sint64 PHYSFS_getLastModTime(const char *fname)
  1970. {
  1971. PHYSFS_Stat statbuf;
  1972. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), -1);
  1973. return statbuf.modtime;
  1974. } /* PHYSFS_getLastModTime */
  1975. int PHYSFS_isDirectory(const char *fname)
  1976. {
  1977. PHYSFS_Stat statbuf;
  1978. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  1979. return (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY);
  1980. } /* PHYSFS_isDirectory */
  1981. int PHYSFS_isSymbolicLink(const char *fname)
  1982. {
  1983. PHYSFS_Stat statbuf;
  1984. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  1985. return (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  1986. } /* PHYSFS_isSymbolicLink */
  1987. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1988. {
  1989. FileHandle *fh = NULL;
  1990. size_t len;
  1991. char *fname;
  1992. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1993. len = strlen(_fname) + 1;
  1994. fname = (char *) __PHYSFS_smallAlloc(len);
  1995. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1996. if (sanitizePlatformIndependentPath(_fname, fname))
  1997. {
  1998. PHYSFS_Io *io = NULL;
  1999. DirHandle *h = NULL;
  2000. const PHYSFS_Archiver *f;
  2001. __PHYSFS_platformGrabMutex(stateLock);
  2002. GOTO_IF(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, doOpenWriteEnd);
  2003. h = writeDir;
  2004. GOTO_IF_ERRPASS(!verifyPath(h, &fname, 0), doOpenWriteEnd);
  2005. f = h->funcs;
  2006. if (appending)
  2007. io = f->openAppend(h->opaque, fname);
  2008. else
  2009. io = f->openWrite(h->opaque, fname);
  2010. GOTO_IF_ERRPASS(!io, doOpenWriteEnd);
  2011. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  2012. if (fh == NULL)
  2013. {
  2014. io->destroy(io);
  2015. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, doOpenWriteEnd);
  2016. } /* if */
  2017. else
  2018. {
  2019. memset(fh, '\0', sizeof (FileHandle));
  2020. fh->io = io;
  2021. fh->dirHandle = h;
  2022. fh->next = openWriteList;
  2023. openWriteList = fh;
  2024. } /* else */
  2025. doOpenWriteEnd:
  2026. __PHYSFS_platformReleaseMutex(stateLock);
  2027. } /* if */
  2028. __PHYSFS_smallFree(fname);
  2029. return ((PHYSFS_File *) fh);
  2030. } /* doOpenWrite */
  2031. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  2032. {
  2033. return doOpenWrite(filename, 0);
  2034. } /* PHYSFS_openWrite */
  2035. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  2036. {
  2037. return doOpenWrite(filename, 1);
  2038. } /* PHYSFS_openAppend */
  2039. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  2040. {
  2041. FileHandle *fh = NULL;
  2042. char *fname;
  2043. size_t len;
  2044. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2045. len = strlen(_fname) + 1;
  2046. fname = (char *) __PHYSFS_smallAlloc(len);
  2047. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2048. if (sanitizePlatformIndependentPath(_fname, fname))
  2049. {
  2050. DirHandle *i = NULL;
  2051. PHYSFS_Io *io = NULL;
  2052. __PHYSFS_platformGrabMutex(stateLock);
  2053. GOTO_IF(!searchPath, PHYSFS_ERR_NOT_FOUND, openReadEnd);
  2054. for (i = searchPath; i != NULL; i = i->next)
  2055. {
  2056. char *arcfname = fname;
  2057. if (verifyPath(i, &arcfname, 0))
  2058. {
  2059. io = i->funcs->openRead(i->opaque, arcfname);
  2060. if (io)
  2061. break;
  2062. } /* if */
  2063. } /* for */
  2064. GOTO_IF_ERRPASS(!io, openReadEnd);
  2065. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  2066. if (fh == NULL)
  2067. {
  2068. io->destroy(io);
  2069. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, openReadEnd);
  2070. } /* if */
  2071. memset(fh, '\0', sizeof (FileHandle));
  2072. fh->io = io;
  2073. fh->forReading = 1;
  2074. fh->dirHandle = i;
  2075. fh->next = openReadList;
  2076. openReadList = fh;
  2077. openReadEnd:
  2078. __PHYSFS_platformReleaseMutex(stateLock);
  2079. } /* if */
  2080. __PHYSFS_smallFree(fname);
  2081. return ((PHYSFS_File *) fh);
  2082. } /* PHYSFS_openRead */
  2083. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  2084. {
  2085. FileHandle *prev = NULL;
  2086. FileHandle *i;
  2087. int rc = 1;
  2088. for (i = *list; i != NULL; i = i->next)
  2089. {
  2090. if (i == handle) /* handle is in this list? */
  2091. {
  2092. PHYSFS_Io *io = handle->io;
  2093. PHYSFS_uint8 *tmp = handle->buffer;
  2094. rc = PHYSFS_flush((PHYSFS_File *) handle);
  2095. if (!rc)
  2096. return -1;
  2097. io->destroy(io);
  2098. if (tmp != NULL) /* free any associated buffer. */
  2099. allocator.Free(tmp);
  2100. if (prev == NULL)
  2101. *list = handle->next;
  2102. else
  2103. prev->next = handle->next;
  2104. allocator.Free(handle);
  2105. return 1;
  2106. } /* if */
  2107. prev = i;
  2108. } /* for */
  2109. return 0;
  2110. } /* closeHandleInOpenList */
  2111. int PHYSFS_close(PHYSFS_File *_handle)
  2112. {
  2113. FileHandle *handle = (FileHandle *) _handle;
  2114. int rc;
  2115. __PHYSFS_platformGrabMutex(stateLock);
  2116. /* -1 == close failure. 0 == not found. 1 == success. */
  2117. rc = closeHandleInOpenList(&openReadList, handle);
  2118. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2119. if (!rc)
  2120. {
  2121. rc = closeHandleInOpenList(&openWriteList, handle);
  2122. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2123. } /* if */
  2124. __PHYSFS_platformReleaseMutex(stateLock);
  2125. BAIL_IF(!rc, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2126. return 1;
  2127. } /* PHYSFS_close */
  2128. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer, size_t len)
  2129. {
  2130. PHYSFS_Io *io = NULL;
  2131. PHYSFS_sint64 retval = 0;
  2132. size_t buffered = 0;
  2133. PHYSFS_sint64 rc = 0;
  2134. if (len == 0)
  2135. return 0;
  2136. buffered = fh->buffill - fh->bufpos;
  2137. if (buffered >= len) /* totally in the buffer, just copy and return! */
  2138. {
  2139. memcpy(buffer, fh->buffer + fh->bufpos, len);
  2140. fh->bufpos += len;
  2141. return (PHYSFS_sint64) len;
  2142. } /* if */
  2143. else if (buffered > 0) /* partially in the buffer... */
  2144. {
  2145. memcpy(buffer, fh->buffer + fh->bufpos, buffered);
  2146. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  2147. len -= buffered;
  2148. retval = (PHYSFS_sint64) buffered;
  2149. } /* if */
  2150. /* if you got here, the buffer is drained and we still need bytes. */
  2151. assert(len > 0);
  2152. fh->buffill = fh->bufpos = 0;
  2153. io = fh->io;
  2154. if (len >= fh->bufsize) /* need more than the buffer takes. */
  2155. {
  2156. /* leave buffer empty, go right to output instead. */
  2157. rc = io->read(io, buffer, len);
  2158. if (rc < 0)
  2159. return ((retval == 0) ? rc : retval);
  2160. return retval + rc;
  2161. } /* if */
  2162. /* need less than buffer can take. Fill buffer. */
  2163. rc = io->read(io, fh->buffer, fh->bufsize);
  2164. if (rc < 0)
  2165. return ((retval == 0) ? rc : retval);
  2166. assert(fh->bufpos == 0);
  2167. fh->buffill = (size_t) rc;
  2168. rc = doBufferedRead(fh, buffer, len); /* go from the start, again. */
  2169. if (rc < 0)
  2170. return ((retval == 0) ? rc : retval);
  2171. return retval + rc;
  2172. } /* doBufferedRead */
  2173. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  2174. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2175. {
  2176. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2177. const PHYSFS_sint64 retval = PHYSFS_readBytes(handle, buffer, len);
  2178. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2179. } /* PHYSFS_read */
  2180. PHYSFS_sint64 PHYSFS_readBytes(PHYSFS_File *handle, void *buffer,
  2181. PHYSFS_uint64 _len)
  2182. {
  2183. const size_t len = (size_t) _len;
  2184. FileHandle *fh = (FileHandle *) handle;
  2185. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2186. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2187. #else
  2188. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2189. #endif
  2190. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2191. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2192. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2193. BAIL_IF(!fh->forReading, PHYSFS_ERR_OPEN_FOR_WRITING, -1);
  2194. BAIL_IF_ERRPASS(len == 0, 0);
  2195. if (fh->buffer)
  2196. return doBufferedRead(fh, buffer, len);
  2197. return fh->io->read(fh->io, buffer, len);
  2198. } /* PHYSFS_readBytes */
  2199. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  2200. const size_t len)
  2201. {
  2202. FileHandle *fh = (FileHandle *) handle;
  2203. /* whole thing fits in the buffer? */
  2204. if ((fh->buffill + len) < fh->bufsize)
  2205. {
  2206. memcpy(fh->buffer + fh->buffill, buffer, len);
  2207. fh->buffill += len;
  2208. return (PHYSFS_sint64) len;
  2209. } /* if */
  2210. /* would overflow buffer. Flush and then write the new objects, too. */
  2211. /* !!! FIXME-3.0: this should refill the buffer, not flush everything down. */
  2212. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), -1);
  2213. return fh->io->write(fh->io, buffer, len);
  2214. } /* doBufferedWrite */
  2215. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  2216. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2217. {
  2218. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2219. const PHYSFS_sint64 retval = PHYSFS_writeBytes(handle, buffer, len);
  2220. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2221. } /* PHYSFS_write */
  2222. PHYSFS_sint64 PHYSFS_writeBytes(PHYSFS_File *handle, const void *buffer,
  2223. PHYSFS_uint64 _len)
  2224. {
  2225. const size_t len = (size_t) _len;
  2226. FileHandle *fh = (FileHandle *) handle;
  2227. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2228. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2229. #else
  2230. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2231. #endif
  2232. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2233. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2234. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2235. BAIL_IF(fh->forReading, PHYSFS_ERR_OPEN_FOR_READING, -1);
  2236. BAIL_IF_ERRPASS(len == 0, 0);
  2237. if (fh->buffer)
  2238. return doBufferedWrite(handle, buffer, len);
  2239. return fh->io->write(fh->io, buffer, len);
  2240. } /* PHYSFS_write */
  2241. int PHYSFS_eof(PHYSFS_File *handle)
  2242. {
  2243. FileHandle *fh = (FileHandle *) handle;
  2244. if (!fh->forReading) /* never EOF on files opened for write/append. */
  2245. return 0;
  2246. /* can't be eof if buffer isn't empty */
  2247. if (fh->bufpos == fh->buffill)
  2248. {
  2249. /* check the Io. */
  2250. PHYSFS_Io *io = fh->io;
  2251. const PHYSFS_sint64 pos = io->tell(io);
  2252. const PHYSFS_sint64 len = io->length(io);
  2253. if ((pos < 0) || (len < 0))
  2254. return 0; /* beats me. */
  2255. return (pos >= len);
  2256. } /* if */
  2257. return 0;
  2258. } /* PHYSFS_eof */
  2259. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  2260. {
  2261. FileHandle *fh = (FileHandle *) handle;
  2262. const PHYSFS_sint64 pos = fh->io->tell(fh->io);
  2263. const PHYSFS_sint64 retval = fh->forReading ?
  2264. (pos - fh->buffill) + fh->bufpos :
  2265. (pos + fh->buffill);
  2266. return retval;
  2267. } /* PHYSFS_tell */
  2268. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  2269. {
  2270. FileHandle *fh = (FileHandle *) handle;
  2271. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2272. if (fh->buffer && fh->forReading)
  2273. {
  2274. /* avoid throwing away our precious buffer if seeking within it. */
  2275. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  2276. if ( /* seeking within the already-buffered range? */
  2277. /* forward? */
  2278. ((offset >= 0) && (((size_t)offset) <= fh->buffill-fh->bufpos)) ||
  2279. /* backward? */
  2280. ((offset < 0) && (((size_t) -offset) <= fh->bufpos)) )
  2281. {
  2282. fh->bufpos += (PHYSFS_uint32) offset;
  2283. return 1; /* successful seek */
  2284. } /* if */
  2285. } /* if */
  2286. /* we have to fall back to a 'raw' seek. */
  2287. fh->buffill = fh->bufpos = 0;
  2288. return fh->io->seek(fh->io, pos);
  2289. } /* PHYSFS_seek */
  2290. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  2291. {
  2292. PHYSFS_Io *io = ((FileHandle *) handle)->io;
  2293. return io->length(io);
  2294. } /* PHYSFS_filelength */
  2295. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  2296. {
  2297. FileHandle *fh = (FileHandle *) handle;
  2298. const size_t bufsize = (size_t) _bufsize;
  2299. if (!__PHYSFS_ui64FitsAddressSpace(_bufsize))
  2300. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2301. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2302. /*
  2303. * For reads, we need to move the file pointer to where it would be
  2304. * if we weren't buffering, so that the next read will get the
  2305. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  2306. */
  2307. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  2308. {
  2309. PHYSFS_uint64 pos;
  2310. const PHYSFS_sint64 curpos = fh->io->tell(fh->io);
  2311. BAIL_IF_ERRPASS(curpos == -1, 0);
  2312. pos = ((curpos - fh->buffill) + fh->bufpos);
  2313. BAIL_IF_ERRPASS(!fh->io->seek(fh->io, pos), 0);
  2314. } /* if */
  2315. if (bufsize == 0) /* delete existing buffer. */
  2316. {
  2317. if (fh->buffer)
  2318. {
  2319. allocator.Free(fh->buffer);
  2320. fh->buffer = NULL;
  2321. } /* if */
  2322. } /* if */
  2323. else
  2324. {
  2325. PHYSFS_uint8 *newbuf;
  2326. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  2327. BAIL_IF(!newbuf, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2328. fh->buffer = newbuf;
  2329. } /* else */
  2330. fh->bufsize = bufsize;
  2331. fh->buffill = fh->bufpos = 0;
  2332. return 1;
  2333. } /* PHYSFS_setBuffer */
  2334. int PHYSFS_flush(PHYSFS_File *handle)
  2335. {
  2336. FileHandle *fh = (FileHandle *) handle;
  2337. PHYSFS_Io *io;
  2338. PHYSFS_sint64 rc;
  2339. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  2340. return 1; /* open for read or buffer empty are successful no-ops. */
  2341. /* dump buffer to disk. */
  2342. io = fh->io;
  2343. rc = io->write(io, fh->buffer + fh->bufpos, fh->buffill - fh->bufpos);
  2344. BAIL_IF_ERRPASS(rc <= 0, 0);
  2345. fh->bufpos = fh->buffill = 0;
  2346. return io->flush ? io->flush(io) : 1;
  2347. } /* PHYSFS_flush */
  2348. int PHYSFS_stat(const char *_fname, PHYSFS_Stat *stat)
  2349. {
  2350. int retval = 0;
  2351. char *fname;
  2352. size_t len;
  2353. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2354. BAIL_IF(!stat, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2355. len = strlen(_fname) + 1;
  2356. fname = (char *) __PHYSFS_smallAlloc(len);
  2357. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2358. /* set some sane defaults... */
  2359. stat->filesize = -1;
  2360. stat->modtime = -1;
  2361. stat->createtime = -1;
  2362. stat->accesstime = -1;
  2363. stat->filetype = PHYSFS_FILETYPE_OTHER;
  2364. stat->readonly = 1;
  2365. if (sanitizePlatformIndependentPath(_fname, fname))
  2366. {
  2367. if (*fname == '\0')
  2368. {
  2369. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2370. stat->readonly = !writeDir; /* Writeable if we have a writeDir */
  2371. retval = 1;
  2372. } /* if */
  2373. else
  2374. {
  2375. DirHandle *i;
  2376. int exists = 0;
  2377. __PHYSFS_platformGrabMutex(stateLock);
  2378. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  2379. {
  2380. char *arcfname = fname;
  2381. exists = partOfMountPoint(i, arcfname);
  2382. if (exists)
  2383. {
  2384. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2385. stat->readonly = 1;
  2386. retval = 1;
  2387. } /* if */
  2388. else if (verifyPath(i, &arcfname, 0))
  2389. {
  2390. /* !!! FIXME-3.0: this test is wrong and should be elsewhere. */
  2391. stat->readonly = !(writeDir &&
  2392. (strcmp(writeDir->dirName, i->dirName) == 0));
  2393. retval = i->funcs->stat(i->opaque, arcfname, stat);
  2394. if ((retval) || (currentErrorCode() != PHYSFS_ERR_NOT_FOUND))
  2395. exists = 1;
  2396. } /* else if */
  2397. } /* for */
  2398. __PHYSFS_platformReleaseMutex(stateLock);
  2399. } /* else */
  2400. } /* if */
  2401. __PHYSFS_smallFree(fname);
  2402. return retval;
  2403. } /* PHYSFS_stat */
  2404. int __PHYSFS_readAll(PHYSFS_Io *io, void *buf, const PHYSFS_uint64 len)
  2405. {
  2406. return (io->read(io, buf, len) == len);
  2407. } /* __PHYSFS_readAll */
  2408. void *__PHYSFS_initSmallAlloc(void *ptr, PHYSFS_uint64 len)
  2409. {
  2410. void *useHeap = ((ptr == NULL) ? ((void *) 1) : ((void *) 0));
  2411. if (useHeap) /* too large for stack allocation or alloca() failed. */
  2412. ptr = allocator.Malloc(len+sizeof (void *));
  2413. if (ptr != NULL)
  2414. {
  2415. void **retval = (void **) ptr;
  2416. /*printf("%s alloc'd (%d) bytes at (%p).\n",
  2417. useHeap ? "heap" : "stack", (int) len, ptr);*/
  2418. *retval = useHeap;
  2419. return retval + 1;
  2420. } /* if */
  2421. return NULL; /* allocation failed. */
  2422. } /* __PHYSFS_initSmallAlloc */
  2423. void __PHYSFS_smallFree(void *ptr)
  2424. {
  2425. if (ptr != NULL)
  2426. {
  2427. void **block = ((void **) ptr) - 1;
  2428. const int useHeap = (*block != 0);
  2429. if (useHeap)
  2430. allocator.Free(block);
  2431. /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
  2432. } /* if */
  2433. } /* __PHYSFS_smallFree */
  2434. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  2435. {
  2436. BAIL_IF(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
  2437. externalAllocator = (a != NULL);
  2438. if (externalAllocator)
  2439. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  2440. return 1;
  2441. } /* PHYSFS_setAllocator */
  2442. const PHYSFS_Allocator *PHYSFS_getAllocator(void)
  2443. {
  2444. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
  2445. return &allocator;
  2446. } /* PHYSFS_getAllocator */
  2447. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  2448. {
  2449. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2450. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2451. #undef malloc
  2452. return malloc((size_t) s);
  2453. } /* mallocAllocatorMalloc */
  2454. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  2455. {
  2456. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2457. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2458. #undef realloc
  2459. return realloc(ptr, (size_t) s);
  2460. } /* mallocAllocatorRealloc */
  2461. static void mallocAllocatorFree(void *ptr)
  2462. {
  2463. #undef free
  2464. free(ptr);
  2465. } /* mallocAllocatorFree */
  2466. static void setDefaultAllocator(void)
  2467. {
  2468. assert(!externalAllocator);
  2469. allocator.Init = NULL;
  2470. allocator.Deinit = NULL;
  2471. allocator.Malloc = mallocAllocatorMalloc;
  2472. allocator.Realloc = mallocAllocatorRealloc;
  2473. allocator.Free = mallocAllocatorFree;
  2474. } /* setDefaultAllocator */
  2475. int __PHYSFS_DirTreeInit(__PHYSFS_DirTree *dt, const size_t entrylen)
  2476. {
  2477. static char rootpath[2] = { '/', '\0' };
  2478. size_t alloclen;
  2479. assert(entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2480. memset(dt, '\0', sizeof (*dt));
  2481. dt->root = (__PHYSFS_DirTreeEntry *) allocator.Malloc(entrylen);
  2482. BAIL_IF(!dt->root, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2483. memset(dt->root, '\0', entrylen);
  2484. dt->root->name = rootpath;
  2485. dt->root->isdir = 1;
  2486. dt->hashBuckets = 64;
  2487. if (!dt->hashBuckets)
  2488. dt->hashBuckets = 1;
  2489. dt->entrylen = entrylen;
  2490. alloclen = dt->hashBuckets * sizeof (__PHYSFS_DirTreeEntry *);
  2491. dt->hash = (__PHYSFS_DirTreeEntry **) allocator.Malloc(alloclen);
  2492. BAIL_IF(!dt->hash, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2493. memset(dt->hash, '\0', alloclen);
  2494. return 1;
  2495. } /* __PHYSFS_DirTreeInit */
  2496. static inline PHYSFS_uint32 hashPathName(__PHYSFS_DirTree *dt, const char *name)
  2497. {
  2498. return __PHYSFS_hashString(name, strlen(name)) % dt->hashBuckets;
  2499. } /* hashPathName */
  2500. /* Fill in missing parent directories. */
  2501. static __PHYSFS_DirTreeEntry *addAncestors(__PHYSFS_DirTree *dt, char *name)
  2502. {
  2503. __PHYSFS_DirTreeEntry *retval = dt->root;
  2504. char *sep = strrchr(name, '/');
  2505. if (sep)
  2506. {
  2507. *sep = '\0'; /* chop off last piece. */
  2508. retval = (__PHYSFS_DirTreeEntry *) __PHYSFS_DirTreeFind(dt, name);
  2509. if (retval != NULL)
  2510. {
  2511. *sep = '/';
  2512. BAIL_IF(!retval->isdir, PHYSFS_ERR_CORRUPT, NULL);
  2513. return retval; /* already hashed. */
  2514. } /* if */
  2515. /* okay, this is a new dir. Build and hash us. */
  2516. retval = (__PHYSFS_DirTreeEntry*)__PHYSFS_DirTreeAdd(dt, name, 1);
  2517. *sep = '/';
  2518. } /* if */
  2519. return retval;
  2520. } /* addAncestors */
  2521. void *__PHYSFS_DirTreeAdd(__PHYSFS_DirTree *dt, char *name, const int isdir)
  2522. {
  2523. __PHYSFS_DirTreeEntry *retval = __PHYSFS_DirTreeFind(dt, name);
  2524. if (!retval)
  2525. {
  2526. const size_t alloclen = strlen(name) + 1 + dt->entrylen;
  2527. PHYSFS_uint32 hashval;
  2528. __PHYSFS_DirTreeEntry *parent = addAncestors(dt, name);
  2529. BAIL_IF_ERRPASS(!parent, NULL);
  2530. assert(dt->entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2531. retval = (__PHYSFS_DirTreeEntry *) allocator.Malloc(alloclen);
  2532. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2533. memset(retval, '\0', dt->entrylen);
  2534. retval->name = ((char *) retval) + dt->entrylen;
  2535. strcpy(retval->name, name);
  2536. hashval = hashPathName(dt, name);
  2537. retval->hashnext = dt->hash[hashval];
  2538. dt->hash[hashval] = retval;
  2539. retval->sibling = parent->children;
  2540. retval->isdir = isdir;
  2541. parent->children = retval;
  2542. } /* if */
  2543. return retval;
  2544. } /* __PHYSFS_DirTreeAdd */
  2545. /* Find the __PHYSFS_DirTreeEntry for a path in platform-independent notation. */
  2546. void *__PHYSFS_DirTreeFind(__PHYSFS_DirTree *dt, const char *path)
  2547. {
  2548. PHYSFS_uint32 hashval;
  2549. __PHYSFS_DirTreeEntry *prev = NULL;
  2550. __PHYSFS_DirTreeEntry *retval;
  2551. if (*path == '\0')
  2552. return dt->root;
  2553. hashval = hashPathName(dt, path);
  2554. for (retval = dt->hash[hashval]; retval; retval = retval->hashnext)
  2555. {
  2556. if (strcmp(retval->name, path) == 0)
  2557. {
  2558. if (prev != NULL) /* move this to the front of the list */
  2559. {
  2560. prev->hashnext = retval->hashnext;
  2561. retval->hashnext = dt->hash[hashval];
  2562. dt->hash[hashval] = retval;
  2563. } /* if */
  2564. return retval;
  2565. } /* if */
  2566. prev = retval;
  2567. } /* for */
  2568. BAIL(PHYSFS_ERR_NOT_FOUND, NULL);
  2569. } /* __PHYSFS_DirTreeFind */
  2570. int __PHYSFS_DirTreeEnumerate(void *opaque, const char *dname,
  2571. PHYSFS_EnumerateCallback cb,
  2572. const char *origdir, void *callbackdata)
  2573. {
  2574. __PHYSFS_DirTree *tree = (__PHYSFS_DirTree *) opaque;
  2575. const __PHYSFS_DirTreeEntry *entry = __PHYSFS_DirTreeFind(tree, dname);
  2576. if (entry && entry->isdir)
  2577. {
  2578. for (entry = entry->children; entry; entry = entry->sibling)
  2579. {
  2580. const char *name = entry->name;
  2581. const char *ptr = strrchr(name, '/');
  2582. const int rc = cb(callbackdata, origdir, ptr ? ptr + 1 : name);
  2583. BAIL_IF(rc == -1, PHYSFS_ERR_APP_CALLBACK, -1);
  2584. if (rc == 0)
  2585. return 0;
  2586. } /* for */
  2587. } /* if */
  2588. return 1;
  2589. } /* __PHYSFS_DirTreeEnumerate */
  2590. void __PHYSFS_DirTreeDeinit(__PHYSFS_DirTree *dt)
  2591. {
  2592. if (!dt)
  2593. return;
  2594. if (dt->root)
  2595. {
  2596. assert(dt->root->sibling == NULL);
  2597. assert(dt->hash || (dt->root->children == NULL));
  2598. allocator.Free(dt->root);
  2599. } /* if */
  2600. if (dt->hash)
  2601. {
  2602. size_t i;
  2603. for (i = 0; i < dt->hashBuckets; i++)
  2604. {
  2605. __PHYSFS_DirTreeEntry *entry;
  2606. __PHYSFS_DirTreeEntry *next;
  2607. for (entry = dt->hash[i]; entry; entry = next)
  2608. {
  2609. next = entry->hashnext;
  2610. allocator.Free(entry);
  2611. } /* for */
  2612. } /* for */
  2613. allocator.Free(dt->hash);
  2614. } /* if */
  2615. } /* __PHYSFS_DirTreeDeinit */
  2616. /* end of physfs.c ... */