physfs.c 89 KB

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