physfs.c 96 KB

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