physfs.c 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405
  1. /**
  2. * PhysicsFS; a portable, flexible file i/o abstraction.
  3. *
  4. * Documentation is in physfs.h. It's verbose, honest. :)
  5. *
  6. * Please see the file LICENSE.txt in the source's root directory.
  7. *
  8. * This file written by Ryan C. Gordon.
  9. */
  10. #define __PHYSICSFS_INTERNAL__
  11. #include "physfs_internal.h"
  12. #if defined(_MSC_VER)
  13. #include <stdarg.h>
  14. /* this code came from https://stackoverflow.com/a/8712996 */
  15. int __PHYSFS_msvc_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap)
  16. {
  17. int count = -1;
  18. if (size != 0)
  19. count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap);
  20. if (count == -1)
  21. count = _vscprintf(format, ap);
  22. return count;
  23. }
  24. int __PHYSFS_msvc_snprintf(char *outBuf, size_t size, const char *format, ...)
  25. {
  26. int count;
  27. va_list ap;
  28. va_start(ap, format);
  29. count = __PHYSFS_msvc_vsnprintf(outBuf, size, format, ap);
  30. va_end(ap);
  31. return count;
  32. }
  33. #endif
  34. typedef struct __PHYSFS_DIRHANDLE__
  35. {
  36. void *opaque; /* Instance data unique to the archiver. */
  37. char *dirName; /* Path to archive in platform-dependent notation. */
  38. char *mountPoint; /* Mountpoint in virtual file tree. */
  39. char *root; /* subdirectory of archiver to use as root of archive (NULL for actual root) */
  40. size_t rootlen; /* subdirectory of archiver to use as root of archive (NULL for actual root) */
  41. const PHYSFS_Archiver *funcs; /* Ptr to archiver info for this handle. */
  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. retval = *ptrval;
  88. *ptrval = retval + val;
  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. } /* else */
  710. } /* if */
  711. return retval;
  712. } /* tryOpenDir */
  713. static DirHandle *openDirectory(PHYSFS_Io *io, const char *d, int forWriting)
  714. {
  715. DirHandle *retval = NULL;
  716. PHYSFS_Archiver **i;
  717. const char *ext;
  718. int created_io = 0;
  719. int claimed = 0;
  720. PHYSFS_ErrorCode errcode;
  721. assert((io != NULL) || (d != NULL));
  722. if (io == NULL)
  723. {
  724. /* file doesn't exist, etc? Just fail out. */
  725. PHYSFS_Stat statbuf;
  726. BAIL_IF_ERRPASS(!__PHYSFS_platformStat(d, &statbuf, 1), NULL);
  727. /* DIR gets first shot (unlike the rest, it doesn't deal with files). */
  728. if (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY)
  729. {
  730. retval = tryOpenDir(io, &__PHYSFS_Archiver_DIR, d, forWriting, &claimed);
  731. if (retval || claimed)
  732. return retval;
  733. } /* if */
  734. io = __PHYSFS_createNativeIo(d, forWriting ? 'w' : 'r');
  735. BAIL_IF_ERRPASS(!io, NULL);
  736. created_io = 1;
  737. } /* if */
  738. ext = find_filename_extension(d);
  739. if (ext != NULL)
  740. {
  741. /* Look for archivers with matching file extensions first... */
  742. for (i = archivers; (*i != NULL) && (retval == NULL) && !claimed; i++)
  743. {
  744. if (PHYSFS_utf8stricmp(ext, (*i)->info.extension) == 0)
  745. retval = tryOpenDir(io, *i, d, forWriting, &claimed);
  746. } /* for */
  747. /* failing an exact file extension match, try all the others... */
  748. for (i = archivers; (*i != NULL) && (retval == NULL) && !claimed; i++)
  749. {
  750. if (PHYSFS_utf8stricmp(ext, (*i)->info.extension) != 0)
  751. retval = tryOpenDir(io, *i, d, forWriting, &claimed);
  752. } /* for */
  753. } /* if */
  754. else /* no extension? Try them all. */
  755. {
  756. for (i = archivers; (*i != NULL) && (retval == NULL) && !claimed; i++)
  757. retval = tryOpenDir(io, *i, d, forWriting, &claimed);
  758. } /* else */
  759. errcode = currentErrorCode();
  760. if ((!retval) && (created_io))
  761. io->destroy(io);
  762. BAIL_IF(!retval, claimed ? errcode : PHYSFS_ERR_UNSUPPORTED, NULL);
  763. return retval;
  764. } /* openDirectory */
  765. /*
  766. * Make a platform-independent path string sane. Doesn't actually check the
  767. * file hierarchy, it just cleans up the string.
  768. * (dst) must be a buffer at least as big as (src), as this is where the
  769. * cleaned up string is deposited.
  770. * If there are illegal bits in the path (".." entries, etc) then we
  771. * return zero and (dst) is undefined. Non-zero if the path was sanitized.
  772. */
  773. static int sanitizePlatformIndependentPath(const char *src, char *dst)
  774. {
  775. char *prev;
  776. char ch;
  777. while (*src == '/') /* skip initial '/' chars... */
  778. src++;
  779. /* Make sure the entire string isn't "." or ".." */
  780. if ((strcmp(src, ".") == 0) || (strcmp(src, "..") == 0))
  781. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  782. prev = dst;
  783. do
  784. {
  785. ch = *(src++);
  786. if ((ch == ':') || (ch == '\\')) /* illegal chars in a physfs path. */
  787. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  788. if (ch == '/') /* path separator. */
  789. {
  790. *dst = '\0'; /* "." and ".." are illegal pathnames. */
  791. if ((strcmp(prev, ".") == 0) || (strcmp(prev, "..") == 0))
  792. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  793. while (*src == '/') /* chop out doubles... */
  794. src++;
  795. if (*src == '\0') /* ends with a pathsep? */
  796. break; /* we're done, don't add final pathsep to dst. */
  797. prev = dst + 1;
  798. } /* if */
  799. *(dst++) = ch;
  800. } while (ch != '\0');
  801. return 1;
  802. } /* sanitizePlatformIndependentPath */
  803. static inline size_t dirHandleRootLen(const DirHandle *h)
  804. {
  805. return h ? h->rootlen : 0;
  806. } /* dirHandleRootLen */
  807. static inline int sanitizePlatformIndependentPathWithRoot(const DirHandle *h, const char *src, char *dst)
  808. {
  809. return sanitizePlatformIndependentPath(src, dst + dirHandleRootLen(h));
  810. } /* sanitizePlatformIndependentPathWithRoot */
  811. /*
  812. * Figure out if (fname) is part of (h)'s mountpoint. (fname) must be an
  813. * output from sanitizePlatformIndependentPath(), so that it is in a known
  814. * state.
  815. *
  816. * This only finds legitimate segments of a mountpoint. If the mountpoint is
  817. * "/a/b/c" and (fname) is "/a/b/c", "/", or "/a/b/c/d", then the results are
  818. * all zero. "/a/b" will succeed, though.
  819. */
  820. static int partOfMountPoint(DirHandle *h, char *fname)
  821. {
  822. int rc;
  823. size_t len, mntpntlen;
  824. if (h->mountPoint == NULL)
  825. return 0;
  826. else if (*fname == '\0')
  827. return 1;
  828. len = strlen(fname);
  829. mntpntlen = strlen(h->mountPoint);
  830. if (len > mntpntlen) /* can't be a subset of mountpoint. */
  831. return 0;
  832. /* if true, must be not a match or a complete match, but not a subset. */
  833. if ((len + 1) == mntpntlen)
  834. return 0;
  835. rc = strncmp(fname, h->mountPoint, len); /* !!! FIXME: case insensitive? */
  836. if (rc != 0)
  837. return 0; /* not a match. */
  838. /* make sure /a/b matches /a/b/ and not /a/bc ... */
  839. return h->mountPoint[len] == '/';
  840. } /* partOfMountPoint */
  841. static DirHandle *createDirHandle(PHYSFS_Io *io, const char *newDir,
  842. const char *mountPoint, int forWriting)
  843. {
  844. DirHandle *dirHandle = NULL;
  845. char *tmpmntpnt = NULL;
  846. assert(newDir != NULL); /* should have caught this higher up. */
  847. if (mountPoint != NULL)
  848. {
  849. const size_t len = strlen(mountPoint) + 1;
  850. tmpmntpnt = (char *) __PHYSFS_smallAlloc(len);
  851. GOTO_IF(!tmpmntpnt, PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  852. if (!sanitizePlatformIndependentPath(mountPoint, tmpmntpnt))
  853. goto badDirHandle;
  854. mountPoint = tmpmntpnt; /* sanitized version. */
  855. } /* if */
  856. dirHandle = openDirectory(io, newDir, forWriting);
  857. GOTO_IF_ERRPASS(!dirHandle, badDirHandle);
  858. dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
  859. GOTO_IF(!dirHandle->dirName, PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  860. strcpy(dirHandle->dirName, newDir);
  861. if ((mountPoint != NULL) && (*mountPoint != '\0'))
  862. {
  863. dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
  864. if (!dirHandle->mountPoint)
  865. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  866. strcpy(dirHandle->mountPoint, mountPoint);
  867. strcat(dirHandle->mountPoint, "/");
  868. } /* if */
  869. __PHYSFS_smallFree(tmpmntpnt);
  870. return dirHandle;
  871. badDirHandle:
  872. if (dirHandle != NULL)
  873. {
  874. dirHandle->funcs->closeArchive(dirHandle->opaque);
  875. allocator.Free(dirHandle->dirName);
  876. allocator.Free(dirHandle->mountPoint);
  877. allocator.Free(dirHandle);
  878. } /* if */
  879. __PHYSFS_smallFree(tmpmntpnt);
  880. return NULL;
  881. } /* createDirHandle */
  882. /* MAKE SURE you've got the stateLock held before calling this! */
  883. static int freeDirHandle(DirHandle *dh, FileHandle *openList)
  884. {
  885. FileHandle *i;
  886. if (dh == NULL)
  887. return 1;
  888. for (i = openList; i != NULL; i = i->next)
  889. BAIL_IF(i->dirHandle == dh, PHYSFS_ERR_FILES_STILL_OPEN, 0);
  890. dh->funcs->closeArchive(dh->opaque);
  891. allocator.Free(dh->dirName);
  892. allocator.Free(dh->mountPoint);
  893. allocator.Free(dh);
  894. return 1;
  895. } /* freeDirHandle */
  896. static char *calculateBaseDir(const char *argv0)
  897. {
  898. const char dirsep = __PHYSFS_platformDirSeparator;
  899. char *retval = NULL;
  900. char *ptr = NULL;
  901. /* Give the platform layer first shot at this. */
  902. retval = __PHYSFS_platformCalcBaseDir(argv0);
  903. if (retval != NULL)
  904. return retval;
  905. /* We need argv0 to go on. */
  906. BAIL_IF(argv0 == NULL, PHYSFS_ERR_ARGV0_IS_NULL, NULL);
  907. ptr = strrchr(argv0, dirsep);
  908. if (ptr != NULL)
  909. {
  910. const size_t size = ((size_t) (ptr - argv0)) + 1;
  911. retval = (char *) allocator.Malloc(size + 1);
  912. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  913. memcpy(retval, argv0, size);
  914. retval[size] = '\0';
  915. return retval;
  916. } /* if */
  917. /* argv0 wasn't helpful. */
  918. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  919. } /* calculateBaseDir */
  920. static int initializeMutexes(void)
  921. {
  922. errorLock = __PHYSFS_platformCreateMutex();
  923. if (errorLock == NULL)
  924. goto initializeMutexes_failed;
  925. stateLock = __PHYSFS_platformCreateMutex();
  926. if (stateLock == NULL)
  927. goto initializeMutexes_failed;
  928. return 1; /* success. */
  929. initializeMutexes_failed:
  930. if (errorLock != NULL)
  931. __PHYSFS_platformDestroyMutex(errorLock);
  932. if (stateLock != NULL)
  933. __PHYSFS_platformDestroyMutex(stateLock);
  934. errorLock = stateLock = NULL;
  935. return 0; /* failed. */
  936. } /* initializeMutexes */
  937. static int doRegisterArchiver(const PHYSFS_Archiver *_archiver);
  938. static int initStaticArchivers(void)
  939. {
  940. #define REGISTER_STATIC_ARCHIVER(arc) { \
  941. if (!doRegisterArchiver(&__PHYSFS_Archiver_##arc)) { \
  942. return 0; \
  943. } \
  944. }
  945. #if PHYSFS_SUPPORTS_ZIP
  946. REGISTER_STATIC_ARCHIVER(ZIP);
  947. #endif
  948. #if PHYSFS_SUPPORTS_7Z
  949. SZIP_global_init();
  950. REGISTER_STATIC_ARCHIVER(7Z);
  951. #endif
  952. #if PHYSFS_SUPPORTS_GRP
  953. REGISTER_STATIC_ARCHIVER(GRP);
  954. #endif
  955. #if PHYSFS_SUPPORTS_QPAK
  956. REGISTER_STATIC_ARCHIVER(QPAK);
  957. #endif
  958. #if PHYSFS_SUPPORTS_HOG
  959. REGISTER_STATIC_ARCHIVER(HOG);
  960. #endif
  961. #if PHYSFS_SUPPORTS_MVL
  962. REGISTER_STATIC_ARCHIVER(MVL);
  963. #endif
  964. #if PHYSFS_SUPPORTS_WAD
  965. REGISTER_STATIC_ARCHIVER(WAD);
  966. #endif
  967. #if PHYSFS_SUPPORTS_SLB
  968. REGISTER_STATIC_ARCHIVER(SLB);
  969. #endif
  970. #if PHYSFS_SUPPORTS_ISO9660
  971. REGISTER_STATIC_ARCHIVER(ISO9660);
  972. #endif
  973. #if PHYSFS_SUPPORTS_VDF
  974. REGISTER_STATIC_ARCHIVER(VDF)
  975. #endif
  976. #undef REGISTER_STATIC_ARCHIVER
  977. return 1;
  978. } /* initStaticArchivers */
  979. static void setDefaultAllocator(void);
  980. static int doDeinit(void);
  981. int PHYSFS_init(const char *argv0)
  982. {
  983. BAIL_IF(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
  984. if (!externalAllocator)
  985. setDefaultAllocator();
  986. if ((allocator.Init != NULL) && (!allocator.Init())) return 0;
  987. if (!__PHYSFS_platformInit())
  988. {
  989. if (allocator.Deinit != NULL) allocator.Deinit();
  990. return 0;
  991. } /* if */
  992. /* everything below here can be cleaned up safely by doDeinit(). */
  993. if (!initializeMutexes()) goto initFailed;
  994. baseDir = calculateBaseDir(argv0);
  995. if (!baseDir) goto initFailed;
  996. userDir = __PHYSFS_platformCalcUserDir();
  997. if (!userDir) goto initFailed;
  998. /* Platform layer is required to append a dirsep. */
  999. assert(baseDir[strlen(baseDir) - 1] == __PHYSFS_platformDirSeparator);
  1000. assert(userDir[strlen(userDir) - 1] == __PHYSFS_platformDirSeparator);
  1001. if (!initStaticArchivers()) goto initFailed;
  1002. initialized = 1;
  1003. /* This makes sure that the error subsystem is initialized. */
  1004. PHYSFS_setErrorCode(PHYSFS_getLastErrorCode());
  1005. return 1;
  1006. initFailed:
  1007. doDeinit();
  1008. return 0;
  1009. } /* PHYSFS_init */
  1010. /* MAKE SURE you hold stateLock before calling this! */
  1011. static int closeFileHandleList(FileHandle **list)
  1012. {
  1013. FileHandle *i;
  1014. FileHandle *next = NULL;
  1015. for (i = *list; i != NULL; i = next)
  1016. {
  1017. PHYSFS_Io *io = i->io;
  1018. next = i->next;
  1019. if (io->flush && !io->flush(io))
  1020. {
  1021. *list = i;
  1022. return 0;
  1023. } /* if */
  1024. io->destroy(io);
  1025. allocator.Free(i);
  1026. } /* for */
  1027. *list = NULL;
  1028. return 1;
  1029. } /* closeFileHandleList */
  1030. /* MAKE SURE you hold the stateLock before calling this! */
  1031. static void freeSearchPath(void)
  1032. {
  1033. DirHandle *i;
  1034. DirHandle *next = NULL;
  1035. closeFileHandleList(&openReadList);
  1036. if (searchPath != NULL)
  1037. {
  1038. for (i = searchPath; i != NULL; i = next)
  1039. {
  1040. next = i->next;
  1041. freeDirHandle(i, openReadList);
  1042. } /* for */
  1043. searchPath = NULL;
  1044. } /* if */
  1045. } /* freeSearchPath */
  1046. /* MAKE SURE you hold stateLock before calling this! */
  1047. static int archiverInUse(const PHYSFS_Archiver *arc, const DirHandle *list)
  1048. {
  1049. const DirHandle *i;
  1050. for (i = list; i != NULL; i = i->next)
  1051. {
  1052. if (i->funcs == arc)
  1053. return 1;
  1054. } /* for */
  1055. return 0; /* not in use */
  1056. } /* archiverInUse */
  1057. /* MAKE SURE you hold stateLock before calling this! */
  1058. static int doDeregisterArchiver(const size_t idx)
  1059. {
  1060. const size_t len = (numArchivers - idx) * sizeof (void *);
  1061. PHYSFS_ArchiveInfo *info = archiveInfo[idx];
  1062. PHYSFS_Archiver *arc = archivers[idx];
  1063. /* make sure nothing is still using this archiver */
  1064. if (archiverInUse(arc, searchPath) || archiverInUse(arc, writeDir))
  1065. BAIL(PHYSFS_ERR_FILES_STILL_OPEN, 0);
  1066. allocator.Free((void *) info->extension);
  1067. allocator.Free((void *) info->description);
  1068. allocator.Free((void *) info->author);
  1069. allocator.Free((void *) info->url);
  1070. allocator.Free((void *) arc);
  1071. memmove(&archiveInfo[idx], &archiveInfo[idx+1], len);
  1072. memmove(&archivers[idx], &archivers[idx+1], len);
  1073. assert(numArchivers > 0);
  1074. numArchivers--;
  1075. return 1;
  1076. } /* doDeregisterArchiver */
  1077. /* Does NOT hold the state lock; we're shutting down. */
  1078. static void freeArchivers(void)
  1079. {
  1080. while (numArchivers > 0)
  1081. {
  1082. if (!doDeregisterArchiver(numArchivers - 1))
  1083. assert(!"nothing should be mounted during shutdown.");
  1084. } /* while */
  1085. allocator.Free(archivers);
  1086. allocator.Free(archiveInfo);
  1087. archivers = NULL;
  1088. archiveInfo = NULL;
  1089. } /* freeArchivers */
  1090. static int doDeinit(void)
  1091. {
  1092. closeFileHandleList(&openWriteList);
  1093. BAIL_IF(!PHYSFS_setWriteDir(NULL), PHYSFS_ERR_FILES_STILL_OPEN, 0);
  1094. freeSearchPath();
  1095. freeArchivers();
  1096. freeErrorStates();
  1097. if (baseDir != NULL)
  1098. {
  1099. allocator.Free(baseDir);
  1100. baseDir = NULL;
  1101. } /* if */
  1102. if (userDir != NULL)
  1103. {
  1104. allocator.Free(userDir);
  1105. userDir = NULL;
  1106. } /* if */
  1107. if (prefDir != NULL)
  1108. {
  1109. allocator.Free(prefDir);
  1110. prefDir = NULL;
  1111. } /* if */
  1112. if (archiveInfo != NULL)
  1113. {
  1114. allocator.Free(archiveInfo);
  1115. archiveInfo = NULL;
  1116. } /* if */
  1117. if (archivers != NULL)
  1118. {
  1119. allocator.Free(archivers);
  1120. archivers = NULL;
  1121. } /* if */
  1122. longest_root = 0;
  1123. allowSymLinks = 0;
  1124. initialized = 0;
  1125. if (errorLock) __PHYSFS_platformDestroyMutex(errorLock);
  1126. if (stateLock) __PHYSFS_platformDestroyMutex(stateLock);
  1127. if (allocator.Deinit != NULL)
  1128. allocator.Deinit();
  1129. errorLock = stateLock = NULL;
  1130. __PHYSFS_platformDeinit();
  1131. return 1;
  1132. } /* doDeinit */
  1133. int PHYSFS_deinit(void)
  1134. {
  1135. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1136. return doDeinit();
  1137. } /* PHYSFS_deinit */
  1138. int PHYSFS_isInit(void)
  1139. {
  1140. return initialized;
  1141. } /* PHYSFS_isInit */
  1142. char *__PHYSFS_strdup(const char *str)
  1143. {
  1144. char *retval = (char *) allocator.Malloc(strlen(str) + 1);
  1145. if (retval)
  1146. strcpy(retval, str);
  1147. return retval;
  1148. } /* __PHYSFS_strdup */
  1149. PHYSFS_uint32 __PHYSFS_hashString(const char *str, size_t len)
  1150. {
  1151. PHYSFS_uint32 hash = 5381;
  1152. while (len--)
  1153. hash = ((hash << 5) + hash) ^ *(str++);
  1154. return hash;
  1155. } /* __PHYSFS_hashString */
  1156. /* MAKE SURE you hold stateLock before calling this! */
  1157. static int doRegisterArchiver(const PHYSFS_Archiver *_archiver)
  1158. {
  1159. const PHYSFS_uint32 maxver = CURRENT_PHYSFS_ARCHIVER_API_VERSION;
  1160. const size_t len = (numArchivers + 2) * sizeof (void *);
  1161. PHYSFS_Archiver *archiver = NULL;
  1162. PHYSFS_ArchiveInfo *info = NULL;
  1163. const char *ext = NULL;
  1164. void *ptr = NULL;
  1165. size_t i;
  1166. BAIL_IF(!_archiver, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1167. BAIL_IF(_archiver->version > maxver, PHYSFS_ERR_UNSUPPORTED, 0);
  1168. BAIL_IF(!_archiver->info.extension, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1169. BAIL_IF(!_archiver->info.description, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1170. BAIL_IF(!_archiver->info.author, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1171. BAIL_IF(!_archiver->info.url, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1172. BAIL_IF(!_archiver->openArchive, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1173. BAIL_IF(!_archiver->enumerate, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1174. BAIL_IF(!_archiver->openRead, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1175. BAIL_IF(!_archiver->openWrite, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1176. BAIL_IF(!_archiver->openAppend, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1177. BAIL_IF(!_archiver->remove, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1178. BAIL_IF(!_archiver->mkdir, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1179. BAIL_IF(!_archiver->closeArchive, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1180. BAIL_IF(!_archiver->stat, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1181. ext = _archiver->info.extension;
  1182. for (i = 0; i < numArchivers; i++)
  1183. {
  1184. if (PHYSFS_utf8stricmp(archiveInfo[i]->extension, ext) == 0)
  1185. BAIL(PHYSFS_ERR_DUPLICATE, 0);
  1186. } /* for */
  1187. /* make a copy of the data. */
  1188. archiver = (PHYSFS_Archiver *) allocator.Malloc(sizeof (*archiver));
  1189. GOTO_IF(!archiver, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1190. /* Must copy sizeof (OLD_VERSION_OF_STRUCT) when version changes! */
  1191. memcpy(archiver, _archiver, sizeof (*archiver));
  1192. info = (PHYSFS_ArchiveInfo *) &archiver->info;
  1193. memset(info, '\0', sizeof (*info)); /* NULL in case an alloc fails. */
  1194. #define CPYSTR(item) \
  1195. info->item = __PHYSFS_strdup(_archiver->info.item); \
  1196. GOTO_IF(!info->item, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1197. CPYSTR(extension);
  1198. CPYSTR(description);
  1199. CPYSTR(author);
  1200. CPYSTR(url);
  1201. info->supportsSymlinks = _archiver->info.supportsSymlinks;
  1202. #undef CPYSTR
  1203. ptr = allocator.Realloc(archiveInfo, len);
  1204. GOTO_IF(!ptr, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1205. archiveInfo = (PHYSFS_ArchiveInfo **) ptr;
  1206. ptr = allocator.Realloc(archivers, len);
  1207. GOTO_IF(!ptr, PHYSFS_ERR_OUT_OF_MEMORY, regfailed);
  1208. archivers = (PHYSFS_Archiver **) ptr;
  1209. archiveInfo[numArchivers] = info;
  1210. archiveInfo[numArchivers + 1] = NULL;
  1211. archivers[numArchivers] = archiver;
  1212. archivers[numArchivers + 1] = NULL;
  1213. numArchivers++;
  1214. return 1;
  1215. regfailed:
  1216. if (info != NULL)
  1217. {
  1218. allocator.Free((void *) info->extension);
  1219. allocator.Free((void *) info->description);
  1220. allocator.Free((void *) info->author);
  1221. allocator.Free((void *) info->url);
  1222. } /* if */
  1223. allocator.Free(archiver);
  1224. return 0;
  1225. } /* doRegisterArchiver */
  1226. int PHYSFS_registerArchiver(const PHYSFS_Archiver *archiver)
  1227. {
  1228. int retval;
  1229. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1230. __PHYSFS_platformGrabMutex(stateLock);
  1231. retval = doRegisterArchiver(archiver);
  1232. __PHYSFS_platformReleaseMutex(stateLock);
  1233. return retval;
  1234. } /* PHYSFS_registerArchiver */
  1235. int PHYSFS_deregisterArchiver(const char *ext)
  1236. {
  1237. size_t i;
  1238. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1239. BAIL_IF(!ext, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1240. __PHYSFS_platformGrabMutex(stateLock);
  1241. for (i = 0; i < numArchivers; i++)
  1242. {
  1243. if (PHYSFS_utf8stricmp(archiveInfo[i]->extension, ext) == 0)
  1244. {
  1245. const int retval = doDeregisterArchiver(i);
  1246. __PHYSFS_platformReleaseMutex(stateLock);
  1247. return retval;
  1248. } /* if */
  1249. } /* for */
  1250. __PHYSFS_platformReleaseMutex(stateLock);
  1251. BAIL(PHYSFS_ERR_NOT_FOUND, 0);
  1252. } /* PHYSFS_deregisterArchiver */
  1253. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  1254. {
  1255. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
  1256. return (const PHYSFS_ArchiveInfo **) archiveInfo;
  1257. } /* PHYSFS_supportedArchiveTypes */
  1258. void PHYSFS_freeList(void *list)
  1259. {
  1260. void **i;
  1261. if (list != NULL)
  1262. {
  1263. for (i = (void **) list; *i != NULL; i++)
  1264. allocator.Free(*i);
  1265. allocator.Free(list);
  1266. } /* if */
  1267. } /* PHYSFS_freeList */
  1268. const char *PHYSFS_getDirSeparator(void)
  1269. {
  1270. static char retval[2] = { __PHYSFS_platformDirSeparator, '\0' };
  1271. return retval;
  1272. } /* PHYSFS_getDirSeparator */
  1273. char **PHYSFS_getCdRomDirs(void)
  1274. {
  1275. return doEnumStringList(__PHYSFS_platformDetectAvailableCDs);
  1276. } /* PHYSFS_getCdRomDirs */
  1277. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  1278. {
  1279. __PHYSFS_platformDetectAvailableCDs(callback, data);
  1280. } /* PHYSFS_getCdRomDirsCallback */
  1281. const char *PHYSFS_getPrefDir(const char *org, const char *app)
  1282. {
  1283. const char dirsep = __PHYSFS_platformDirSeparator;
  1284. PHYSFS_Stat statbuf;
  1285. char *ptr = NULL;
  1286. char *endstr = NULL;
  1287. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1288. BAIL_IF(!org, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1289. BAIL_IF(*org == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1290. BAIL_IF(!app, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1291. BAIL_IF(*app == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1292. allocator.Free(prefDir);
  1293. prefDir = __PHYSFS_platformCalcPrefDir(org, app);
  1294. BAIL_IF_ERRPASS(!prefDir, NULL);
  1295. assert(strlen(prefDir) > 0);
  1296. endstr = prefDir + (strlen(prefDir) - 1);
  1297. assert(*endstr == dirsep);
  1298. *endstr = '\0'; /* mask out the final dirsep for now. */
  1299. if (!__PHYSFS_platformStat(prefDir, &statbuf, 1))
  1300. {
  1301. for (ptr = strchr(prefDir, dirsep); ptr; ptr = strchr(ptr+1, dirsep))
  1302. {
  1303. *ptr = '\0';
  1304. __PHYSFS_platformMkDir(prefDir);
  1305. *ptr = dirsep;
  1306. } /* for */
  1307. if (!__PHYSFS_platformMkDir(prefDir))
  1308. {
  1309. allocator.Free(prefDir);
  1310. prefDir = NULL;
  1311. } /* if */
  1312. } /* if */
  1313. *endstr = dirsep; /* readd the final dirsep. */
  1314. return prefDir;
  1315. } /* PHYSFS_getPrefDir */
  1316. const char *PHYSFS_getBaseDir(void)
  1317. {
  1318. return baseDir; /* this is calculated in PHYSFS_init()... */
  1319. } /* PHYSFS_getBaseDir */
  1320. const char *__PHYSFS_getUserDir(void) /* not deprecated internal version. */
  1321. {
  1322. return userDir; /* this is calculated in PHYSFS_init()... */
  1323. } /* __PHYSFS_getUserDir */
  1324. const char *PHYSFS_getUserDir(void)
  1325. {
  1326. return __PHYSFS_getUserDir();
  1327. } /* PHYSFS_getUserDir */
  1328. const char *PHYSFS_getWriteDir(void)
  1329. {
  1330. const char *retval = NULL;
  1331. __PHYSFS_platformGrabMutex(stateLock);
  1332. if (writeDir != NULL)
  1333. retval = writeDir->dirName;
  1334. __PHYSFS_platformReleaseMutex(stateLock);
  1335. return retval;
  1336. } /* PHYSFS_getWriteDir */
  1337. int PHYSFS_setWriteDir(const char *newDir)
  1338. {
  1339. int retval = 1;
  1340. __PHYSFS_platformGrabMutex(stateLock);
  1341. if (writeDir != NULL)
  1342. {
  1343. BAIL_IF_MUTEX_ERRPASS(!freeDirHandle(writeDir, openWriteList),
  1344. stateLock, 0);
  1345. writeDir = NULL;
  1346. } /* if */
  1347. if (newDir != NULL)
  1348. {
  1349. writeDir = createDirHandle(NULL, newDir, NULL, 1);
  1350. retval = (writeDir != NULL);
  1351. } /* if */
  1352. __PHYSFS_platformReleaseMutex(stateLock);
  1353. return retval;
  1354. } /* PHYSFS_setWriteDir */
  1355. int PHYSFS_setRoot(const char *archive, const char *subdir)
  1356. {
  1357. DirHandle *i;
  1358. BAIL_IF(!archive, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1359. __PHYSFS_platformGrabMutex(stateLock);
  1360. for (i = searchPath; i != NULL; i = i->next)
  1361. {
  1362. if ((i->dirName != NULL) && (strcmp(archive, i->dirName) == 0))
  1363. {
  1364. if (!subdir || (strcmp(subdir, "/") == 0))
  1365. {
  1366. if (i->root)
  1367. allocator.Free(i->root);
  1368. i->root = NULL;
  1369. i->rootlen = 0;
  1370. } /* if */
  1371. else
  1372. {
  1373. const size_t len = strlen(subdir) + 1;
  1374. char *ptr = (char *) allocator.Malloc(len);
  1375. BAIL_IF_MUTEX(!ptr, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, 0);
  1376. if (!sanitizePlatformIndependentPath(subdir, ptr))
  1377. {
  1378. allocator.Free(ptr);
  1379. BAIL_MUTEX_ERRPASS(stateLock, 0);
  1380. } /* if */
  1381. if (i->root)
  1382. allocator.Free(i->root);
  1383. i->root = ptr;
  1384. i->rootlen = len;
  1385. if (longest_root < len)
  1386. longest_root = len;
  1387. } /* else */
  1388. break;
  1389. } /* if */
  1390. } /* for */
  1391. __PHYSFS_platformReleaseMutex(stateLock);
  1392. return 1;
  1393. } /* PHYSFS_setRoot */
  1394. static int doMount(PHYSFS_Io *io, const char *fname,
  1395. const char *mountPoint, int appendToPath)
  1396. {
  1397. DirHandle *dh;
  1398. DirHandle *prev = NULL;
  1399. DirHandle *i;
  1400. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1401. if (mountPoint == NULL)
  1402. mountPoint = "/";
  1403. __PHYSFS_platformGrabMutex(stateLock);
  1404. for (i = searchPath; i != NULL; i = i->next)
  1405. {
  1406. /* already in search path? */
  1407. if ((i->dirName != NULL) && (strcmp(fname, i->dirName) == 0))
  1408. BAIL_MUTEX_ERRPASS(stateLock, 1);
  1409. prev = i;
  1410. } /* for */
  1411. dh = createDirHandle(io, fname, mountPoint, 0);
  1412. BAIL_IF_MUTEX_ERRPASS(!dh, stateLock, 0);
  1413. if (appendToPath)
  1414. {
  1415. if (prev == NULL)
  1416. searchPath = dh;
  1417. else
  1418. prev->next = dh;
  1419. } /* if */
  1420. else
  1421. {
  1422. dh->next = searchPath;
  1423. searchPath = dh;
  1424. } /* else */
  1425. __PHYSFS_platformReleaseMutex(stateLock);
  1426. return 1;
  1427. } /* doMount */
  1428. int PHYSFS_mountIo(PHYSFS_Io *io, const char *fname,
  1429. const char *mountPoint, int appendToPath)
  1430. {
  1431. BAIL_IF(!io, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1432. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1433. BAIL_IF(io->version != 0, PHYSFS_ERR_UNSUPPORTED, 0);
  1434. return doMount(io, fname, mountPoint, appendToPath);
  1435. } /* PHYSFS_mountIo */
  1436. int PHYSFS_mountMemory(const void *buf, PHYSFS_uint64 len, void (*del)(void *),
  1437. const char *fname, const char *mountPoint,
  1438. int appendToPath)
  1439. {
  1440. int retval = 0;
  1441. PHYSFS_Io *io = NULL;
  1442. BAIL_IF(!buf, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1443. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1444. io = __PHYSFS_createMemoryIo(buf, len, del);
  1445. BAIL_IF_ERRPASS(!io, 0);
  1446. retval = doMount(io, fname, mountPoint, appendToPath);
  1447. if (!retval)
  1448. {
  1449. /* docs say not to call (del) in case of failure, so cheat. */
  1450. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  1451. info->destruct = NULL;
  1452. io->destroy(io);
  1453. } /* if */
  1454. return retval;
  1455. } /* PHYSFS_mountMemory */
  1456. int PHYSFS_mountHandle(PHYSFS_File *file, const char *fname,
  1457. const char *mountPoint, int appendToPath)
  1458. {
  1459. int retval = 0;
  1460. PHYSFS_Io *io = NULL;
  1461. BAIL_IF(!file, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1462. BAIL_IF(!fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1463. io = __PHYSFS_createHandleIo(file);
  1464. BAIL_IF_ERRPASS(!io, 0);
  1465. retval = doMount(io, fname, mountPoint, appendToPath);
  1466. if (!retval)
  1467. {
  1468. /* docs say not to destruct in case of failure, so cheat. */
  1469. io->opaque = NULL;
  1470. io->destroy(io);
  1471. } /* if */
  1472. return retval;
  1473. } /* PHYSFS_mountHandle */
  1474. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  1475. {
  1476. BAIL_IF(!newDir, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1477. return doMount(NULL, newDir, mountPoint, appendToPath);
  1478. } /* PHYSFS_mount */
  1479. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  1480. {
  1481. return PHYSFS_mount(newDir, NULL, appendToPath);
  1482. } /* PHYSFS_addToSearchPath */
  1483. int PHYSFS_removeFromSearchPath(const char *oldDir)
  1484. {
  1485. return PHYSFS_unmount(oldDir);
  1486. } /* PHYSFS_removeFromSearchPath */
  1487. int PHYSFS_unmount(const char *oldDir)
  1488. {
  1489. DirHandle *i;
  1490. DirHandle *prev = NULL;
  1491. DirHandle *next = NULL;
  1492. BAIL_IF(oldDir == NULL, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1493. __PHYSFS_platformGrabMutex(stateLock);
  1494. for (i = searchPath; i != NULL; i = i->next)
  1495. {
  1496. if (strcmp(i->dirName, oldDir) == 0)
  1497. {
  1498. next = i->next;
  1499. BAIL_IF_MUTEX_ERRPASS(!freeDirHandle(i, openReadList),
  1500. stateLock, 0);
  1501. if (prev == NULL)
  1502. searchPath = next;
  1503. else
  1504. prev->next = next;
  1505. BAIL_MUTEX_ERRPASS(stateLock, 1);
  1506. } /* if */
  1507. prev = i;
  1508. } /* for */
  1509. BAIL_MUTEX(PHYSFS_ERR_NOT_MOUNTED, stateLock, 0);
  1510. } /* PHYSFS_unmount */
  1511. char **PHYSFS_getSearchPath(void)
  1512. {
  1513. return doEnumStringList(PHYSFS_getSearchPathCallback);
  1514. } /* PHYSFS_getSearchPath */
  1515. const char *PHYSFS_getMountPoint(const char *dir)
  1516. {
  1517. DirHandle *i;
  1518. __PHYSFS_platformGrabMutex(stateLock);
  1519. for (i = searchPath; i != NULL; i = i->next)
  1520. {
  1521. if (strcmp(i->dirName, dir) == 0)
  1522. {
  1523. const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
  1524. __PHYSFS_platformReleaseMutex(stateLock);
  1525. return retval;
  1526. } /* if */
  1527. } /* for */
  1528. __PHYSFS_platformReleaseMutex(stateLock);
  1529. BAIL(PHYSFS_ERR_NOT_MOUNTED, NULL);
  1530. } /* PHYSFS_getMountPoint */
  1531. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  1532. {
  1533. DirHandle *i;
  1534. __PHYSFS_platformGrabMutex(stateLock);
  1535. for (i = searchPath; i != NULL; i = i->next)
  1536. callback(data, i->dirName);
  1537. __PHYSFS_platformReleaseMutex(stateLock);
  1538. } /* PHYSFS_getSearchPathCallback */
  1539. typedef struct setSaneCfgEnumData
  1540. {
  1541. const char *archiveExt;
  1542. size_t archiveExtLen;
  1543. int archivesFirst;
  1544. PHYSFS_ErrorCode errcode;
  1545. } setSaneCfgEnumData;
  1546. static PHYSFS_EnumerateCallbackResult setSaneCfgEnumCallback(void *_data,
  1547. const char *dir, const char *f)
  1548. {
  1549. setSaneCfgEnumData *data = (setSaneCfgEnumData *) _data;
  1550. const size_t extlen = data->archiveExtLen;
  1551. const size_t l = strlen(f);
  1552. const char *ext;
  1553. if ((l > extlen) && (f[l - extlen - 1] == '.'))
  1554. {
  1555. ext = f + (l - extlen);
  1556. if (PHYSFS_utf8stricmp(ext, data->archiveExt) == 0)
  1557. {
  1558. const char dirsep = __PHYSFS_platformDirSeparator;
  1559. const char *d = PHYSFS_getRealDir(f);
  1560. const size_t allocsize = strlen(d) + l + 2;
  1561. char *str = (char *) __PHYSFS_smallAlloc(allocsize);
  1562. if (str == NULL)
  1563. data->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1564. else
  1565. {
  1566. snprintf(str, allocsize, "%s%c%s", d, dirsep, f);
  1567. if (!PHYSFS_mount(str, NULL, data->archivesFirst == 0))
  1568. data->errcode = currentErrorCode();
  1569. __PHYSFS_smallFree(str);
  1570. } /* else */
  1571. } /* if */
  1572. } /* if */
  1573. /* !!! FIXME: if we want to abort on errors... */
  1574. /*return (data->errcode != PHYSFS_ERR_OK) ? PHYSFS_ENUM_ERROR : PHYSFS_ENUM_OK;*/
  1575. return PHYSFS_ENUM_OK; /* keep going */
  1576. } /* setSaneCfgEnumCallback */
  1577. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  1578. const char *archiveExt, int includeCdRoms,
  1579. int archivesFirst)
  1580. {
  1581. const char *basedir;
  1582. const char *prefdir;
  1583. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1584. prefdir = PHYSFS_getPrefDir(organization, appName);
  1585. BAIL_IF_ERRPASS(!prefdir, 0);
  1586. basedir = PHYSFS_getBaseDir();
  1587. BAIL_IF_ERRPASS(!basedir, 0);
  1588. BAIL_IF(!PHYSFS_setWriteDir(prefdir), PHYSFS_ERR_NO_WRITE_DIR, 0);
  1589. /* !!! FIXME: these can fail and we should report that... */
  1590. /* Put write dir first in search path... */
  1591. PHYSFS_mount(prefdir, NULL, 0);
  1592. /* Put base path on search path... */
  1593. PHYSFS_mount(basedir, NULL, 1);
  1594. /* handle CD-ROMs... */
  1595. if (includeCdRoms)
  1596. {
  1597. char **cds = PHYSFS_getCdRomDirs();
  1598. char **i;
  1599. for (i = cds; *i != NULL; i++)
  1600. PHYSFS_mount(*i, NULL, 1);
  1601. PHYSFS_freeList(cds);
  1602. } /* if */
  1603. /* Root out archives, and add them to search path... */
  1604. if (archiveExt != NULL)
  1605. {
  1606. setSaneCfgEnumData data;
  1607. memset(&data, '\0', sizeof (data));
  1608. data.archiveExt = archiveExt;
  1609. data.archiveExtLen = strlen(archiveExt);
  1610. data.archivesFirst = archivesFirst;
  1611. data.errcode = PHYSFS_ERR_OK;
  1612. if (!PHYSFS_enumerate("/", setSaneCfgEnumCallback, &data))
  1613. {
  1614. /* !!! FIXME: use this if we're reporting errors.
  1615. PHYSFS_ErrorCode errcode = currentErrorCode();
  1616. if (errcode == PHYSFS_ERR_APP_CALLBACK)
  1617. errcode = data->errcode; */
  1618. } /* if */
  1619. } /* if */
  1620. return 1;
  1621. } /* PHYSFS_setSaneConfig */
  1622. void PHYSFS_permitSymbolicLinks(int allow)
  1623. {
  1624. allowSymLinks = allow;
  1625. } /* PHYSFS_permitSymbolicLinks */
  1626. int PHYSFS_symbolicLinksPermitted(void)
  1627. {
  1628. return allowSymLinks;
  1629. } /* PHYSFS_symbolicLinksPermitted */
  1630. /*
  1631. * Verify that (fname) (in platform-independent notation), in relation
  1632. * to (h) is secure. That means that each element of fname is checked
  1633. * for symlinks (if they aren't permitted). This also allows for quick
  1634. * rejection of files that exist outside an archive's mountpoint.
  1635. *
  1636. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  1637. * at a time), you should always pass zero for "allowMissing" for efficiency.
  1638. *
  1639. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  1640. * since it will make sure that path names are in the right format for
  1641. * passing certain checks. It will also do checks for "insecure" pathnames
  1642. * like ".." which should be done once instead of once per archive. This also
  1643. * gives us license to treat (fname) as scratch space in this function.
  1644. *
  1645. * (fname)'s buffer must have enough space available before it for this
  1646. * function to prepend any root directory for this DirHandle.
  1647. *
  1648. * Returns non-zero if string is safe, zero if there's a security issue.
  1649. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  1650. * updated to point past any mount point elements so it is prepared to
  1651. * be used with the archiver directly.
  1652. */
  1653. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1654. {
  1655. char *fname = *_fname;
  1656. int retval = 1;
  1657. char *start;
  1658. char *end;
  1659. if ((*fname == '\0') && (!h->root)) /* quick rejection. */
  1660. return 1;
  1661. /* !!! FIXME: This codeblock sucks. */
  1662. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1663. {
  1664. size_t mntpntlen = strlen(h->mountPoint);
  1665. size_t len = strlen(fname);
  1666. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1667. /* not under the mountpoint, so skip this archive. */
  1668. BAIL_IF(len < mntpntlen-1, PHYSFS_ERR_NOT_FOUND, 0);
  1669. /* !!! FIXME: Case insensitive? */
  1670. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1671. BAIL_IF(retval != 0, PHYSFS_ERR_NOT_FOUND, 0);
  1672. if (len > mntpntlen-1) /* corner case... */
  1673. BAIL_IF(fname[mntpntlen-1]!='/', PHYSFS_ERR_NOT_FOUND, 0);
  1674. fname += mntpntlen-1; /* move to start of actual archive path. */
  1675. if (*fname == '/')
  1676. fname++;
  1677. *_fname = fname; /* skip mountpoint for later use. */
  1678. retval = 1; /* may be reset, below. */
  1679. } /* if */
  1680. /* prepend the root directory, if any. */
  1681. if (h->root)
  1682. {
  1683. const int isempty = (*fname == '\0');
  1684. fname -= h->rootlen - 1;
  1685. strcpy(fname, h->root);
  1686. if (!isempty)
  1687. fname[h->rootlen - 2] = '/';
  1688. *_fname = fname;
  1689. } /* if */
  1690. start = fname;
  1691. if (!allowSymLinks)
  1692. {
  1693. while (1)
  1694. {
  1695. PHYSFS_Stat statbuf;
  1696. int rc = 0;
  1697. end = strchr(start, '/');
  1698. if (end != NULL) *end = '\0';
  1699. rc = h->funcs->stat(h->opaque, fname, &statbuf);
  1700. if (rc)
  1701. rc = (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  1702. else if (currentErrorCode() == PHYSFS_ERR_NOT_FOUND)
  1703. retval = 0;
  1704. if (end != NULL) *end = '/';
  1705. /* insecure path (has a disallowed symlink in it)? */
  1706. BAIL_IF(rc, PHYSFS_ERR_SYMLINK_FORBIDDEN, 0);
  1707. /* break out early if path element is missing. */
  1708. if (!retval)
  1709. {
  1710. /*
  1711. * We need to clear it if it's the last element of the path,
  1712. * since this might be a non-existant file we're opening
  1713. * for writing...
  1714. */
  1715. if ((end == NULL) || (allowMissing))
  1716. retval = 1;
  1717. break;
  1718. } /* if */
  1719. if (end == NULL)
  1720. break;
  1721. start = end + 1;
  1722. } /* while */
  1723. } /* if */
  1724. return retval;
  1725. } /* verifyPath */
  1726. /* This must hold the stateLock before calling. */
  1727. static int doMkdir(const char *_dname, char *dname)
  1728. {
  1729. DirHandle *h = writeDir;
  1730. char *start;
  1731. char *end;
  1732. int retval = 0;
  1733. int exists = 1; /* force existance check on first path element. */
  1734. assert(h != NULL);
  1735. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPathWithRoot(h, _dname, dname), 0);
  1736. BAIL_IF_ERRPASS(!verifyPath(h, &dname, 1), 0);
  1737. start = dname;
  1738. while (1)
  1739. {
  1740. end = strchr(start, '/');
  1741. if (end != NULL)
  1742. *end = '\0';
  1743. /* only check for existance if all parent dirs existed, too... */
  1744. if (exists)
  1745. {
  1746. PHYSFS_Stat statbuf;
  1747. const int rc = h->funcs->stat(h->opaque, dname, &statbuf);
  1748. if ((!rc) && (currentErrorCode() == PHYSFS_ERR_NOT_FOUND))
  1749. exists = 0;
  1750. retval = ((rc) && (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY));
  1751. } /* if */
  1752. if (!exists)
  1753. retval = h->funcs->mkdir(h->opaque, dname);
  1754. if (!retval)
  1755. break;
  1756. if (end == NULL)
  1757. break;
  1758. *end = '/';
  1759. start = end + 1;
  1760. } /* while */
  1761. return retval;
  1762. } /* doMkdir */
  1763. int PHYSFS_mkdir(const char *_dname)
  1764. {
  1765. int retval = 0;
  1766. char *dname;
  1767. size_t len;
  1768. BAIL_IF(!_dname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1769. __PHYSFS_platformGrabMutex(stateLock);
  1770. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1771. len = strlen(_dname) + dirHandleRootLen(writeDir) + 1;
  1772. dname = (char *) __PHYSFS_smallAlloc(len);
  1773. BAIL_IF_MUTEX(!dname, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, 0);
  1774. retval = doMkdir(_dname, dname);
  1775. __PHYSFS_platformReleaseMutex(stateLock);
  1776. __PHYSFS_smallFree(dname);
  1777. return retval;
  1778. } /* PHYSFS_mkdir */
  1779. /* This must hold the stateLock before calling. */
  1780. static int doDelete(const char *_fname, char *fname)
  1781. {
  1782. DirHandle *h = writeDir;
  1783. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPathWithRoot(h, _fname, fname), 0);
  1784. BAIL_IF_ERRPASS(!verifyPath(h, &fname, 0), 0);
  1785. return h->funcs->remove(h->opaque, fname);
  1786. } /* doDelete */
  1787. int PHYSFS_delete(const char *_fname)
  1788. {
  1789. int retval;
  1790. char *fname;
  1791. size_t len;
  1792. __PHYSFS_platformGrabMutex(stateLock);
  1793. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1794. len = strlen(_fname) + dirHandleRootLen(writeDir) + 1;
  1795. fname = (char *) __PHYSFS_smallAlloc(len);
  1796. BAIL_IF_MUTEX(!fname, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, 0);
  1797. retval = doDelete(_fname, fname);
  1798. __PHYSFS_platformReleaseMutex(stateLock);
  1799. __PHYSFS_smallFree(fname);
  1800. return retval;
  1801. } /* PHYSFS_delete */
  1802. static DirHandle *getRealDirHandle(const char *_fname)
  1803. {
  1804. DirHandle *retval = NULL;
  1805. char *allocated_fname = NULL;
  1806. char *fname = NULL;
  1807. size_t len;
  1808. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1809. __PHYSFS_platformGrabMutex(stateLock);
  1810. len = strlen(_fname) + longest_root + 1;
  1811. allocated_fname = __PHYSFS_smallAlloc(len);
  1812. BAIL_IF_MUTEX(!allocated_fname, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, NULL);
  1813. fname = allocated_fname + longest_root;
  1814. if (sanitizePlatformIndependentPath(_fname, fname))
  1815. {
  1816. DirHandle *i;
  1817. for (i = searchPath; i != NULL; i = i->next)
  1818. {
  1819. char *arcfname = fname;
  1820. if (partOfMountPoint(i, arcfname))
  1821. {
  1822. retval = i;
  1823. break;
  1824. } /* if */
  1825. else if (verifyPath(i, &arcfname, 0))
  1826. {
  1827. PHYSFS_Stat statbuf;
  1828. if (i->funcs->stat(i->opaque, arcfname, &statbuf))
  1829. {
  1830. retval = i;
  1831. break;
  1832. } /* if */
  1833. } /* if */
  1834. } /* for */
  1835. } /* if */
  1836. __PHYSFS_platformReleaseMutex(stateLock);
  1837. __PHYSFS_smallFree(allocated_fname);
  1838. return retval;
  1839. } /* getRealDirHandle */
  1840. const char *PHYSFS_getRealDir(const char *fname)
  1841. {
  1842. DirHandle *dh = getRealDirHandle(fname);
  1843. return dh ? dh->dirName : NULL;
  1844. } /* PHYSFS_getRealDir */
  1845. static int locateInStringList(const char *str,
  1846. char **list,
  1847. PHYSFS_uint32 *pos)
  1848. {
  1849. PHYSFS_uint32 len = *pos;
  1850. PHYSFS_uint32 half_len;
  1851. PHYSFS_uint32 lo = 0;
  1852. PHYSFS_uint32 middle;
  1853. int cmp;
  1854. while (len > 0)
  1855. {
  1856. half_len = len >> 1;
  1857. middle = lo + half_len;
  1858. cmp = strcmp(list[middle], str);
  1859. if (cmp == 0) /* it's in the list already. */
  1860. return 1;
  1861. else if (cmp > 0)
  1862. len = half_len;
  1863. else
  1864. {
  1865. lo = middle + 1;
  1866. len -= half_len + 1;
  1867. } /* else */
  1868. } /* while */
  1869. *pos = lo;
  1870. return 0;
  1871. } /* locateInStringList */
  1872. static PHYSFS_EnumerateCallbackResult enumFilesCallback(void *data,
  1873. const char *origdir, const char *str)
  1874. {
  1875. PHYSFS_uint32 pos;
  1876. void *ptr;
  1877. char *newstr;
  1878. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1879. /*
  1880. * See if file is in the list already, and if not, insert it in there
  1881. * alphabetically...
  1882. */
  1883. pos = pecd->size;
  1884. if (locateInStringList(str, pecd->list, &pos))
  1885. return PHYSFS_ENUM_OK; /* already in the list, but keep going. */
  1886. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1887. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1888. if (ptr != NULL)
  1889. pecd->list = (char **) ptr;
  1890. if ((ptr == NULL) || (newstr == NULL))
  1891. {
  1892. if (newstr)
  1893. allocator.Free(newstr);
  1894. pecd->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1895. return PHYSFS_ENUM_ERROR; /* better luck next time. */
  1896. } /* if */
  1897. strcpy(newstr, str);
  1898. if (pos != pecd->size)
  1899. {
  1900. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1901. sizeof (char *) * ((pecd->size) - pos));
  1902. } /* if */
  1903. pecd->list[pos] = newstr;
  1904. pecd->size++;
  1905. return PHYSFS_ENUM_OK;
  1906. } /* enumFilesCallback */
  1907. char **PHYSFS_enumerateFiles(const char *path)
  1908. {
  1909. EnumStringListCallbackData ecd;
  1910. memset(&ecd, '\0', sizeof (ecd));
  1911. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1912. BAIL_IF(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  1913. if (!PHYSFS_enumerate(path, enumFilesCallback, &ecd))
  1914. {
  1915. const PHYSFS_ErrorCode errcode = currentErrorCode();
  1916. PHYSFS_uint32 i;
  1917. for (i = 0; i < ecd.size; i++)
  1918. allocator.Free(ecd.list[i]);
  1919. allocator.Free(ecd.list);
  1920. BAIL_IF(errcode == PHYSFS_ERR_APP_CALLBACK, ecd.errcode, NULL);
  1921. return NULL;
  1922. } /* if */
  1923. ecd.list[ecd.size] = NULL;
  1924. return ecd.list;
  1925. } /* PHYSFS_enumerateFiles */
  1926. /*
  1927. * Broke out to seperate function so we can use stack allocation gratuitously.
  1928. */
  1929. static PHYSFS_EnumerateCallbackResult enumerateFromMountPoint(DirHandle *i,
  1930. const char *arcfname,
  1931. PHYSFS_EnumerateCallback callback,
  1932. const char *_fname, void *data)
  1933. {
  1934. PHYSFS_EnumerateCallbackResult retval;
  1935. const size_t len = strlen(arcfname);
  1936. char *ptr = NULL;
  1937. char *end = NULL;
  1938. const size_t slen = strlen(i->mountPoint) + 1;
  1939. char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
  1940. BAIL_IF(!mountPoint, PHYSFS_ERR_OUT_OF_MEMORY, PHYSFS_ENUM_ERROR);
  1941. strcpy(mountPoint, i->mountPoint);
  1942. ptr = mountPoint + ((len) ? len + 1 : 0);
  1943. end = strchr(ptr, '/');
  1944. assert(end); /* should always find a terminating '/'. */
  1945. *end = '\0';
  1946. retval = callback(data, _fname, ptr);
  1947. __PHYSFS_smallFree(mountPoint);
  1948. BAIL_IF(retval == PHYSFS_ENUM_ERROR, PHYSFS_ERR_APP_CALLBACK, retval);
  1949. return retval;
  1950. } /* enumerateFromMountPoint */
  1951. typedef struct SymlinkFilterData
  1952. {
  1953. PHYSFS_EnumerateCallback callback;
  1954. void *callbackData;
  1955. DirHandle *dirhandle;
  1956. const char *arcfname;
  1957. PHYSFS_ErrorCode errcode;
  1958. } SymlinkFilterData;
  1959. static PHYSFS_EnumerateCallbackResult enumCallbackFilterSymLinks(void *_data,
  1960. const char *origdir, const char *fname)
  1961. {
  1962. SymlinkFilterData *data = (SymlinkFilterData *) _data;
  1963. const DirHandle *dh = data->dirhandle;
  1964. const char *arcfname = data->arcfname;
  1965. PHYSFS_Stat statbuf;
  1966. const char *trimmedDir = (*arcfname == '/') ? (arcfname + 1) : arcfname;
  1967. const size_t slen = strlen(trimmedDir) + strlen(fname) + 2;
  1968. char *path = (char *) __PHYSFS_smallAlloc(slen);
  1969. PHYSFS_EnumerateCallbackResult retval = PHYSFS_ENUM_OK;
  1970. if (path == NULL)
  1971. {
  1972. data->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  1973. return PHYSFS_ENUM_ERROR;
  1974. } /* if */
  1975. snprintf(path, slen, "%s%s%s", trimmedDir, *trimmedDir ? "/" : "", fname);
  1976. if (!dh->funcs->stat(dh->opaque, path, &statbuf))
  1977. {
  1978. data->errcode = currentErrorCode();
  1979. retval = PHYSFS_ENUM_ERROR;
  1980. } /* if */
  1981. else
  1982. {
  1983. /* Pass it on to the application if it's not a symlink. */
  1984. if (statbuf.filetype != PHYSFS_FILETYPE_SYMLINK)
  1985. {
  1986. retval = data->callback(data->callbackData, origdir, fname);
  1987. if (retval == PHYSFS_ENUM_ERROR)
  1988. data->errcode = PHYSFS_ERR_APP_CALLBACK;
  1989. } /* if */
  1990. } /* else */
  1991. __PHYSFS_smallFree(path);
  1992. return retval;
  1993. } /* enumCallbackFilterSymLinks */
  1994. int PHYSFS_enumerate(const char *_fn, PHYSFS_EnumerateCallback cb, void *data)
  1995. {
  1996. PHYSFS_EnumerateCallbackResult retval = PHYSFS_ENUM_OK;
  1997. size_t len;
  1998. char *allocated_fname;
  1999. char *fname;
  2000. BAIL_IF(!_fn, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2001. BAIL_IF(!cb, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2002. __PHYSFS_platformGrabMutex(stateLock);
  2003. len = strlen(_fn) + longest_root + 1;
  2004. allocated_fname = (char *) __PHYSFS_smallAlloc(len);
  2005. BAIL_IF_MUTEX(!allocated_fname, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, 0);
  2006. fname = allocated_fname + longest_root;
  2007. if (!sanitizePlatformIndependentPath(_fn, fname))
  2008. retval = PHYSFS_ENUM_STOP;
  2009. else
  2010. {
  2011. DirHandle *i;
  2012. SymlinkFilterData filterdata;
  2013. if (!allowSymLinks)
  2014. {
  2015. memset(&filterdata, '\0', sizeof (filterdata));
  2016. filterdata.callback = cb;
  2017. filterdata.callbackData = data;
  2018. } /* if */
  2019. for (i = searchPath; (retval == PHYSFS_ENUM_OK) && i; i = i->next)
  2020. {
  2021. char *arcfname = fname;
  2022. if (partOfMountPoint(i, arcfname))
  2023. retval = enumerateFromMountPoint(i, arcfname, cb, _fn, data);
  2024. else if (verifyPath(i, &arcfname, 0))
  2025. {
  2026. PHYSFS_Stat statbuf;
  2027. if (!i->funcs->stat(i->opaque, arcfname, &statbuf))
  2028. {
  2029. if (currentErrorCode() == PHYSFS_ERR_NOT_FOUND)
  2030. continue; /* no such dir in this archive, skip it. */
  2031. } /* if */
  2032. if (statbuf.filetype != PHYSFS_FILETYPE_DIRECTORY)
  2033. continue; /* not a directory in this archive, skip it. */
  2034. else if ((!allowSymLinks) && (i->funcs->info.supportsSymlinks))
  2035. {
  2036. filterdata.dirhandle = i;
  2037. filterdata.arcfname = arcfname;
  2038. filterdata.errcode = PHYSFS_ERR_OK;
  2039. retval = i->funcs->enumerate(i->opaque, arcfname,
  2040. enumCallbackFilterSymLinks,
  2041. _fn, &filterdata);
  2042. if (retval == PHYSFS_ENUM_ERROR)
  2043. {
  2044. if (currentErrorCode() == PHYSFS_ERR_APP_CALLBACK)
  2045. PHYSFS_setErrorCode(filterdata.errcode);
  2046. } /* if */
  2047. } /* else if */
  2048. else
  2049. {
  2050. retval = i->funcs->enumerate(i->opaque, arcfname,
  2051. cb, _fn, data);
  2052. } /* else */
  2053. } /* else if */
  2054. } /* for */
  2055. } /* if */
  2056. __PHYSFS_platformReleaseMutex(stateLock);
  2057. __PHYSFS_smallFree(allocated_fname);
  2058. return (retval == PHYSFS_ENUM_ERROR) ? 0 : 1;
  2059. } /* PHYSFS_enumerate */
  2060. typedef struct
  2061. {
  2062. PHYSFS_EnumFilesCallback callback;
  2063. void *data;
  2064. } LegacyEnumFilesCallbackData;
  2065. static PHYSFS_EnumerateCallbackResult enumFilesCallbackAlwaysSucceed(void *d,
  2066. const char *origdir, const char *fname)
  2067. {
  2068. LegacyEnumFilesCallbackData *cbdata = (LegacyEnumFilesCallbackData *) d;
  2069. cbdata->callback(cbdata->data, origdir, fname);
  2070. return PHYSFS_ENUM_OK;
  2071. } /* enumFilesCallbackAlwaysSucceed */
  2072. void PHYSFS_enumerateFilesCallback(const char *fname,
  2073. PHYSFS_EnumFilesCallback callback,
  2074. void *data)
  2075. {
  2076. LegacyEnumFilesCallbackData cbdata;
  2077. cbdata.callback = callback;
  2078. cbdata.data = data;
  2079. (void) PHYSFS_enumerate(fname, enumFilesCallbackAlwaysSucceed, &cbdata);
  2080. } /* PHYSFS_enumerateFilesCallback */
  2081. int PHYSFS_exists(const char *fname)
  2082. {
  2083. return (getRealDirHandle(fname) != NULL);
  2084. } /* PHYSFS_exists */
  2085. PHYSFS_sint64 PHYSFS_getLastModTime(const char *fname)
  2086. {
  2087. PHYSFS_Stat statbuf;
  2088. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), -1);
  2089. return statbuf.modtime;
  2090. } /* PHYSFS_getLastModTime */
  2091. int PHYSFS_isDirectory(const char *fname)
  2092. {
  2093. PHYSFS_Stat statbuf;
  2094. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  2095. return (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY);
  2096. } /* PHYSFS_isDirectory */
  2097. int PHYSFS_isSymbolicLink(const char *fname)
  2098. {
  2099. PHYSFS_Stat statbuf;
  2100. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  2101. return (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  2102. } /* PHYSFS_isSymbolicLink */
  2103. static PHYSFS_File *doOpenWrite(const char *_fname, const int appending)
  2104. {
  2105. FileHandle *fh = NULL;
  2106. DirHandle *h;
  2107. size_t len;
  2108. char *fname;
  2109. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2110. __PHYSFS_platformGrabMutex(stateLock);
  2111. h = writeDir;
  2112. BAIL_IF_MUTEX(!h, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  2113. len = strlen(_fname) + dirHandleRootLen(h) + 1;
  2114. fname = (char *) __PHYSFS_smallAlloc(len);
  2115. BAIL_IF_MUTEX(!fname, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, 0);
  2116. if (sanitizePlatformIndependentPathWithRoot(h, _fname, fname))
  2117. {
  2118. PHYSFS_Io *io = NULL;
  2119. char *arcfname = fname;
  2120. if (verifyPath(h, &arcfname, 0))
  2121. {
  2122. const PHYSFS_Archiver *f = h->funcs;
  2123. if (appending)
  2124. io = f->openAppend(h->opaque, arcfname);
  2125. else
  2126. io = f->openWrite(h->opaque, arcfname);
  2127. if (io)
  2128. {
  2129. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  2130. if (fh == NULL)
  2131. {
  2132. io->destroy(io);
  2133. PHYSFS_setErrorCode(PHYSFS_ERR_OUT_OF_MEMORY);
  2134. } /* if */
  2135. else
  2136. {
  2137. memset(fh, '\0', sizeof (FileHandle));
  2138. fh->io = io;
  2139. fh->dirHandle = h;
  2140. fh->next = openWriteList;
  2141. openWriteList = fh;
  2142. } /* else */
  2143. } /* if */
  2144. } /* if */
  2145. } /* if */
  2146. __PHYSFS_platformReleaseMutex(stateLock);
  2147. __PHYSFS_smallFree(fname);
  2148. return ((PHYSFS_File *) fh);
  2149. } /* doOpenWrite */
  2150. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  2151. {
  2152. return doOpenWrite(filename, 0);
  2153. } /* PHYSFS_openWrite */
  2154. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  2155. {
  2156. return doOpenWrite(filename, 1);
  2157. } /* PHYSFS_openAppend */
  2158. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  2159. {
  2160. FileHandle *fh = NULL;
  2161. char *allocated_fname;
  2162. char *fname;
  2163. size_t len;
  2164. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2165. __PHYSFS_platformGrabMutex(stateLock);
  2166. BAIL_IF_MUTEX(!searchPath, PHYSFS_ERR_NOT_FOUND, stateLock, 0);
  2167. len = strlen(_fname) + longest_root + 1;
  2168. allocated_fname = (char *) __PHYSFS_smallAlloc(len);
  2169. BAIL_IF_MUTEX(!allocated_fname, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, 0);
  2170. fname = allocated_fname + longest_root;
  2171. if (sanitizePlatformIndependentPath(_fname, fname))
  2172. {
  2173. PHYSFS_Io *io = NULL;
  2174. DirHandle *i;
  2175. for (i = searchPath; i != NULL; i = i->next)
  2176. {
  2177. char *arcfname = fname;
  2178. if (verifyPath(i, &arcfname, 0))
  2179. {
  2180. io = i->funcs->openRead(i->opaque, arcfname);
  2181. if (io)
  2182. break;
  2183. } /* if */
  2184. } /* for */
  2185. if (io)
  2186. {
  2187. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  2188. if (fh == NULL)
  2189. {
  2190. io->destroy(io);
  2191. PHYSFS_setErrorCode(PHYSFS_ERR_OUT_OF_MEMORY);
  2192. } /* if */
  2193. else
  2194. {
  2195. memset(fh, '\0', sizeof (FileHandle));
  2196. fh->io = io;
  2197. fh->forReading = 1;
  2198. fh->dirHandle = i;
  2199. fh->next = openReadList;
  2200. openReadList = fh;
  2201. } /* else */
  2202. } /* if */
  2203. } /* if */
  2204. __PHYSFS_platformReleaseMutex(stateLock);
  2205. __PHYSFS_smallFree(allocated_fname);
  2206. return ((PHYSFS_File *) fh);
  2207. } /* PHYSFS_openRead */
  2208. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  2209. {
  2210. FileHandle *prev = NULL;
  2211. FileHandle *i;
  2212. for (i = *list; i != NULL; i = i->next)
  2213. {
  2214. if (i == handle) /* handle is in this list? */
  2215. {
  2216. PHYSFS_Io *io = handle->io;
  2217. PHYSFS_uint8 *tmp = handle->buffer;
  2218. /* send our buffer to io... */
  2219. if (!handle->forReading)
  2220. {
  2221. if (!PHYSFS_flush((PHYSFS_File *) handle))
  2222. return -1;
  2223. /* ...then have io send it to the disk... */
  2224. else if (io->flush && !io->flush(io))
  2225. return -1;
  2226. } /* if */
  2227. /* ...then close the underlying file. */
  2228. io->destroy(io);
  2229. if (tmp != NULL) /* free any associated buffer. */
  2230. allocator.Free(tmp);
  2231. if (prev == NULL)
  2232. *list = handle->next;
  2233. else
  2234. prev->next = handle->next;
  2235. allocator.Free(handle);
  2236. return 1;
  2237. } /* if */
  2238. prev = i;
  2239. } /* for */
  2240. return 0;
  2241. } /* closeHandleInOpenList */
  2242. int PHYSFS_close(PHYSFS_File *_handle)
  2243. {
  2244. FileHandle *handle = (FileHandle *) _handle;
  2245. int rc;
  2246. __PHYSFS_platformGrabMutex(stateLock);
  2247. /* -1 == close failure. 0 == not found. 1 == success. */
  2248. rc = closeHandleInOpenList(&openReadList, handle);
  2249. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2250. if (!rc)
  2251. {
  2252. rc = closeHandleInOpenList(&openWriteList, handle);
  2253. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2254. } /* if */
  2255. __PHYSFS_platformReleaseMutex(stateLock);
  2256. BAIL_IF(!rc, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2257. return 1;
  2258. } /* PHYSFS_close */
  2259. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *_buffer, size_t len)
  2260. {
  2261. PHYSFS_uint8 *buffer = (PHYSFS_uint8 *) _buffer;
  2262. PHYSFS_sint64 retval = 0;
  2263. while (len > 0)
  2264. {
  2265. const size_t avail = fh->buffill - fh->bufpos;
  2266. if (avail > 0) /* data available in the buffer. */
  2267. {
  2268. const size_t cpy = (len < avail) ? len : avail;
  2269. memcpy(buffer, fh->buffer + fh->bufpos, cpy);
  2270. assert(len >= cpy);
  2271. buffer += cpy;
  2272. len -= cpy;
  2273. fh->bufpos += cpy;
  2274. retval += cpy;
  2275. } /* if */
  2276. else /* buffer is empty, refill it. */
  2277. {
  2278. PHYSFS_Io *io = fh->io;
  2279. const PHYSFS_sint64 rc = io->read(io, fh->buffer, fh->bufsize);
  2280. fh->bufpos = 0;
  2281. if (rc > 0)
  2282. fh->buffill = (size_t) rc;
  2283. else
  2284. {
  2285. fh->buffill = 0;
  2286. if (retval == 0) /* report already-read data, or failure. */
  2287. retval = rc;
  2288. break;
  2289. } /* else */
  2290. } /* else */
  2291. } /* while */
  2292. return retval;
  2293. } /* doBufferedRead */
  2294. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  2295. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2296. {
  2297. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2298. const PHYSFS_sint64 retval = PHYSFS_readBytes(handle, buffer, len);
  2299. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2300. } /* PHYSFS_read */
  2301. PHYSFS_sint64 PHYSFS_readBytes(PHYSFS_File *handle, void *buffer,
  2302. PHYSFS_uint64 _len)
  2303. {
  2304. const size_t len = (size_t) _len;
  2305. FileHandle *fh = (FileHandle *) handle;
  2306. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2307. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2308. #else
  2309. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2310. #endif
  2311. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2312. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2313. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2314. BAIL_IF(!fh->forReading, PHYSFS_ERR_OPEN_FOR_WRITING, -1);
  2315. BAIL_IF_ERRPASS(len == 0, 0);
  2316. if (fh->buffer)
  2317. return doBufferedRead(fh, buffer, len);
  2318. return fh->io->read(fh->io, buffer, len);
  2319. } /* PHYSFS_readBytes */
  2320. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  2321. const size_t len)
  2322. {
  2323. FileHandle *fh = (FileHandle *) handle;
  2324. /* whole thing fits in the buffer? */
  2325. if ((fh->buffill + len) < fh->bufsize)
  2326. {
  2327. memcpy(fh->buffer + fh->buffill, buffer, len);
  2328. fh->buffill += len;
  2329. return (PHYSFS_sint64) len;
  2330. } /* if */
  2331. /* would overflow buffer. Flush and then write the new objects, too. */
  2332. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), -1);
  2333. return fh->io->write(fh->io, buffer, len);
  2334. } /* doBufferedWrite */
  2335. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  2336. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2337. {
  2338. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2339. const PHYSFS_sint64 retval = PHYSFS_writeBytes(handle, buffer, len);
  2340. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2341. } /* PHYSFS_write */
  2342. PHYSFS_sint64 PHYSFS_writeBytes(PHYSFS_File *handle, const void *buffer,
  2343. PHYSFS_uint64 _len)
  2344. {
  2345. const size_t len = (size_t) _len;
  2346. FileHandle *fh = (FileHandle *) handle;
  2347. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2348. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2349. #else
  2350. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2351. #endif
  2352. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2353. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2354. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2355. BAIL_IF(fh->forReading, PHYSFS_ERR_OPEN_FOR_READING, -1);
  2356. BAIL_IF_ERRPASS(len == 0, 0);
  2357. if (fh->buffer)
  2358. return doBufferedWrite(handle, buffer, len);
  2359. return fh->io->write(fh->io, buffer, len);
  2360. } /* PHYSFS_write */
  2361. int PHYSFS_eof(PHYSFS_File *handle)
  2362. {
  2363. FileHandle *fh = (FileHandle *) handle;
  2364. if (!fh->forReading) /* never EOF on files opened for write/append. */
  2365. return 0;
  2366. /* can't be eof if buffer isn't empty */
  2367. if (fh->bufpos == fh->buffill)
  2368. {
  2369. /* check the Io. */
  2370. PHYSFS_Io *io = fh->io;
  2371. const PHYSFS_sint64 pos = io->tell(io);
  2372. const PHYSFS_sint64 len = io->length(io);
  2373. if ((pos < 0) || (len < 0))
  2374. return 0; /* beats me. */
  2375. return (pos >= len);
  2376. } /* if */
  2377. return 0;
  2378. } /* PHYSFS_eof */
  2379. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  2380. {
  2381. FileHandle *fh = (FileHandle *) handle;
  2382. const PHYSFS_sint64 pos = fh->io->tell(fh->io);
  2383. const PHYSFS_sint64 retval = fh->forReading ?
  2384. (pos - fh->buffill) + fh->bufpos :
  2385. (pos + fh->buffill);
  2386. return retval;
  2387. } /* PHYSFS_tell */
  2388. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  2389. {
  2390. FileHandle *fh = (FileHandle *) handle;
  2391. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2392. if (fh->buffer && fh->forReading)
  2393. {
  2394. /* avoid throwing away our precious buffer if seeking within it. */
  2395. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  2396. if ( /* seeking within the already-buffered range? */
  2397. /* forward? */
  2398. ((offset >= 0) && (((size_t)offset) <= fh->buffill-fh->bufpos)) ||
  2399. /* backward? */
  2400. ((offset < 0) && (((size_t) -offset) <= fh->bufpos)) )
  2401. {
  2402. fh->bufpos = (size_t) (((PHYSFS_sint64) fh->bufpos) + offset);
  2403. return 1; /* successful seek */
  2404. } /* if */
  2405. } /* if */
  2406. /* we have to fall back to a 'raw' seek. */
  2407. fh->buffill = fh->bufpos = 0;
  2408. return fh->io->seek(fh->io, pos);
  2409. } /* PHYSFS_seek */
  2410. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  2411. {
  2412. PHYSFS_Io *io = ((FileHandle *) handle)->io;
  2413. return io->length(io);
  2414. } /* PHYSFS_filelength */
  2415. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  2416. {
  2417. FileHandle *fh = (FileHandle *) handle;
  2418. const size_t bufsize = (size_t) _bufsize;
  2419. if (!__PHYSFS_ui64FitsAddressSpace(_bufsize))
  2420. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2421. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2422. /*
  2423. * For reads, we need to move the file pointer to where it would be
  2424. * if we weren't buffering, so that the next read will get the
  2425. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  2426. */
  2427. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  2428. {
  2429. PHYSFS_uint64 pos;
  2430. const PHYSFS_sint64 curpos = fh->io->tell(fh->io);
  2431. BAIL_IF_ERRPASS(curpos == -1, 0);
  2432. pos = ((curpos - fh->buffill) + fh->bufpos);
  2433. BAIL_IF_ERRPASS(!fh->io->seek(fh->io, pos), 0);
  2434. } /* if */
  2435. if (bufsize == 0) /* delete existing buffer. */
  2436. {
  2437. if (fh->buffer)
  2438. {
  2439. allocator.Free(fh->buffer);
  2440. fh->buffer = NULL;
  2441. } /* if */
  2442. } /* if */
  2443. else
  2444. {
  2445. PHYSFS_uint8 *newbuf;
  2446. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  2447. BAIL_IF(!newbuf, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2448. fh->buffer = newbuf;
  2449. } /* else */
  2450. fh->bufsize = bufsize;
  2451. fh->buffill = fh->bufpos = 0;
  2452. return 1;
  2453. } /* PHYSFS_setBuffer */
  2454. int PHYSFS_flush(PHYSFS_File *handle)
  2455. {
  2456. FileHandle *fh = (FileHandle *) handle;
  2457. PHYSFS_Io *io;
  2458. PHYSFS_sint64 rc;
  2459. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  2460. return 1; /* open for read or buffer empty are successful no-ops. */
  2461. /* dump buffer to disk. */
  2462. io = fh->io;
  2463. rc = io->write(io, fh->buffer + fh->bufpos, fh->buffill - fh->bufpos);
  2464. BAIL_IF_ERRPASS(rc <= 0, 0);
  2465. fh->bufpos = fh->buffill = 0;
  2466. return 1;
  2467. } /* PHYSFS_flush */
  2468. int PHYSFS_stat(const char *_fname, PHYSFS_Stat *stat)
  2469. {
  2470. int retval = 0;
  2471. char *allocated_fname;
  2472. char *fname;
  2473. size_t len;
  2474. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2475. BAIL_IF(!stat, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2476. /* set some sane defaults... */
  2477. stat->filesize = -1;
  2478. stat->modtime = -1;
  2479. stat->createtime = -1;
  2480. stat->accesstime = -1;
  2481. stat->filetype = PHYSFS_FILETYPE_OTHER;
  2482. stat->readonly = 1;
  2483. __PHYSFS_platformGrabMutex(stateLock);
  2484. len = strlen(_fname) + longest_root + 1;
  2485. allocated_fname = (char *) __PHYSFS_smallAlloc(len);
  2486. BAIL_IF_MUTEX(!allocated_fname, PHYSFS_ERR_OUT_OF_MEMORY, stateLock, 0);
  2487. fname = allocated_fname + longest_root;
  2488. if (sanitizePlatformIndependentPath(_fname, fname))
  2489. {
  2490. if (*fname == '\0')
  2491. {
  2492. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2493. stat->readonly = !writeDir; /* Writeable if we have a writeDir */
  2494. retval = 1;
  2495. } /* if */
  2496. else
  2497. {
  2498. DirHandle *i;
  2499. int exists = 0;
  2500. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  2501. {
  2502. char *arcfname = fname;
  2503. exists = partOfMountPoint(i, arcfname);
  2504. if (exists)
  2505. {
  2506. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2507. stat->readonly = 1;
  2508. retval = 1;
  2509. } /* if */
  2510. else if (verifyPath(i, &arcfname, 0))
  2511. {
  2512. retval = i->funcs->stat(i->opaque, arcfname, stat);
  2513. if ((retval) || (currentErrorCode() != PHYSFS_ERR_NOT_FOUND))
  2514. exists = 1;
  2515. } /* else if */
  2516. } /* for */
  2517. } /* else */
  2518. } /* if */
  2519. __PHYSFS_platformReleaseMutex(stateLock);
  2520. __PHYSFS_smallFree(allocated_fname);
  2521. return retval;
  2522. } /* PHYSFS_stat */
  2523. int __PHYSFS_readAll(PHYSFS_Io *io, void *buf, const size_t _len)
  2524. {
  2525. const PHYSFS_uint64 len = (PHYSFS_uint64) _len;
  2526. return (io->read(io, buf, len) == len);
  2527. } /* __PHYSFS_readAll */
  2528. void *__PHYSFS_initSmallAlloc(void *ptr, const size_t len)
  2529. {
  2530. void *useHeap = ((ptr == NULL) ? ((void *) 1) : ((void *) 0));
  2531. if (useHeap) /* too large for stack allocation or alloca() failed. */
  2532. ptr = allocator.Malloc(len+sizeof (void *));
  2533. if (ptr != NULL)
  2534. {
  2535. void **retval = (void **) ptr;
  2536. /*printf("%s alloc'd (%lld) bytes at (%p).\n",
  2537. useHeap ? "heap" : "stack", (long long) len, ptr);*/
  2538. *retval = useHeap;
  2539. return retval + 1;
  2540. } /* if */
  2541. return NULL; /* allocation failed. */
  2542. } /* __PHYSFS_initSmallAlloc */
  2543. void __PHYSFS_smallFree(void *ptr)
  2544. {
  2545. if (ptr != NULL)
  2546. {
  2547. void **block = ((void **) ptr) - 1;
  2548. const int useHeap = (*block != NULL);
  2549. if (useHeap)
  2550. allocator.Free(block);
  2551. /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
  2552. } /* if */
  2553. } /* __PHYSFS_smallFree */
  2554. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  2555. {
  2556. BAIL_IF(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
  2557. externalAllocator = (a != NULL);
  2558. if (externalAllocator)
  2559. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  2560. return 1;
  2561. } /* PHYSFS_setAllocator */
  2562. const PHYSFS_Allocator *PHYSFS_getAllocator(void)
  2563. {
  2564. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
  2565. return &allocator;
  2566. } /* PHYSFS_getAllocator */
  2567. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  2568. {
  2569. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2570. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2571. #undef malloc
  2572. return malloc((size_t) s);
  2573. } /* mallocAllocatorMalloc */
  2574. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  2575. {
  2576. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2577. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2578. #undef realloc
  2579. return realloc(ptr, (size_t) s);
  2580. } /* mallocAllocatorRealloc */
  2581. static void mallocAllocatorFree(void *ptr)
  2582. {
  2583. #undef free
  2584. free(ptr);
  2585. } /* mallocAllocatorFree */
  2586. static void setDefaultAllocator(void)
  2587. {
  2588. assert(!externalAllocator);
  2589. allocator.Init = NULL;
  2590. allocator.Deinit = NULL;
  2591. allocator.Malloc = mallocAllocatorMalloc;
  2592. allocator.Realloc = mallocAllocatorRealloc;
  2593. allocator.Free = mallocAllocatorFree;
  2594. } /* setDefaultAllocator */
  2595. int __PHYSFS_DirTreeInit(__PHYSFS_DirTree *dt, const size_t entrylen)
  2596. {
  2597. static char rootpath[2] = { '/', '\0' };
  2598. size_t alloclen;
  2599. assert(entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2600. memset(dt, '\0', sizeof (*dt));
  2601. dt->root = (__PHYSFS_DirTreeEntry *) allocator.Malloc(entrylen);
  2602. BAIL_IF(!dt->root, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2603. memset(dt->root, '\0', entrylen);
  2604. dt->root->name = rootpath;
  2605. dt->root->isdir = 1;
  2606. dt->hashBuckets = 64;
  2607. if (!dt->hashBuckets)
  2608. dt->hashBuckets = 1;
  2609. dt->entrylen = entrylen;
  2610. alloclen = dt->hashBuckets * sizeof (__PHYSFS_DirTreeEntry *);
  2611. dt->hash = (__PHYSFS_DirTreeEntry **) allocator.Malloc(alloclen);
  2612. BAIL_IF(!dt->hash, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2613. memset(dt->hash, '\0', alloclen);
  2614. return 1;
  2615. } /* __PHYSFS_DirTreeInit */
  2616. static inline PHYSFS_uint32 hashPathName(__PHYSFS_DirTree *dt, const char *name)
  2617. {
  2618. return __PHYSFS_hashString(name, strlen(name)) % dt->hashBuckets;
  2619. } /* hashPathName */
  2620. /* Fill in missing parent directories. */
  2621. static __PHYSFS_DirTreeEntry *addAncestors(__PHYSFS_DirTree *dt, char *name)
  2622. {
  2623. __PHYSFS_DirTreeEntry *retval = dt->root;
  2624. char *sep = strrchr(name, '/');
  2625. if (sep)
  2626. {
  2627. *sep = '\0'; /* chop off last piece. */
  2628. retval = (__PHYSFS_DirTreeEntry *) __PHYSFS_DirTreeFind(dt, name);
  2629. if (retval != NULL)
  2630. {
  2631. *sep = '/';
  2632. BAIL_IF(!retval->isdir, PHYSFS_ERR_CORRUPT, NULL);
  2633. return retval; /* already hashed. */
  2634. } /* if */
  2635. /* okay, this is a new dir. Build and hash us. */
  2636. retval = (__PHYSFS_DirTreeEntry*)__PHYSFS_DirTreeAdd(dt, name, 1);
  2637. *sep = '/';
  2638. } /* if */
  2639. return retval;
  2640. } /* addAncestors */
  2641. void *__PHYSFS_DirTreeAdd(__PHYSFS_DirTree *dt, char *name, const int isdir)
  2642. {
  2643. __PHYSFS_DirTreeEntry *retval = __PHYSFS_DirTreeFind(dt, name);
  2644. if (!retval)
  2645. {
  2646. const size_t alloclen = strlen(name) + 1 + dt->entrylen;
  2647. PHYSFS_uint32 hashval;
  2648. __PHYSFS_DirTreeEntry *parent = addAncestors(dt, name);
  2649. BAIL_IF_ERRPASS(!parent, NULL);
  2650. assert(dt->entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2651. retval = (__PHYSFS_DirTreeEntry *) allocator.Malloc(alloclen);
  2652. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2653. memset(retval, '\0', dt->entrylen);
  2654. retval->name = ((char *) retval) + dt->entrylen;
  2655. strcpy(retval->name, name);
  2656. hashval = hashPathName(dt, name);
  2657. retval->hashnext = dt->hash[hashval];
  2658. dt->hash[hashval] = retval;
  2659. retval->sibling = parent->children;
  2660. retval->isdir = isdir;
  2661. parent->children = retval;
  2662. } /* if */
  2663. return retval;
  2664. } /* __PHYSFS_DirTreeAdd */
  2665. /* Find the __PHYSFS_DirTreeEntry for a path in platform-independent notation. */
  2666. void *__PHYSFS_DirTreeFind(__PHYSFS_DirTree *dt, const char *path)
  2667. {
  2668. PHYSFS_uint32 hashval;
  2669. __PHYSFS_DirTreeEntry *prev = NULL;
  2670. __PHYSFS_DirTreeEntry *retval;
  2671. if (*path == '\0')
  2672. return dt->root;
  2673. hashval = hashPathName(dt, path);
  2674. for (retval = dt->hash[hashval]; retval; retval = retval->hashnext)
  2675. {
  2676. if (strcmp(retval->name, path) == 0)
  2677. {
  2678. if (prev != NULL) /* move this to the front of the list */
  2679. {
  2680. prev->hashnext = retval->hashnext;
  2681. retval->hashnext = dt->hash[hashval];
  2682. dt->hash[hashval] = retval;
  2683. } /* if */
  2684. return retval;
  2685. } /* if */
  2686. prev = retval;
  2687. } /* for */
  2688. BAIL(PHYSFS_ERR_NOT_FOUND, NULL);
  2689. } /* __PHYSFS_DirTreeFind */
  2690. PHYSFS_EnumerateCallbackResult __PHYSFS_DirTreeEnumerate(void *opaque,
  2691. const char *dname, PHYSFS_EnumerateCallback cb,
  2692. const char *origdir, void *callbackdata)
  2693. {
  2694. PHYSFS_EnumerateCallbackResult retval = PHYSFS_ENUM_OK;
  2695. __PHYSFS_DirTree *tree = (__PHYSFS_DirTree *) opaque;
  2696. const __PHYSFS_DirTreeEntry *entry = __PHYSFS_DirTreeFind(tree, dname);
  2697. BAIL_IF(!entry, PHYSFS_ERR_NOT_FOUND, PHYSFS_ENUM_ERROR);
  2698. entry = entry->children;
  2699. while (entry && (retval == PHYSFS_ENUM_OK))
  2700. {
  2701. const char *name = entry->name;
  2702. const char *ptr = strrchr(name, '/');
  2703. retval = cb(callbackdata, origdir, ptr ? ptr + 1 : name);
  2704. BAIL_IF(retval == PHYSFS_ENUM_ERROR, PHYSFS_ERR_APP_CALLBACK, retval);
  2705. entry = entry->sibling;
  2706. } /* while */
  2707. return retval;
  2708. } /* __PHYSFS_DirTreeEnumerate */
  2709. void __PHYSFS_DirTreeDeinit(__PHYSFS_DirTree *dt)
  2710. {
  2711. if (!dt)
  2712. return;
  2713. if (dt->root)
  2714. {
  2715. assert(dt->root->sibling == NULL);
  2716. assert(dt->hash || (dt->root->children == NULL));
  2717. allocator.Free(dt->root);
  2718. } /* if */
  2719. if (dt->hash)
  2720. {
  2721. size_t i;
  2722. for (i = 0; i < dt->hashBuckets; i++)
  2723. {
  2724. __PHYSFS_DirTreeEntry *entry;
  2725. __PHYSFS_DirTreeEntry *next;
  2726. for (entry = dt->hash[i]; entry; entry = next)
  2727. {
  2728. next = entry->hashnext;
  2729. allocator.Free(entry);
  2730. } /* for */
  2731. } /* for */
  2732. allocator.Free(dt->hash);
  2733. } /* if */
  2734. } /* __PHYSFS_DirTreeDeinit */
  2735. /* end of physfs.c ... */