physfs.c 74 KB

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