physfs.c 98 KB

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