physfs.c 76 KB

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