physfs.c 101 KB

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