physfs.c 92 KB

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