physfs.c 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187
  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. return __PHYSFS_platformFlush(io->opaque);
  140. } /* nativeIo_flush */
  141. static void nativeIo_destroy(PHYSFS_Io *io)
  142. {
  143. NativeIoInfo *info = (NativeIoInfo *) io->opaque;
  144. __PHYSFS_platformClose(info->handle);
  145. allocator.Free((void *) info->path);
  146. allocator.Free(info);
  147. allocator.Free(io);
  148. } /* nativeIo_destroy */
  149. static const PHYSFS_Io __PHYSFS_nativeIoInterface =
  150. {
  151. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  152. nativeIo_read,
  153. nativeIo_write,
  154. nativeIo_seek,
  155. nativeIo_tell,
  156. nativeIo_length,
  157. nativeIo_duplicate,
  158. nativeIo_flush,
  159. nativeIo_destroy
  160. };
  161. PHYSFS_Io *__PHYSFS_createNativeIo(const char *path, const int mode)
  162. {
  163. PHYSFS_Io *io = NULL;
  164. NativeIoInfo *info = NULL;
  165. void *handle = NULL;
  166. char *pathdup = NULL;
  167. assert((mode == 'r') || (mode == 'w') || (mode == 'a'));
  168. io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  169. GOTO_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  170. info = (NativeIoInfo *) allocator.Malloc(sizeof (NativeIoInfo));
  171. GOTO_IF(!info, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  172. pathdup = (char *) allocator.Malloc(strlen(path) + 1);
  173. GOTO_IF(!pathdup, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
  174. if (mode == 'r')
  175. handle = __PHYSFS_platformOpenRead(path);
  176. else if (mode == 'w')
  177. handle = __PHYSFS_platformOpenWrite(path);
  178. else if (mode == 'a')
  179. handle = __PHYSFS_platformOpenAppend(path);
  180. GOTO_IF_ERRPASS(!handle, createNativeIo_failed);
  181. strcpy(pathdup, path);
  182. info->handle = handle;
  183. info->path = pathdup;
  184. info->mode = mode;
  185. memcpy(io, &__PHYSFS_nativeIoInterface, sizeof (*io));
  186. io->opaque = info;
  187. return io;
  188. createNativeIo_failed:
  189. if (handle != NULL) __PHYSFS_platformClose(handle);
  190. if (pathdup != NULL) allocator.Free(pathdup);
  191. if (info != NULL) allocator.Free(info);
  192. if (io != NULL) allocator.Free(io);
  193. return NULL;
  194. } /* __PHYSFS_createNativeIo */
  195. /* PHYSFS_Io implementation for i/o to a memory buffer... */
  196. typedef struct __PHYSFS_MemoryIoInfo
  197. {
  198. const PHYSFS_uint8 *buf;
  199. PHYSFS_uint64 len;
  200. PHYSFS_uint64 pos;
  201. PHYSFS_Io *parent;
  202. volatile PHYSFS_uint32 refcount;
  203. void (*destruct)(void *);
  204. } MemoryIoInfo;
  205. static PHYSFS_sint64 memoryIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  206. {
  207. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  208. const PHYSFS_uint64 avail = info->len - info->pos;
  209. assert(avail <= info->len);
  210. if (avail == 0)
  211. return 0; /* we're at EOF; nothing to do. */
  212. if (len > avail)
  213. len = avail;
  214. memcpy(buf, info->buf + info->pos, (size_t) len);
  215. info->pos += len;
  216. return len;
  217. } /* memoryIo_read */
  218. static PHYSFS_sint64 memoryIo_write(PHYSFS_Io *io, const void *buffer,
  219. PHYSFS_uint64 len)
  220. {
  221. BAIL(PHYSFS_ERR_OPEN_FOR_READING, -1);
  222. } /* memoryIo_write */
  223. static int memoryIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  224. {
  225. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  226. BAIL_IF(offset > info->len, PHYSFS_ERR_PAST_EOF, 0);
  227. info->pos = offset;
  228. return 1;
  229. } /* memoryIo_seek */
  230. static PHYSFS_sint64 memoryIo_tell(PHYSFS_Io *io)
  231. {
  232. const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  233. return (PHYSFS_sint64) info->pos;
  234. } /* memoryIo_tell */
  235. static PHYSFS_sint64 memoryIo_length(PHYSFS_Io *io)
  236. {
  237. const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  238. return (PHYSFS_sint64) info->len;
  239. } /* memoryIo_length */
  240. static PHYSFS_Io *memoryIo_duplicate(PHYSFS_Io *io)
  241. {
  242. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  243. MemoryIoInfo *newinfo = NULL;
  244. PHYSFS_Io *parent = info->parent;
  245. PHYSFS_Io *retval = NULL;
  246. /* avoid deep copies. */
  247. assert((!parent) || (!((MemoryIoInfo *) parent->opaque)->parent) );
  248. /* share the buffer between duplicates. */
  249. if (parent != NULL) /* dup the parent, increment its refcount. */
  250. return parent->duplicate(parent);
  251. /* we're the parent. */
  252. retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  253. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  254. newinfo = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
  255. if (!newinfo)
  256. {
  257. allocator.Free(retval);
  258. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  259. } /* if */
  260. __PHYSFS_ATOMIC_INCR(&info->refcount);
  261. memset(newinfo, '\0', sizeof (*info));
  262. newinfo->buf = info->buf;
  263. newinfo->len = info->len;
  264. newinfo->pos = 0;
  265. newinfo->parent = io;
  266. newinfo->refcount = 0;
  267. newinfo->destruct = NULL;
  268. memcpy(retval, io, sizeof (*retval));
  269. retval->opaque = newinfo;
  270. return retval;
  271. } /* memoryIo_duplicate */
  272. static int memoryIo_flush(PHYSFS_Io *io) { return 1; /* it's read-only. */ }
  273. static void memoryIo_destroy(PHYSFS_Io *io)
  274. {
  275. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  276. PHYSFS_Io *parent = info->parent;
  277. if (parent != NULL)
  278. {
  279. assert(info->buf == ((MemoryIoInfo *) info->parent->opaque)->buf);
  280. assert(info->len == ((MemoryIoInfo *) info->parent->opaque)->len);
  281. assert(info->refcount == 0);
  282. assert(info->destruct == NULL);
  283. allocator.Free(info);
  284. allocator.Free(io);
  285. parent->destroy(parent); /* decrements refcount. */
  286. return;
  287. } /* if */
  288. /* we _are_ the parent. */
  289. assert(info->refcount > 0); /* even in a race, we hold a reference. */
  290. if (__PHYSFS_ATOMIC_DECR(&info->refcount) == 0)
  291. {
  292. void (*destruct)(void *) = info->destruct;
  293. void *buf = (void *) info->buf;
  294. io->opaque = NULL; /* kill this here in case of race. */
  295. allocator.Free(info);
  296. allocator.Free(io);
  297. if (destruct != NULL)
  298. destruct(buf);
  299. } /* if */
  300. } /* memoryIo_destroy */
  301. static const PHYSFS_Io __PHYSFS_memoryIoInterface =
  302. {
  303. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  304. memoryIo_read,
  305. memoryIo_write,
  306. memoryIo_seek,
  307. memoryIo_tell,
  308. memoryIo_length,
  309. memoryIo_duplicate,
  310. memoryIo_flush,
  311. memoryIo_destroy
  312. };
  313. PHYSFS_Io *__PHYSFS_createMemoryIo(const void *buf, PHYSFS_uint64 len,
  314. void (*destruct)(void *))
  315. {
  316. PHYSFS_Io *io = NULL;
  317. MemoryIoInfo *info = NULL;
  318. io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  319. GOTO_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
  320. info = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
  321. GOTO_IF(!info, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
  322. memset(info, '\0', sizeof (*info));
  323. info->buf = (const PHYSFS_uint8 *) buf;
  324. info->len = len;
  325. info->pos = 0;
  326. info->parent = NULL;
  327. info->refcount = 1;
  328. info->destruct = destruct;
  329. memcpy(io, &__PHYSFS_memoryIoInterface, sizeof (*io));
  330. io->opaque = info;
  331. return io;
  332. createMemoryIo_failed:
  333. if (info != NULL) allocator.Free(info);
  334. if (io != NULL) allocator.Free(io);
  335. return NULL;
  336. } /* __PHYSFS_createMemoryIo */
  337. /* PHYSFS_Io implementation for i/o to a PHYSFS_File... */
  338. static PHYSFS_sint64 handleIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
  339. {
  340. return PHYSFS_readBytes((PHYSFS_File *) io->opaque, buf, len);
  341. } /* handleIo_read */
  342. static PHYSFS_sint64 handleIo_write(PHYSFS_Io *io, const void *buffer,
  343. PHYSFS_uint64 len)
  344. {
  345. return PHYSFS_writeBytes((PHYSFS_File *) io->opaque, buffer, len);
  346. } /* handleIo_write */
  347. static int handleIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
  348. {
  349. return PHYSFS_seek((PHYSFS_File *) io->opaque, offset);
  350. } /* handleIo_seek */
  351. static PHYSFS_sint64 handleIo_tell(PHYSFS_Io *io)
  352. {
  353. return PHYSFS_tell((PHYSFS_File *) io->opaque);
  354. } /* handleIo_tell */
  355. static PHYSFS_sint64 handleIo_length(PHYSFS_Io *io)
  356. {
  357. return PHYSFS_fileLength((PHYSFS_File *) io->opaque);
  358. } /* handleIo_length */
  359. static PHYSFS_Io *handleIo_duplicate(PHYSFS_Io *io)
  360. {
  361. /*
  362. * There's no duplicate at the PHYSFS_File level, so we break the
  363. * abstraction. We're allowed to: we're physfs.c!
  364. */
  365. FileHandle *origfh = (FileHandle *) io->opaque;
  366. FileHandle *newfh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  367. PHYSFS_Io *retval = NULL;
  368. GOTO_IF(!newfh, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  369. memset(newfh, '\0', sizeof (*newfh));
  370. retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  371. GOTO_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  372. #if 0 /* we don't buffer the duplicate, at least not at the moment. */
  373. if (origfh->buffer != NULL)
  374. {
  375. newfh->buffer = (PHYSFS_uint8 *) allocator.Malloc(origfh->bufsize);
  376. if (!newfh->buffer)
  377. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
  378. newfh->bufsize = origfh->bufsize;
  379. } /* if */
  380. #endif
  381. newfh->io = origfh->io->duplicate(origfh->io);
  382. GOTO_IF_ERRPASS(!newfh->io, handleIo_dupe_failed);
  383. newfh->forReading = origfh->forReading;
  384. newfh->dirHandle = origfh->dirHandle;
  385. __PHYSFS_platformGrabMutex(stateLock);
  386. if (newfh->forReading)
  387. {
  388. newfh->next = openReadList;
  389. openReadList = newfh;
  390. } /* if */
  391. else
  392. {
  393. newfh->next = openWriteList;
  394. openWriteList = newfh;
  395. } /* else */
  396. __PHYSFS_platformReleaseMutex(stateLock);
  397. memcpy(retval, io, sizeof (PHYSFS_Io));
  398. retval->opaque = newfh;
  399. return retval;
  400. handleIo_dupe_failed:
  401. if (newfh)
  402. {
  403. if (newfh->io != NULL) newfh->io->destroy(newfh->io);
  404. if (newfh->buffer != NULL) allocator.Free(newfh->buffer);
  405. allocator.Free(newfh);
  406. } /* if */
  407. return NULL;
  408. } /* handleIo_duplicate */
  409. static int handleIo_flush(PHYSFS_Io *io)
  410. {
  411. return PHYSFS_flush((PHYSFS_File *) io->opaque);
  412. } /* handleIo_flush */
  413. static void handleIo_destroy(PHYSFS_Io *io)
  414. {
  415. if (io->opaque != NULL)
  416. PHYSFS_close((PHYSFS_File *) io->opaque);
  417. allocator.Free(io);
  418. } /* handleIo_destroy */
  419. static const PHYSFS_Io __PHYSFS_handleIoInterface =
  420. {
  421. CURRENT_PHYSFS_IO_API_VERSION, NULL,
  422. handleIo_read,
  423. handleIo_write,
  424. handleIo_seek,
  425. handleIo_tell,
  426. handleIo_length,
  427. handleIo_duplicate,
  428. handleIo_flush,
  429. handleIo_destroy
  430. };
  431. static PHYSFS_Io *__PHYSFS_createHandleIo(PHYSFS_File *f)
  432. {
  433. PHYSFS_Io *io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
  434. BAIL_IF(!io, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  435. memcpy(io, &__PHYSFS_handleIoInterface, sizeof (*io));
  436. io->opaque = f;
  437. return io;
  438. } /* __PHYSFS_createHandleIo */
  439. /* functions ... */
  440. typedef struct
  441. {
  442. char **list;
  443. PHYSFS_uint32 size;
  444. PHYSFS_ErrorCode errcode;
  445. } EnumStringListCallbackData;
  446. static void enumStringListCallback(void *data, const char *str)
  447. {
  448. void *ptr;
  449. char *newstr;
  450. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  451. if (pecd->errcode)
  452. return;
  453. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  454. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  455. if (ptr != NULL)
  456. pecd->list = (char **) ptr;
  457. if ((ptr == NULL) || (newstr == NULL))
  458. {
  459. pecd->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
  460. pecd->list[pecd->size] = NULL;
  461. PHYSFS_freeList(pecd->list);
  462. return;
  463. } /* if */
  464. strcpy(newstr, str);
  465. pecd->list[pecd->size] = newstr;
  466. pecd->size++;
  467. } /* enumStringListCallback */
  468. static char **doEnumStringList(void (*func)(PHYSFS_StringCallback, void *))
  469. {
  470. EnumStringListCallbackData ecd;
  471. memset(&ecd, '\0', sizeof (ecd));
  472. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  473. BAIL_IF(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  474. func(enumStringListCallback, &ecd);
  475. if (ecd.errcode)
  476. {
  477. PHYSFS_setErrorCode(ecd.errcode);
  478. return NULL;
  479. } /* if */
  480. ecd.list[ecd.size] = NULL;
  481. return ecd.list;
  482. } /* doEnumStringList */
  483. static void __PHYSFS_bubble_sort(void *a, size_t lo, size_t hi,
  484. int (*cmpfn)(void *, size_t, size_t),
  485. void (*swapfn)(void *, size_t, size_t))
  486. {
  487. size_t i;
  488. int sorted;
  489. do
  490. {
  491. sorted = 1;
  492. for (i = lo; i < hi; i++)
  493. {
  494. if (cmpfn(a, i, i + 1) > 0)
  495. {
  496. swapfn(a, i, i + 1);
  497. sorted = 0;
  498. } /* if */
  499. } /* for */
  500. } while (!sorted);
  501. } /* __PHYSFS_bubble_sort */
  502. static void __PHYSFS_quick_sort(void *a, size_t lo, size_t hi,
  503. int (*cmpfn)(void *, size_t, size_t),
  504. void (*swapfn)(void *, size_t, size_t))
  505. {
  506. size_t i;
  507. size_t j;
  508. size_t v;
  509. if ((hi - lo) <= PHYSFS_QUICKSORT_THRESHOLD)
  510. __PHYSFS_bubble_sort(a, lo, hi, cmpfn, swapfn);
  511. else
  512. {
  513. i = (hi + lo) / 2;
  514. if (cmpfn(a, lo, i) > 0) swapfn(a, lo, i);
  515. if (cmpfn(a, lo, hi) > 0) swapfn(a, lo, hi);
  516. if (cmpfn(a, i, hi) > 0) swapfn(a, i, hi);
  517. j = hi - 1;
  518. swapfn(a, i, j);
  519. i = lo;
  520. v = j;
  521. while (1)
  522. {
  523. while(cmpfn(a, ++i, v) < 0) { /* do nothing */ }
  524. while(cmpfn(a, --j, v) > 0) { /* do nothing */ }
  525. if (j < i)
  526. break;
  527. swapfn(a, i, j);
  528. } /* while */
  529. if (i != (hi-1))
  530. swapfn(a, i, hi-1);
  531. __PHYSFS_quick_sort(a, lo, j, cmpfn, swapfn);
  532. __PHYSFS_quick_sort(a, i+1, hi, cmpfn, swapfn);
  533. } /* else */
  534. } /* __PHYSFS_quick_sort */
  535. void __PHYSFS_sort(void *entries, size_t max,
  536. int (*cmpfn)(void *, size_t, size_t),
  537. void (*swapfn)(void *, size_t, size_t))
  538. {
  539. /*
  540. * Quicksort w/ Bubblesort fallback algorithm inspired by code from here:
  541. * https://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
  542. */
  543. if (max > 0)
  544. __PHYSFS_quick_sort(entries, 0, max - 1, cmpfn, swapfn);
  545. } /* __PHYSFS_sort */
  546. static ErrState *findErrorForCurrentThread(void)
  547. {
  548. ErrState *i;
  549. void *tid;
  550. if (errorLock != NULL)
  551. __PHYSFS_platformGrabMutex(errorLock);
  552. if (errorStates != NULL)
  553. {
  554. tid = __PHYSFS_platformGetThreadID();
  555. for (i = errorStates; i != NULL; i = i->next)
  556. {
  557. if (i->tid == tid)
  558. {
  559. if (errorLock != NULL)
  560. __PHYSFS_platformReleaseMutex(errorLock);
  561. return i;
  562. } /* if */
  563. } /* for */
  564. } /* if */
  565. if (errorLock != NULL)
  566. __PHYSFS_platformReleaseMutex(errorLock);
  567. return NULL; /* no error available. */
  568. } /* findErrorForCurrentThread */
  569. /* this doesn't reset the error state. */
  570. static inline PHYSFS_ErrorCode currentErrorCode(void)
  571. {
  572. const ErrState *err = findErrorForCurrentThread();
  573. return err ? err->code : PHYSFS_ERR_OK;
  574. } /* currentErrorCode */
  575. PHYSFS_ErrorCode PHYSFS_getLastErrorCode(void)
  576. {
  577. ErrState *err = findErrorForCurrentThread();
  578. const PHYSFS_ErrorCode retval = (err) ? err->code : PHYSFS_ERR_OK;
  579. if (err)
  580. err->code = PHYSFS_ERR_OK;
  581. return retval;
  582. } /* PHYSFS_getLastErrorCode */
  583. PHYSFS_DECL const char *PHYSFS_getErrorByCode(PHYSFS_ErrorCode code)
  584. {
  585. switch (code)
  586. {
  587. case PHYSFS_ERR_OK: return "no error";
  588. case PHYSFS_ERR_OTHER_ERROR: return "unknown error";
  589. case PHYSFS_ERR_OUT_OF_MEMORY: return "out of memory";
  590. case PHYSFS_ERR_NOT_INITIALIZED: return "not initialized";
  591. case PHYSFS_ERR_IS_INITIALIZED: return "already initialized";
  592. case PHYSFS_ERR_ARGV0_IS_NULL: return "argv[0] is NULL";
  593. case PHYSFS_ERR_UNSUPPORTED: return "unsupported";
  594. case PHYSFS_ERR_PAST_EOF: return "past end of file";
  595. case PHYSFS_ERR_FILES_STILL_OPEN: return "files still open";
  596. case PHYSFS_ERR_INVALID_ARGUMENT: return "invalid argument";
  597. case PHYSFS_ERR_NOT_MOUNTED: return "not mounted";
  598. case PHYSFS_ERR_NOT_FOUND: return "not found";
  599. case PHYSFS_ERR_SYMLINK_FORBIDDEN: return "symlinks are forbidden";
  600. case PHYSFS_ERR_NO_WRITE_DIR: return "write directory is not set";
  601. case PHYSFS_ERR_OPEN_FOR_READING: return "file open for reading";
  602. case PHYSFS_ERR_OPEN_FOR_WRITING: return "file open for writing";
  603. case PHYSFS_ERR_NOT_A_FILE: return "not a file";
  604. case PHYSFS_ERR_READ_ONLY: return "read-only filesystem";
  605. case PHYSFS_ERR_CORRUPT: return "corrupted";
  606. case PHYSFS_ERR_SYMLINK_LOOP: return "infinite symbolic link loop";
  607. case PHYSFS_ERR_IO: return "i/o error";
  608. case PHYSFS_ERR_PERMISSION: return "permission denied";
  609. case PHYSFS_ERR_NO_SPACE: return "no space available for writing";
  610. case PHYSFS_ERR_BAD_FILENAME: return "filename is illegal or insecure";
  611. case PHYSFS_ERR_BUSY: return "tried to modify a file the OS needs";
  612. case PHYSFS_ERR_DIR_NOT_EMPTY: return "directory isn't empty";
  613. case PHYSFS_ERR_OS_ERROR: return "OS reported an error";
  614. case PHYSFS_ERR_DUPLICATE: return "duplicate resource";
  615. case PHYSFS_ERR_BAD_PASSWORD: return "bad password";
  616. } /* switch */
  617. return NULL; /* don't know this error code. */
  618. } /* PHYSFS_getErrorByCode */
  619. void PHYSFS_setErrorCode(PHYSFS_ErrorCode errcode)
  620. {
  621. ErrState *err;
  622. if (!errcode)
  623. return;
  624. err = findErrorForCurrentThread();
  625. if (err == NULL)
  626. {
  627. err = (ErrState *) allocator.Malloc(sizeof (ErrState));
  628. if (err == NULL)
  629. return; /* uhh...? */
  630. memset(err, '\0', sizeof (ErrState));
  631. err->tid = __PHYSFS_platformGetThreadID();
  632. if (errorLock != NULL)
  633. __PHYSFS_platformGrabMutex(errorLock);
  634. err->next = errorStates;
  635. errorStates = err;
  636. if (errorLock != NULL)
  637. __PHYSFS_platformReleaseMutex(errorLock);
  638. } /* if */
  639. err->code = errcode;
  640. } /* PHYSFS_setErrorCode */
  641. const char *PHYSFS_getLastError(void)
  642. {
  643. const PHYSFS_ErrorCode err = PHYSFS_getLastErrorCode();
  644. return (err) ? PHYSFS_getErrorByCode(err) : NULL;
  645. } /* PHYSFS_getLastError */
  646. /* MAKE SURE that errorLock is held before calling this! */
  647. static void freeErrorStates(void)
  648. {
  649. ErrState *i;
  650. ErrState *next;
  651. for (i = errorStates; i != NULL; i = next)
  652. {
  653. next = i->next;
  654. allocator.Free(i);
  655. } /* for */
  656. errorStates = NULL;
  657. } /* freeErrorStates */
  658. void PHYSFS_getLinkedVersion(PHYSFS_Version *ver)
  659. {
  660. if (ver != NULL)
  661. {
  662. ver->major = PHYSFS_VER_MAJOR;
  663. ver->minor = PHYSFS_VER_MINOR;
  664. ver->patch = PHYSFS_VER_PATCH;
  665. } /* if */
  666. } /* PHYSFS_getLinkedVersion */
  667. static const char *find_filename_extension(const char *fname)
  668. {
  669. const char *retval = NULL;
  670. if (fname != NULL)
  671. {
  672. const char *p = strchr(fname, '.');
  673. retval = p;
  674. while (p != NULL)
  675. {
  676. p = strchr(p + 1, '.');
  677. if (p != NULL)
  678. retval = p;
  679. } /* while */
  680. if (retval != NULL)
  681. retval++; /* skip '.' */
  682. } /* if */
  683. return retval;
  684. } /* find_filename_extension */
  685. static DirHandle *tryOpenDir(PHYSFS_Io *io, const PHYSFS_Archiver *funcs,
  686. const char *d, int forWriting)
  687. {
  688. DirHandle *retval = NULL;
  689. void *opaque = NULL;
  690. if (io != NULL)
  691. BAIL_IF_ERRPASS(!io->seek(io, 0), NULL);
  692. opaque = funcs->openArchive(io, d, forWriting);
  693. if (opaque != NULL)
  694. {
  695. retval = (DirHandle *) allocator.Malloc(sizeof (DirHandle));
  696. if (retval == NULL)
  697. funcs->closeArchive(opaque);
  698. else
  699. {
  700. memset(retval, '\0', sizeof (DirHandle));
  701. retval->mountPoint = NULL;
  702. retval->funcs = funcs;
  703. retval->opaque = opaque;
  704. } /* else */
  705. } /* if */
  706. return retval;
  707. } /* tryOpenDir */
  708. static DirHandle *openDirectory(PHYSFS_Io *io, const char *d, int forWriting)
  709. {
  710. DirHandle *retval = NULL;
  711. PHYSFS_Archiver **i;
  712. const char *ext;
  713. int created_io = 0;
  714. assert((io != NULL) || (d != NULL));
  715. if (io == NULL)
  716. {
  717. /* DIR gets first shot (unlike the rest, it doesn't deal with files). */
  718. retval = tryOpenDir(io, &__PHYSFS_Archiver_DIR, d, forWriting);
  719. if (retval != NULL)
  720. return retval;
  721. io = __PHYSFS_createNativeIo(d, forWriting ? 'w' : 'r');
  722. BAIL_IF_ERRPASS(!io, 0);
  723. created_io = 1;
  724. } /* if */
  725. ext = find_filename_extension(d);
  726. if (ext != NULL)
  727. {
  728. /* Look for archivers with matching file extensions first... */
  729. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  730. {
  731. if (__PHYSFS_utf8stricmp(ext, (*i)->info.extension) == 0)
  732. retval = tryOpenDir(io, *i, d, forWriting);
  733. } /* for */
  734. /* failing an exact file extension match, try all the others... */
  735. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  736. {
  737. if (__PHYSFS_utf8stricmp(ext, (*i)->info.extension) != 0)
  738. retval = tryOpenDir(io, *i, d, forWriting);
  739. } /* for */
  740. } /* if */
  741. else /* no extension? Try them all. */
  742. {
  743. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  744. retval = tryOpenDir(io, *i, d, forWriting);
  745. } /* else */
  746. if ((!retval) && (created_io))
  747. io->destroy(io);
  748. BAIL_IF(!retval, PHYSFS_ERR_UNSUPPORTED, NULL);
  749. return retval;
  750. } /* openDirectory */
  751. /*
  752. * Make a platform-independent path string sane. Doesn't actually check the
  753. * file hierarchy, it just cleans up the string.
  754. * (dst) must be a buffer at least as big as (src), as this is where the
  755. * cleaned up string is deposited.
  756. * If there are illegal bits in the path (".." entries, etc) then we
  757. * return zero and (dst) is undefined. Non-zero if the path was sanitized.
  758. */
  759. static int sanitizePlatformIndependentPath(const char *src, char *dst)
  760. {
  761. char *prev;
  762. char ch;
  763. while (*src == '/') /* skip initial '/' chars... */
  764. src++;
  765. prev = dst;
  766. do
  767. {
  768. ch = *(src++);
  769. if ((ch == ':') || (ch == '\\')) /* illegal chars in a physfs path. */
  770. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  771. if (ch == '/') /* path separator. */
  772. {
  773. *dst = '\0'; /* "." and ".." are illegal pathnames. */
  774. if ((strcmp(prev, ".") == 0) || (strcmp(prev, "..") == 0))
  775. BAIL(PHYSFS_ERR_BAD_FILENAME, 0);
  776. while (*src == '/') /* chop out doubles... */
  777. src++;
  778. if (*src == '\0') /* ends with a pathsep? */
  779. break; /* we're done, don't add final pathsep to dst. */
  780. prev = dst + 1;
  781. } /* if */
  782. *(dst++) = ch;
  783. } while (ch != '\0');
  784. return 1;
  785. } /* sanitizePlatformIndependentPath */
  786. /*
  787. * Figure out if (fname) is part of (h)'s mountpoint. (fname) must be an
  788. * output from sanitizePlatformIndependentPath(), so that it is in a known
  789. * state.
  790. *
  791. * This only finds legitimate segments of a mountpoint. If the mountpoint is
  792. * "/a/b/c" and (fname) is "/a/b/c", "/", or "/a/b/c/d", then the results are
  793. * all zero. "/a/b" will succeed, though.
  794. */
  795. static int partOfMountPoint(DirHandle *h, char *fname)
  796. {
  797. /* !!! FIXME: This code feels gross. */
  798. int rc;
  799. size_t len, mntpntlen;
  800. if (h->mountPoint == NULL)
  801. return 0;
  802. else if (*fname == '\0')
  803. return 1;
  804. len = strlen(fname);
  805. mntpntlen = strlen(h->mountPoint);
  806. if (len > mntpntlen) /* can't be a subset of mountpoint. */
  807. return 0;
  808. /* if true, must be not a match or a complete match, but not a subset. */
  809. if ((len + 1) == mntpntlen)
  810. return 0;
  811. rc = strncmp(fname, h->mountPoint, len); /* !!! FIXME: case insensitive? */
  812. if (rc != 0)
  813. return 0; /* not a match. */
  814. /* make sure /a/b matches /a/b/ and not /a/bc ... */
  815. return h->mountPoint[len] == '/';
  816. } /* partOfMountPoint */
  817. static DirHandle *createDirHandle(PHYSFS_Io *io, const char *newDir,
  818. const char *mountPoint, int forWriting)
  819. {
  820. DirHandle *dirHandle = NULL;
  821. char *tmpmntpnt = NULL;
  822. if (mountPoint != NULL)
  823. {
  824. const size_t len = strlen(mountPoint) + 1;
  825. tmpmntpnt = (char *) __PHYSFS_smallAlloc(len);
  826. GOTO_IF(!tmpmntpnt, PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  827. if (!sanitizePlatformIndependentPath(mountPoint, tmpmntpnt))
  828. goto badDirHandle;
  829. mountPoint = tmpmntpnt; /* sanitized version. */
  830. } /* if */
  831. dirHandle = openDirectory(io, newDir, forWriting);
  832. GOTO_IF_ERRPASS(!dirHandle, badDirHandle);
  833. if (newDir == NULL)
  834. dirHandle->dirName = NULL;
  835. else
  836. {
  837. dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
  838. if (!dirHandle->dirName)
  839. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  840. strcpy(dirHandle->dirName, newDir);
  841. } /* else */
  842. if ((mountPoint != NULL) && (*mountPoint != '\0'))
  843. {
  844. dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
  845. if (!dirHandle->mountPoint)
  846. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
  847. strcpy(dirHandle->mountPoint, mountPoint);
  848. strcat(dirHandle->mountPoint, "/");
  849. } /* if */
  850. __PHYSFS_smallFree(tmpmntpnt);
  851. return dirHandle;
  852. badDirHandle:
  853. if (dirHandle != NULL)
  854. {
  855. dirHandle->funcs->closeArchive(dirHandle->opaque);
  856. allocator.Free(dirHandle->dirName);
  857. allocator.Free(dirHandle->mountPoint);
  858. allocator.Free(dirHandle);
  859. } /* if */
  860. __PHYSFS_smallFree(tmpmntpnt);
  861. return NULL;
  862. } /* createDirHandle */
  863. /* MAKE SURE you've got the stateLock held before calling this! */
  864. static int freeDirHandle(DirHandle *dh, FileHandle *openList)
  865. {
  866. FileHandle *i;
  867. if (dh == NULL)
  868. return 1;
  869. for (i = openList; i != NULL; i = i->next)
  870. BAIL_IF(i->dirHandle == dh, PHYSFS_ERR_FILES_STILL_OPEN, 0);
  871. dh->funcs->closeArchive(dh->opaque);
  872. allocator.Free(dh->dirName);
  873. allocator.Free(dh->mountPoint);
  874. allocator.Free(dh);
  875. return 1;
  876. } /* freeDirHandle */
  877. static char *calculateBaseDir(const char *argv0)
  878. {
  879. const char dirsep = __PHYSFS_platformDirSeparator;
  880. char *retval = NULL;
  881. char *ptr = NULL;
  882. /* Give the platform layer first shot at this. */
  883. retval = __PHYSFS_platformCalcBaseDir(argv0);
  884. if (retval != NULL)
  885. return retval;
  886. /* We need argv0 to go on. */
  887. BAIL_IF(argv0 == NULL, PHYSFS_ERR_ARGV0_IS_NULL, NULL);
  888. ptr = strrchr(argv0, dirsep);
  889. if (ptr != NULL)
  890. {
  891. const size_t size = ((size_t) (ptr - argv0)) + 1;
  892. retval = (char *) allocator.Malloc(size + 1);
  893. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  894. memcpy(retval, argv0, size);
  895. retval[size] = '\0';
  896. return retval;
  897. } /* if */
  898. /* argv0 wasn't helpful. */
  899. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  900. } /* calculateBaseDir */
  901. static int initializeMutexes(void)
  902. {
  903. errorLock = __PHYSFS_platformCreateMutex();
  904. if (errorLock == NULL)
  905. goto initializeMutexes_failed;
  906. stateLock = __PHYSFS_platformCreateMutex();
  907. if (stateLock == NULL)
  908. goto initializeMutexes_failed;
  909. return 1; /* success. */
  910. initializeMutexes_failed:
  911. if (errorLock != NULL)
  912. __PHYSFS_platformDestroyMutex(errorLock);
  913. if (stateLock != NULL)
  914. __PHYSFS_platformDestroyMutex(stateLock);
  915. errorLock = stateLock = NULL;
  916. return 0; /* failed. */
  917. } /* initializeMutexes */
  918. static int doRegisterArchiver(const PHYSFS_Archiver *_archiver);
  919. static int initStaticArchivers(void)
  920. {
  921. #define REGISTER_STATIC_ARCHIVER(arc) { \
  922. if (!doRegisterArchiver(&__PHYSFS_Archiver_##arc)) { \
  923. return 0; \
  924. } \
  925. }
  926. #if PHYSFS_SUPPORTS_ZIP
  927. REGISTER_STATIC_ARCHIVER(ZIP);
  928. #endif
  929. #if PHYSFS_SUPPORTS_7Z
  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->enumerateFiles, 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. /* !!! FIXME: PHYSFS_Io shouldn't be NULL */
  1329. writeDir = createDirHandle(NULL, newDir, NULL, 1);
  1330. retval = (writeDir != NULL);
  1331. } /* if */
  1332. __PHYSFS_platformReleaseMutex(stateLock);
  1333. return retval;
  1334. } /* PHYSFS_setWriteDir */
  1335. static int doMount(PHYSFS_Io *io, const char *fname,
  1336. const char *mountPoint, int appendToPath)
  1337. {
  1338. DirHandle *dh;
  1339. DirHandle *prev = NULL;
  1340. DirHandle *i;
  1341. if (mountPoint == NULL)
  1342. mountPoint = "/";
  1343. __PHYSFS_platformGrabMutex(stateLock);
  1344. if (fname != NULL)
  1345. {
  1346. for (i = searchPath; i != NULL; i = i->next)
  1347. {
  1348. /* already in search path? */
  1349. if ((i->dirName != NULL) && (strcmp(fname, i->dirName) == 0))
  1350. BAIL_MUTEX_ERRPASS(stateLock, 1);
  1351. prev = i;
  1352. } /* for */
  1353. } /* if */
  1354. dh = createDirHandle(io, fname, mountPoint, 0);
  1355. BAIL_IF_MUTEX_ERRPASS(!dh, stateLock, 0);
  1356. if (appendToPath)
  1357. {
  1358. if (prev == NULL)
  1359. searchPath = dh;
  1360. else
  1361. prev->next = dh;
  1362. } /* if */
  1363. else
  1364. {
  1365. dh->next = searchPath;
  1366. searchPath = dh;
  1367. } /* else */
  1368. __PHYSFS_platformReleaseMutex(stateLock);
  1369. return 1;
  1370. } /* doMount */
  1371. int PHYSFS_mountIo(PHYSFS_Io *io, const char *fname,
  1372. const char *mountPoint, int appendToPath)
  1373. {
  1374. BAIL_IF(!io, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1375. BAIL_IF(io->version != 0, PHYSFS_ERR_UNSUPPORTED, 0);
  1376. return doMount(io, fname, mountPoint, appendToPath);
  1377. } /* PHYSFS_mountIo */
  1378. int PHYSFS_mountMemory(const void *buf, PHYSFS_uint64 len, void (*del)(void *),
  1379. const char *fname, const char *mountPoint,
  1380. int appendToPath)
  1381. {
  1382. int retval = 0;
  1383. PHYSFS_Io *io = NULL;
  1384. BAIL_IF(!buf, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1385. io = __PHYSFS_createMemoryIo(buf, len, del);
  1386. BAIL_IF_ERRPASS(!io, 0);
  1387. retval = doMount(io, fname, mountPoint, appendToPath);
  1388. if (!retval)
  1389. {
  1390. /* docs say not to call (del) in case of failure, so cheat. */
  1391. MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
  1392. info->destruct = NULL;
  1393. io->destroy(io);
  1394. } /* if */
  1395. return retval;
  1396. } /* PHYSFS_mountMemory */
  1397. int PHYSFS_mountHandle(PHYSFS_File *file, const char *fname,
  1398. const char *mountPoint, int appendToPath)
  1399. {
  1400. int retval = 0;
  1401. PHYSFS_Io *io = NULL;
  1402. BAIL_IF(file == NULL, 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 doMount(NULL, 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. /* Split out to avoid stack allocation in a loop. */
  1480. static void setSaneCfgAddPath(const char *i, const size_t l, const char *dirsep,
  1481. int archivesFirst)
  1482. {
  1483. const char *d = PHYSFS_getRealDir(i);
  1484. const size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
  1485. char *str = (char *) __PHYSFS_smallAlloc(allocsize);
  1486. if (str != NULL)
  1487. {
  1488. snprintf(str, allocsize, "%s%s%s", d, dirsep, i);
  1489. PHYSFS_mount(str, NULL, archivesFirst == 0);
  1490. __PHYSFS_smallFree(str);
  1491. } /* if */
  1492. } /* setSaneCfgAddPath */
  1493. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  1494. const char *archiveExt, int includeCdRoms,
  1495. int archivesFirst)
  1496. {
  1497. const char *dirsep = PHYSFS_getDirSeparator();
  1498. const char *basedir;
  1499. const char *prefdir;
  1500. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
  1501. prefdir = PHYSFS_getPrefDir(organization, appName);
  1502. BAIL_IF_ERRPASS(!prefdir, 0);
  1503. basedir = PHYSFS_getBaseDir();
  1504. BAIL_IF_ERRPASS(!basedir, 0);
  1505. BAIL_IF(!PHYSFS_setWriteDir(prefdir), PHYSFS_ERR_NO_WRITE_DIR, 0);
  1506. /* Put write dir first in search path... */
  1507. PHYSFS_mount(prefdir, NULL, 0);
  1508. /* Put base path on search path... */
  1509. PHYSFS_mount(basedir, NULL, 1);
  1510. /* handle CD-ROMs... */
  1511. if (includeCdRoms)
  1512. {
  1513. char **cds = PHYSFS_getCdRomDirs();
  1514. char **i;
  1515. for (i = cds; *i != NULL; i++)
  1516. PHYSFS_mount(*i, NULL, 1);
  1517. PHYSFS_freeList(cds);
  1518. } /* if */
  1519. /* Root out archives, and add them to search path... */
  1520. if (archiveExt != NULL)
  1521. {
  1522. char **rc = PHYSFS_enumerateFiles("/");
  1523. char **i;
  1524. size_t extlen = strlen(archiveExt);
  1525. char *ext;
  1526. for (i = rc; *i != NULL; i++)
  1527. {
  1528. size_t l = strlen(*i);
  1529. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  1530. {
  1531. ext = (*i) + (l - extlen);
  1532. if (__PHYSFS_utf8stricmp(ext, archiveExt) == 0)
  1533. setSaneCfgAddPath(*i, l, dirsep, archivesFirst);
  1534. } /* if */
  1535. } /* for */
  1536. PHYSFS_freeList(rc);
  1537. } /* if */
  1538. return 1;
  1539. } /* PHYSFS_setSaneConfig */
  1540. void PHYSFS_permitSymbolicLinks(int allow)
  1541. {
  1542. allowSymLinks = allow;
  1543. } /* PHYSFS_permitSymbolicLinks */
  1544. int PHYSFS_symbolicLinksPermitted(void)
  1545. {
  1546. return allowSymLinks;
  1547. } /* PHYSFS_symbolicLinksPermitted */
  1548. /*
  1549. * Verify that (fname) (in platform-independent notation), in relation
  1550. * to (h) is secure. That means that each element of fname is checked
  1551. * for symlinks (if they aren't permitted). This also allows for quick
  1552. * rejection of files that exist outside an archive's mountpoint.
  1553. *
  1554. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  1555. * at a time), you should always pass zero for "allowMissing" for efficiency.
  1556. *
  1557. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  1558. * since it will make sure that path names are in the right format for
  1559. * passing certain checks. It will also do checks for "insecure" pathnames
  1560. * like ".." which should be done once instead of once per archive. This also
  1561. * gives us license to treat (fname) as scratch space in this function.
  1562. *
  1563. * Returns non-zero if string is safe, zero if there's a security issue.
  1564. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  1565. * updated to point past any mount point elements so it is prepared to
  1566. * be used with the archiver directly.
  1567. */
  1568. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1569. {
  1570. char *fname = *_fname;
  1571. int retval = 1;
  1572. char *start;
  1573. char *end;
  1574. if (*fname == '\0') /* quick rejection. */
  1575. return 1;
  1576. /* !!! FIXME: This codeblock sucks. */
  1577. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1578. {
  1579. size_t mntpntlen = strlen(h->mountPoint);
  1580. size_t len = strlen(fname);
  1581. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1582. /* not under the mountpoint, so skip this archive. */
  1583. BAIL_IF(len < mntpntlen-1, PHYSFS_ERR_NOT_FOUND, 0);
  1584. /* !!! FIXME: Case insensitive? */
  1585. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1586. BAIL_IF(retval != 0, PHYSFS_ERR_NOT_FOUND, 0);
  1587. if (len > mntpntlen-1) /* corner case... */
  1588. BAIL_IF(fname[mntpntlen-1]!='/', PHYSFS_ERR_NOT_FOUND, 0);
  1589. fname += mntpntlen-1; /* move to start of actual archive path. */
  1590. if (*fname == '/')
  1591. fname++;
  1592. *_fname = fname; /* skip mountpoint for later use. */
  1593. retval = 1; /* may be reset, below. */
  1594. } /* if */
  1595. start = fname;
  1596. if (!allowSymLinks)
  1597. {
  1598. while (1)
  1599. {
  1600. PHYSFS_Stat statbuf;
  1601. int rc = 0;
  1602. end = strchr(start, '/');
  1603. if (end != NULL) *end = '\0';
  1604. rc = h->funcs->stat(h->opaque, fname, &statbuf);
  1605. if (rc)
  1606. rc = (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  1607. else if (currentErrorCode() == PHYSFS_ERR_NOT_FOUND)
  1608. retval = 0;
  1609. if (end != NULL) *end = '/';
  1610. /* insecure path (has a disallowed symlink in it)? */
  1611. BAIL_IF(rc, PHYSFS_ERR_SYMLINK_FORBIDDEN, 0);
  1612. /* break out early if path element is missing. */
  1613. if (!retval)
  1614. {
  1615. /*
  1616. * We need to clear it if it's the last element of the path,
  1617. * since this might be a non-existant file we're opening
  1618. * for writing...
  1619. */
  1620. if ((end == NULL) || (allowMissing))
  1621. retval = 1;
  1622. break;
  1623. } /* if */
  1624. if (end == NULL)
  1625. break;
  1626. start = end + 1;
  1627. } /* while */
  1628. } /* if */
  1629. return retval;
  1630. } /* verifyPath */
  1631. static int doMkdir(const char *_dname, char *dname)
  1632. {
  1633. DirHandle *h;
  1634. char *start;
  1635. char *end;
  1636. int retval = 0;
  1637. int exists = 1; /* force existance check on first path element. */
  1638. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPath(_dname, dname), 0);
  1639. __PHYSFS_platformGrabMutex(stateLock);
  1640. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1641. h = writeDir;
  1642. BAIL_IF_MUTEX_ERRPASS(!verifyPath(h, &dname, 1), stateLock, 0);
  1643. start = dname;
  1644. while (1)
  1645. {
  1646. end = strchr(start, '/');
  1647. if (end != NULL)
  1648. *end = '\0';
  1649. /* only check for existance if all parent dirs existed, too... */
  1650. if (exists)
  1651. {
  1652. PHYSFS_Stat statbuf;
  1653. const int rc = h->funcs->stat(h->opaque, dname, &statbuf);
  1654. if ((!rc) && (currentErrorCode() == PHYSFS_ERR_NOT_FOUND))
  1655. exists = 0;
  1656. retval = ((rc) && (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY));
  1657. } /* if */
  1658. if (!exists)
  1659. retval = h->funcs->mkdir(h->opaque, dname);
  1660. if (!retval)
  1661. break;
  1662. if (end == NULL)
  1663. break;
  1664. *end = '/';
  1665. start = end + 1;
  1666. } /* while */
  1667. __PHYSFS_platformReleaseMutex(stateLock);
  1668. return retval;
  1669. } /* doMkdir */
  1670. int PHYSFS_mkdir(const char *_dname)
  1671. {
  1672. int retval = 0;
  1673. char *dname;
  1674. size_t len;
  1675. BAIL_IF(!_dname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1676. len = strlen(_dname) + 1;
  1677. dname = (char *) __PHYSFS_smallAlloc(len);
  1678. BAIL_IF(!dname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1679. retval = doMkdir(_dname, dname);
  1680. __PHYSFS_smallFree(dname);
  1681. return retval;
  1682. } /* PHYSFS_mkdir */
  1683. static int doDelete(const char *_fname, char *fname)
  1684. {
  1685. int retval;
  1686. DirHandle *h;
  1687. BAIL_IF_ERRPASS(!sanitizePlatformIndependentPath(_fname, fname), 0);
  1688. __PHYSFS_platformGrabMutex(stateLock);
  1689. BAIL_IF_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
  1690. h = writeDir;
  1691. BAIL_IF_MUTEX_ERRPASS(!verifyPath(h, &fname, 0), stateLock, 0);
  1692. retval = h->funcs->remove(h->opaque, fname);
  1693. __PHYSFS_platformReleaseMutex(stateLock);
  1694. return retval;
  1695. } /* doDelete */
  1696. int PHYSFS_delete(const char *_fname)
  1697. {
  1698. int retval;
  1699. char *fname;
  1700. size_t len;
  1701. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1702. len = strlen(_fname) + 1;
  1703. fname = (char *) __PHYSFS_smallAlloc(len);
  1704. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1705. retval = doDelete(_fname, fname);
  1706. __PHYSFS_smallFree(fname);
  1707. return retval;
  1708. } /* PHYSFS_delete */
  1709. const char *PHYSFS_getRealDir(const char *_fname)
  1710. {
  1711. const char *retval = NULL;
  1712. char *fname = NULL;
  1713. size_t len;
  1714. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
  1715. len = strlen(_fname) + 1;
  1716. fname = __PHYSFS_smallAlloc(len);
  1717. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  1718. if (sanitizePlatformIndependentPath(_fname, fname))
  1719. {
  1720. DirHandle *i;
  1721. __PHYSFS_platformGrabMutex(stateLock);
  1722. for (i = searchPath; i != NULL; i = i->next)
  1723. {
  1724. char *arcfname = fname;
  1725. if (partOfMountPoint(i, arcfname))
  1726. {
  1727. retval = i->dirName;
  1728. break;
  1729. } /* if */
  1730. else if (verifyPath(i, &arcfname, 0))
  1731. {
  1732. PHYSFS_Stat statbuf;
  1733. if (i->funcs->stat(i->opaque, arcfname, &statbuf))
  1734. {
  1735. retval = i->dirName;
  1736. break;
  1737. } /* if */
  1738. } /* if */
  1739. } /* for */
  1740. __PHYSFS_platformReleaseMutex(stateLock);
  1741. } /* if */
  1742. __PHYSFS_smallFree(fname);
  1743. return retval;
  1744. } /* PHYSFS_getRealDir */
  1745. static int locateInStringList(const char *str,
  1746. char **list,
  1747. PHYSFS_uint32 *pos)
  1748. {
  1749. PHYSFS_uint32 len = *pos;
  1750. PHYSFS_uint32 half_len;
  1751. PHYSFS_uint32 lo = 0;
  1752. PHYSFS_uint32 middle;
  1753. int cmp;
  1754. while (len > 0)
  1755. {
  1756. half_len = len >> 1;
  1757. middle = lo + half_len;
  1758. cmp = strcmp(list[middle], str);
  1759. if (cmp == 0) /* it's in the list already. */
  1760. return 1;
  1761. else if (cmp > 0)
  1762. len = half_len;
  1763. else
  1764. {
  1765. lo = middle + 1;
  1766. len -= half_len + 1;
  1767. } /* else */
  1768. } /* while */
  1769. *pos = lo;
  1770. return 0;
  1771. } /* locateInStringList */
  1772. static void enumFilesCallback(void *data, const char *origdir, const char *str)
  1773. {
  1774. PHYSFS_uint32 pos;
  1775. void *ptr;
  1776. char *newstr;
  1777. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1778. /*
  1779. * See if file is in the list already, and if not, insert it in there
  1780. * alphabetically...
  1781. */
  1782. pos = pecd->size;
  1783. if (locateInStringList(str, pecd->list, &pos))
  1784. return; /* already in the list. */
  1785. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1786. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1787. if (ptr != NULL)
  1788. pecd->list = (char **) ptr;
  1789. if ((ptr == NULL) || (newstr == NULL))
  1790. return; /* better luck next time. */
  1791. strcpy(newstr, str);
  1792. if (pos != pecd->size)
  1793. {
  1794. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1795. sizeof (char *) * ((pecd->size) - pos));
  1796. } /* if */
  1797. pecd->list[pos] = newstr;
  1798. pecd->size++;
  1799. } /* enumFilesCallback */
  1800. char **PHYSFS_enumerateFiles(const char *path)
  1801. {
  1802. EnumStringListCallbackData ecd;
  1803. memset(&ecd, '\0', sizeof (ecd));
  1804. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1805. BAIL_IF(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  1806. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1807. ecd.list[ecd.size] = NULL;
  1808. return ecd.list;
  1809. } /* PHYSFS_enumerateFiles */
  1810. /*
  1811. * Broke out to seperate function so we can use stack allocation gratuitously.
  1812. */
  1813. static void enumerateFromMountPoint(DirHandle *i, const char *arcfname,
  1814. PHYSFS_EnumFilesCallback callback,
  1815. const char *_fname, void *data)
  1816. {
  1817. const size_t len = strlen(arcfname);
  1818. char *ptr = NULL;
  1819. char *end = NULL;
  1820. const size_t slen = strlen(i->mountPoint) + 1;
  1821. char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
  1822. if (mountPoint == NULL)
  1823. return; /* oh well. */
  1824. strcpy(mountPoint, i->mountPoint);
  1825. ptr = mountPoint + ((len) ? len + 1 : 0);
  1826. end = strchr(ptr, '/');
  1827. assert(end); /* should always find a terminating '/'. */
  1828. *end = '\0';
  1829. callback(data, _fname, ptr);
  1830. __PHYSFS_smallFree(mountPoint);
  1831. } /* enumerateFromMountPoint */
  1832. typedef struct SymlinkFilterData
  1833. {
  1834. PHYSFS_EnumFilesCallback callback;
  1835. void *callbackData;
  1836. DirHandle *dirhandle;
  1837. } SymlinkFilterData;
  1838. /* !!! FIXME: broken if in a virtual mountpoint (stat call fails). */
  1839. static void enumCallbackFilterSymLinks(void *_data, const char *origdir,
  1840. const char *fname)
  1841. {
  1842. const char *trimmedDir = (*origdir == '/') ? (origdir+1) : origdir;
  1843. const size_t slen = strlen(trimmedDir) + strlen(fname) + 2;
  1844. char *path = (char *) __PHYSFS_smallAlloc(slen);
  1845. if (path != NULL)
  1846. {
  1847. SymlinkFilterData *data = (SymlinkFilterData *) _data;
  1848. const DirHandle *dh = data->dirhandle;
  1849. PHYSFS_Stat statbuf;
  1850. snprintf(path, slen, "%s%s%s", trimmedDir, *trimmedDir ? "/" : "", fname);
  1851. if (dh->funcs->stat(dh->opaque, path, &statbuf))
  1852. {
  1853. /* Pass it on to the application if it's not a symlink. */
  1854. if (statbuf.filetype != PHYSFS_FILETYPE_SYMLINK)
  1855. data->callback(data->callbackData, origdir, fname);
  1856. } /* if */
  1857. __PHYSFS_smallFree(path);
  1858. } /* if */
  1859. } /* enumCallbackFilterSymLinks */
  1860. /* !!! FIXME: this should report error conditions. */
  1861. void PHYSFS_enumerateFilesCallback(const char *_fname,
  1862. PHYSFS_EnumFilesCallback callback,
  1863. void *data)
  1864. {
  1865. size_t len;
  1866. char *fname;
  1867. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, ) /*0*/;
  1868. BAIL_IF(!callback, PHYSFS_ERR_INVALID_ARGUMENT, ) /*0*/;
  1869. len = strlen(_fname) + 1;
  1870. fname = (char *) __PHYSFS_smallAlloc(len);
  1871. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, ) /*0*/;
  1872. if (sanitizePlatformIndependentPath(_fname, fname))
  1873. {
  1874. DirHandle *i;
  1875. SymlinkFilterData filterdata;
  1876. __PHYSFS_platformGrabMutex(stateLock);
  1877. if (!allowSymLinks)
  1878. {
  1879. memset(&filterdata, '\0', sizeof (filterdata));
  1880. filterdata.callback = callback;
  1881. filterdata.callbackData = data;
  1882. } /* if */
  1883. for (i = searchPath; i != NULL; i = i->next)
  1884. {
  1885. char *arcfname = fname;
  1886. if (partOfMountPoint(i, arcfname))
  1887. enumerateFromMountPoint(i, arcfname, callback, _fname, data);
  1888. else if (verifyPath(i, &arcfname, 0))
  1889. {
  1890. if ((!allowSymLinks) && (i->funcs->info.supportsSymlinks))
  1891. {
  1892. filterdata.dirhandle = i;
  1893. i->funcs->enumerateFiles(i->opaque, arcfname,
  1894. enumCallbackFilterSymLinks,
  1895. _fname, &filterdata);
  1896. } /* if */
  1897. else
  1898. {
  1899. i->funcs->enumerateFiles(i->opaque, arcfname,
  1900. callback, _fname, data);
  1901. } /* else */
  1902. } /* else if */
  1903. } /* for */
  1904. __PHYSFS_platformReleaseMutex(stateLock);
  1905. } /* if */
  1906. __PHYSFS_smallFree(fname);
  1907. } /* PHYSFS_enumerateFilesCallback */
  1908. int PHYSFS_exists(const char *fname)
  1909. {
  1910. return (PHYSFS_getRealDir(fname) != NULL);
  1911. } /* PHYSFS_exists */
  1912. PHYSFS_sint64 PHYSFS_getLastModTime(const char *fname)
  1913. {
  1914. PHYSFS_Stat statbuf;
  1915. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), -1);
  1916. return statbuf.modtime;
  1917. } /* PHYSFS_getLastModTime */
  1918. int PHYSFS_isDirectory(const char *fname)
  1919. {
  1920. PHYSFS_Stat statbuf;
  1921. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  1922. return (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY);
  1923. } /* PHYSFS_isDirectory */
  1924. int PHYSFS_isSymbolicLink(const char *fname)
  1925. {
  1926. PHYSFS_Stat statbuf;
  1927. BAIL_IF_ERRPASS(!PHYSFS_stat(fname, &statbuf), 0);
  1928. return (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
  1929. } /* PHYSFS_isSymbolicLink */
  1930. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1931. {
  1932. FileHandle *fh = NULL;
  1933. size_t len;
  1934. char *fname;
  1935. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1936. len = strlen(_fname) + 1;
  1937. fname = (char *) __PHYSFS_smallAlloc(len);
  1938. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1939. if (sanitizePlatformIndependentPath(_fname, fname))
  1940. {
  1941. PHYSFS_Io *io = NULL;
  1942. DirHandle *h = NULL;
  1943. const PHYSFS_Archiver *f;
  1944. __PHYSFS_platformGrabMutex(stateLock);
  1945. GOTO_IF(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, doOpenWriteEnd);
  1946. h = writeDir;
  1947. GOTO_IF_ERRPASS(!verifyPath(h, &fname, 0), doOpenWriteEnd);
  1948. f = h->funcs;
  1949. if (appending)
  1950. io = f->openAppend(h->opaque, fname);
  1951. else
  1952. io = f->openWrite(h->opaque, fname);
  1953. GOTO_IF_ERRPASS(!io, doOpenWriteEnd);
  1954. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1955. if (fh == NULL)
  1956. {
  1957. io->destroy(io);
  1958. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, doOpenWriteEnd);
  1959. } /* if */
  1960. else
  1961. {
  1962. memset(fh, '\0', sizeof (FileHandle));
  1963. fh->io = io;
  1964. fh->dirHandle = h;
  1965. fh->next = openWriteList;
  1966. openWriteList = fh;
  1967. } /* else */
  1968. doOpenWriteEnd:
  1969. __PHYSFS_platformReleaseMutex(stateLock);
  1970. } /* if */
  1971. __PHYSFS_smallFree(fname);
  1972. return ((PHYSFS_File *) fh);
  1973. } /* doOpenWrite */
  1974. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1975. {
  1976. return doOpenWrite(filename, 0);
  1977. } /* PHYSFS_openWrite */
  1978. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1979. {
  1980. return doOpenWrite(filename, 1);
  1981. } /* PHYSFS_openAppend */
  1982. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  1983. {
  1984. FileHandle *fh = NULL;
  1985. char *fname;
  1986. size_t len;
  1987. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  1988. len = strlen(_fname) + 1;
  1989. fname = (char *) __PHYSFS_smallAlloc(len);
  1990. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  1991. if (sanitizePlatformIndependentPath(_fname, fname))
  1992. {
  1993. DirHandle *i = NULL;
  1994. PHYSFS_Io *io = NULL;
  1995. __PHYSFS_platformGrabMutex(stateLock);
  1996. GOTO_IF(!searchPath, PHYSFS_ERR_NOT_FOUND, openReadEnd);
  1997. for (i = searchPath; i != NULL; i = i->next)
  1998. {
  1999. char *arcfname = fname;
  2000. if (verifyPath(i, &arcfname, 0))
  2001. {
  2002. io = i->funcs->openRead(i->opaque, arcfname);
  2003. if (io)
  2004. break;
  2005. } /* if */
  2006. } /* for */
  2007. GOTO_IF_ERRPASS(!io, openReadEnd);
  2008. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  2009. if (fh == NULL)
  2010. {
  2011. io->destroy(io);
  2012. GOTO(PHYSFS_ERR_OUT_OF_MEMORY, openReadEnd);
  2013. } /* if */
  2014. memset(fh, '\0', sizeof (FileHandle));
  2015. fh->io = io;
  2016. fh->forReading = 1;
  2017. fh->dirHandle = i;
  2018. fh->next = openReadList;
  2019. openReadList = fh;
  2020. openReadEnd:
  2021. __PHYSFS_platformReleaseMutex(stateLock);
  2022. } /* if */
  2023. __PHYSFS_smallFree(fname);
  2024. return ((PHYSFS_File *) fh);
  2025. } /* PHYSFS_openRead */
  2026. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  2027. {
  2028. FileHandle *prev = NULL;
  2029. FileHandle *i;
  2030. int rc = 1;
  2031. for (i = *list; i != NULL; i = i->next)
  2032. {
  2033. if (i == handle) /* handle is in this list? */
  2034. {
  2035. PHYSFS_Io *io = handle->io;
  2036. PHYSFS_uint8 *tmp = handle->buffer;
  2037. rc = PHYSFS_flush((PHYSFS_File *) handle);
  2038. if (!rc)
  2039. return -1;
  2040. io->destroy(io);
  2041. if (tmp != NULL) /* free any associated buffer. */
  2042. allocator.Free(tmp);
  2043. if (prev == NULL)
  2044. *list = handle->next;
  2045. else
  2046. prev->next = handle->next;
  2047. allocator.Free(handle);
  2048. return 1;
  2049. } /* if */
  2050. prev = i;
  2051. } /* for */
  2052. return 0;
  2053. } /* closeHandleInOpenList */
  2054. int PHYSFS_close(PHYSFS_File *_handle)
  2055. {
  2056. FileHandle *handle = (FileHandle *) _handle;
  2057. int rc;
  2058. __PHYSFS_platformGrabMutex(stateLock);
  2059. /* -1 == close failure. 0 == not found. 1 == success. */
  2060. rc = closeHandleInOpenList(&openReadList, handle);
  2061. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2062. if (!rc)
  2063. {
  2064. rc = closeHandleInOpenList(&openWriteList, handle);
  2065. BAIL_IF_MUTEX_ERRPASS(rc == -1, stateLock, 0);
  2066. } /* if */
  2067. __PHYSFS_platformReleaseMutex(stateLock);
  2068. BAIL_IF(!rc, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2069. return 1;
  2070. } /* PHYSFS_close */
  2071. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer, size_t len)
  2072. {
  2073. PHYSFS_Io *io = NULL;
  2074. PHYSFS_sint64 retval = 0;
  2075. size_t buffered = 0;
  2076. PHYSFS_sint64 rc = 0;
  2077. if (len == 0)
  2078. return 0;
  2079. buffered = fh->buffill - fh->bufpos;
  2080. if (buffered >= len) /* totally in the buffer, just copy and return! */
  2081. {
  2082. memcpy(buffer, fh->buffer + fh->bufpos, len);
  2083. fh->bufpos += len;
  2084. return (PHYSFS_sint64) len;
  2085. } /* if */
  2086. else if (buffered > 0) /* partially in the buffer... */
  2087. {
  2088. memcpy(buffer, fh->buffer + fh->bufpos, buffered);
  2089. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  2090. len -= buffered;
  2091. retval = (PHYSFS_sint64) buffered;
  2092. } /* if */
  2093. /* if you got here, the buffer is drained and we still need bytes. */
  2094. assert(len > 0);
  2095. fh->buffill = fh->bufpos = 0;
  2096. io = fh->io;
  2097. if (len >= fh->bufsize) /* need more than the buffer takes. */
  2098. {
  2099. /* leave buffer empty, go right to output instead. */
  2100. rc = io->read(io, buffer, len);
  2101. if (rc < 0)
  2102. return ((retval == 0) ? rc : retval);
  2103. return retval + rc;
  2104. } /* if */
  2105. /* need less than buffer can take. Fill buffer. */
  2106. rc = io->read(io, fh->buffer, fh->bufsize);
  2107. if (rc < 0)
  2108. return ((retval == 0) ? rc : retval);
  2109. assert(fh->bufpos == 0);
  2110. fh->buffill = (size_t) rc;
  2111. rc = doBufferedRead(fh, buffer, len); /* go from the start, again. */
  2112. if (rc < 0)
  2113. return ((retval == 0) ? rc : retval);
  2114. return retval + rc;
  2115. } /* doBufferedRead */
  2116. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  2117. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2118. {
  2119. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2120. const PHYSFS_sint64 retval = PHYSFS_readBytes(handle, buffer, len);
  2121. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2122. } /* PHYSFS_read */
  2123. PHYSFS_sint64 PHYSFS_readBytes(PHYSFS_File *handle, void *buffer,
  2124. PHYSFS_uint64 _len)
  2125. {
  2126. const size_t len = (size_t) _len;
  2127. FileHandle *fh = (FileHandle *) handle;
  2128. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2129. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2130. #else
  2131. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2132. #endif
  2133. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2134. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2135. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2136. BAIL_IF(!fh->forReading, PHYSFS_ERR_OPEN_FOR_WRITING, -1);
  2137. BAIL_IF_ERRPASS(len == 0, 0);
  2138. if (fh->buffer)
  2139. return doBufferedRead(fh, buffer, len);
  2140. return fh->io->read(fh->io, buffer, len);
  2141. } /* PHYSFS_readBytes */
  2142. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  2143. const size_t len)
  2144. {
  2145. FileHandle *fh = (FileHandle *) handle;
  2146. /* whole thing fits in the buffer? */
  2147. if ((fh->buffill + len) < fh->bufsize)
  2148. {
  2149. memcpy(fh->buffer + fh->buffill, buffer, len);
  2150. fh->buffill += len;
  2151. return (PHYSFS_sint64) len;
  2152. } /* if */
  2153. /* would overflow buffer. Flush and then write the new objects, too. */
  2154. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), -1);
  2155. return fh->io->write(fh->io, buffer, len);
  2156. } /* doBufferedWrite */
  2157. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  2158. PHYSFS_uint32 size, PHYSFS_uint32 count)
  2159. {
  2160. const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
  2161. const PHYSFS_sint64 retval = PHYSFS_writeBytes(handle, buffer, len);
  2162. return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
  2163. } /* PHYSFS_write */
  2164. PHYSFS_sint64 PHYSFS_writeBytes(PHYSFS_File *handle, const void *buffer,
  2165. PHYSFS_uint64 _len)
  2166. {
  2167. const size_t len = (size_t) _len;
  2168. FileHandle *fh = (FileHandle *) handle;
  2169. #ifdef PHYSFS_NO_64BIT_SUPPORT
  2170. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
  2171. #else
  2172. const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
  2173. #endif
  2174. if (!__PHYSFS_ui64FitsAddressSpace(_len))
  2175. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2176. BAIL_IF(_len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
  2177. BAIL_IF(fh->forReading, PHYSFS_ERR_OPEN_FOR_READING, -1);
  2178. BAIL_IF_ERRPASS(len == 0, 0);
  2179. if (fh->buffer)
  2180. return doBufferedWrite(handle, buffer, len);
  2181. return fh->io->write(fh->io, buffer, len);
  2182. } /* PHYSFS_write */
  2183. int PHYSFS_eof(PHYSFS_File *handle)
  2184. {
  2185. FileHandle *fh = (FileHandle *) handle;
  2186. if (!fh->forReading) /* never EOF on files opened for write/append. */
  2187. return 0;
  2188. /* can't be eof if buffer isn't empty */
  2189. if (fh->bufpos == fh->buffill)
  2190. {
  2191. /* check the Io. */
  2192. PHYSFS_Io *io = fh->io;
  2193. const PHYSFS_sint64 pos = io->tell(io);
  2194. const PHYSFS_sint64 len = io->length(io);
  2195. if ((pos < 0) || (len < 0))
  2196. return 0; /* beats me. */
  2197. return (pos >= len);
  2198. } /* if */
  2199. return 0;
  2200. } /* PHYSFS_eof */
  2201. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  2202. {
  2203. FileHandle *fh = (FileHandle *) handle;
  2204. const PHYSFS_sint64 pos = fh->io->tell(fh->io);
  2205. const PHYSFS_sint64 retval = fh->forReading ?
  2206. (pos - fh->buffill) + fh->bufpos :
  2207. (pos + fh->buffill);
  2208. return retval;
  2209. } /* PHYSFS_tell */
  2210. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  2211. {
  2212. FileHandle *fh = (FileHandle *) handle;
  2213. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2214. if (fh->buffer && fh->forReading)
  2215. {
  2216. /* avoid throwing away our precious buffer if seeking within it. */
  2217. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  2218. if ( /* seeking within the already-buffered range? */
  2219. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  2220. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  2221. {
  2222. fh->bufpos += (PHYSFS_uint32) offset;
  2223. return 1; /* successful seek */
  2224. } /* if */
  2225. } /* if */
  2226. /* we have to fall back to a 'raw' seek. */
  2227. fh->buffill = fh->bufpos = 0;
  2228. return fh->io->seek(fh->io, pos);
  2229. } /* PHYSFS_seek */
  2230. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  2231. {
  2232. PHYSFS_Io *io = ((FileHandle *) handle)->io;
  2233. return io->length(io);
  2234. } /* PHYSFS_filelength */
  2235. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  2236. {
  2237. FileHandle *fh = (FileHandle *) handle;
  2238. const size_t bufsize = (size_t) _bufsize;
  2239. if (!__PHYSFS_ui64FitsAddressSpace(_bufsize))
  2240. BAIL(PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2241. BAIL_IF_ERRPASS(!PHYSFS_flush(handle), 0);
  2242. /*
  2243. * For reads, we need to move the file pointer to where it would be
  2244. * if we weren't buffering, so that the next read will get the
  2245. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  2246. */
  2247. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  2248. {
  2249. PHYSFS_uint64 pos;
  2250. const PHYSFS_sint64 curpos = fh->io->tell(fh->io);
  2251. BAIL_IF_ERRPASS(curpos == -1, 0);
  2252. pos = ((curpos - fh->buffill) + fh->bufpos);
  2253. BAIL_IF_ERRPASS(!fh->io->seek(fh->io, pos), 0);
  2254. } /* if */
  2255. if (bufsize == 0) /* delete existing buffer. */
  2256. {
  2257. if (fh->buffer)
  2258. {
  2259. allocator.Free(fh->buffer);
  2260. fh->buffer = NULL;
  2261. } /* if */
  2262. } /* if */
  2263. else
  2264. {
  2265. PHYSFS_uint8 *newbuf;
  2266. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  2267. BAIL_IF(!newbuf, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2268. fh->buffer = newbuf;
  2269. } /* else */
  2270. fh->bufsize = bufsize;
  2271. fh->buffill = fh->bufpos = 0;
  2272. return 1;
  2273. } /* PHYSFS_setBuffer */
  2274. int PHYSFS_flush(PHYSFS_File *handle)
  2275. {
  2276. FileHandle *fh = (FileHandle *) handle;
  2277. PHYSFS_Io *io;
  2278. PHYSFS_sint64 rc;
  2279. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  2280. return 1; /* open for read or buffer empty are successful no-ops. */
  2281. /* dump buffer to disk. */
  2282. io = fh->io;
  2283. rc = io->write(io, fh->buffer + fh->bufpos, fh->buffill - fh->bufpos);
  2284. BAIL_IF_ERRPASS(rc <= 0, 0);
  2285. fh->bufpos = fh->buffill = 0;
  2286. return io->flush ? io->flush(io) : 1;
  2287. } /* PHYSFS_flush */
  2288. int PHYSFS_stat(const char *_fname, PHYSFS_Stat *stat)
  2289. {
  2290. int retval = 0;
  2291. char *fname;
  2292. size_t len;
  2293. BAIL_IF(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2294. BAIL_IF(!stat, PHYSFS_ERR_INVALID_ARGUMENT, 0);
  2295. len = strlen(_fname) + 1;
  2296. fname = (char *) __PHYSFS_smallAlloc(len);
  2297. BAIL_IF(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2298. /* set some sane defaults... */
  2299. stat->filesize = -1;
  2300. stat->modtime = -1;
  2301. stat->createtime = -1;
  2302. stat->accesstime = -1;
  2303. stat->filetype = PHYSFS_FILETYPE_OTHER;
  2304. stat->readonly = 1;
  2305. if (sanitizePlatformIndependentPath(_fname, fname))
  2306. {
  2307. if (*fname == '\0')
  2308. {
  2309. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2310. stat->readonly = !writeDir; /* Writeable if we have a writeDir */
  2311. retval = 1;
  2312. } /* if */
  2313. else
  2314. {
  2315. DirHandle *i;
  2316. int exists = 0;
  2317. __PHYSFS_platformGrabMutex(stateLock);
  2318. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  2319. {
  2320. char *arcfname = fname;
  2321. exists = partOfMountPoint(i, arcfname);
  2322. if (exists)
  2323. {
  2324. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  2325. stat->readonly = 1;
  2326. retval = 1;
  2327. } /* if */
  2328. else if (verifyPath(i, &arcfname, 0))
  2329. {
  2330. /* !!! FIXME: this test is wrong and should be elsewhere. */
  2331. stat->readonly = !(writeDir &&
  2332. (strcmp(writeDir->dirName, i->dirName) == 0));
  2333. retval = i->funcs->stat(i->opaque, arcfname, stat);
  2334. if ((retval) || (currentErrorCode() != PHYSFS_ERR_NOT_FOUND))
  2335. exists = 1;
  2336. } /* else if */
  2337. } /* for */
  2338. __PHYSFS_platformReleaseMutex(stateLock);
  2339. } /* else */
  2340. } /* if */
  2341. __PHYSFS_smallFree(fname);
  2342. return retval;
  2343. } /* PHYSFS_stat */
  2344. int __PHYSFS_readAll(PHYSFS_Io *io, void *buf, const PHYSFS_uint64 len)
  2345. {
  2346. return (io->read(io, buf, len) == len);
  2347. } /* __PHYSFS_readAll */
  2348. void *__PHYSFS_initSmallAlloc(void *ptr, PHYSFS_uint64 len)
  2349. {
  2350. void *useHeap = ((ptr == NULL) ? ((void *) 1) : ((void *) 0));
  2351. if (useHeap) /* too large for stack allocation or alloca() failed. */
  2352. ptr = allocator.Malloc(len+sizeof (void *));
  2353. if (ptr != NULL)
  2354. {
  2355. void **retval = (void **) ptr;
  2356. /*printf("%s alloc'd (%d) bytes at (%p).\n",
  2357. useHeap ? "heap" : "stack", (int) len, ptr);*/
  2358. *retval = useHeap;
  2359. return retval + 1;
  2360. } /* if */
  2361. return NULL; /* allocation failed. */
  2362. } /* __PHYSFS_initSmallAlloc */
  2363. void __PHYSFS_smallFree(void *ptr)
  2364. {
  2365. if (ptr != NULL)
  2366. {
  2367. void **block = ((void **) ptr) - 1;
  2368. const int useHeap = (*block != 0);
  2369. if (useHeap)
  2370. allocator.Free(block);
  2371. /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
  2372. } /* if */
  2373. } /* __PHYSFS_smallFree */
  2374. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  2375. {
  2376. BAIL_IF(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
  2377. externalAllocator = (a != NULL);
  2378. if (externalAllocator)
  2379. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  2380. return 1;
  2381. } /* PHYSFS_setAllocator */
  2382. const PHYSFS_Allocator *PHYSFS_getAllocator(void)
  2383. {
  2384. BAIL_IF(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
  2385. return &allocator;
  2386. } /* PHYSFS_getAllocator */
  2387. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  2388. {
  2389. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2390. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2391. #undef malloc
  2392. return malloc((size_t) s);
  2393. } /* mallocAllocatorMalloc */
  2394. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  2395. {
  2396. if (!__PHYSFS_ui64FitsAddressSpace(s))
  2397. BAIL(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2398. #undef realloc
  2399. return realloc(ptr, (size_t) s);
  2400. } /* mallocAllocatorRealloc */
  2401. static void mallocAllocatorFree(void *ptr)
  2402. {
  2403. #undef free
  2404. free(ptr);
  2405. } /* mallocAllocatorFree */
  2406. static void setDefaultAllocator(void)
  2407. {
  2408. assert(!externalAllocator);
  2409. allocator.Init = NULL;
  2410. allocator.Deinit = NULL;
  2411. allocator.Malloc = mallocAllocatorMalloc;
  2412. allocator.Realloc = mallocAllocatorRealloc;
  2413. allocator.Free = mallocAllocatorFree;
  2414. } /* setDefaultAllocator */
  2415. int __PHYSFS_DirTreeInit(__PHYSFS_DirTree *dt, const size_t entrylen)
  2416. {
  2417. static char rootpath[2] = { '/', '\0' };
  2418. size_t alloclen;
  2419. assert(entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2420. memset(dt, '\0', sizeof (*dt));
  2421. dt->root = (__PHYSFS_DirTreeEntry *) allocator.Malloc(entrylen);
  2422. BAIL_IF(!dt->root, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2423. memset(dt->root, '\0', entrylen);
  2424. dt->root->name = rootpath;
  2425. dt->root->isdir = 1;
  2426. dt->hashBuckets = 64;
  2427. if (!dt->hashBuckets)
  2428. dt->hashBuckets = 1;
  2429. dt->entrylen = entrylen;
  2430. alloclen = dt->hashBuckets * sizeof (__PHYSFS_DirTreeEntry *);
  2431. dt->hash = (__PHYSFS_DirTreeEntry **) allocator.Malloc(alloclen);
  2432. BAIL_IF(!dt->hash, PHYSFS_ERR_OUT_OF_MEMORY, 0);
  2433. memset(dt->hash, '\0', alloclen);
  2434. return 1;
  2435. } /* __PHYSFS_DirTreeInit */
  2436. static inline PHYSFS_uint32 hashPathName(__PHYSFS_DirTree *dt, const char *name)
  2437. {
  2438. return __PHYSFS_hashString(name, strlen(name)) % dt->hashBuckets;
  2439. } /* hashPathName */
  2440. /* Fill in missing parent directories. */
  2441. static __PHYSFS_DirTreeEntry *addAncestors(__PHYSFS_DirTree *dt, char *name)
  2442. {
  2443. __PHYSFS_DirTreeEntry *retval = dt->root;
  2444. char *sep = strrchr(name, '/');
  2445. if (sep)
  2446. {
  2447. *sep = '\0'; /* chop off last piece. */
  2448. retval = (__PHYSFS_DirTreeEntry *) __PHYSFS_DirTreeFind(dt, name);
  2449. if (retval != NULL)
  2450. {
  2451. *sep = '/';
  2452. BAIL_IF(!retval->isdir, PHYSFS_ERR_CORRUPT, NULL);
  2453. return retval; /* already hashed. */
  2454. } /* if */
  2455. /* okay, this is a new dir. Build and hash us. */
  2456. retval = (__PHYSFS_DirTreeEntry*)__PHYSFS_DirTreeAdd(dt, name, 1);
  2457. *sep = '/';
  2458. } /* if */
  2459. return retval;
  2460. } /* addAncestors */
  2461. void *__PHYSFS_DirTreeAdd(__PHYSFS_DirTree *dt, char *name, const int isdir)
  2462. {
  2463. __PHYSFS_DirTreeEntry *retval = __PHYSFS_DirTreeFind(dt, name);
  2464. if (!retval)
  2465. {
  2466. const size_t alloclen = strlen(name) + 1 + dt->entrylen;
  2467. PHYSFS_uint32 hashval;
  2468. __PHYSFS_DirTreeEntry *parent = addAncestors(dt, name);
  2469. BAIL_IF_ERRPASS(!parent, NULL);
  2470. assert(dt->entrylen >= sizeof (__PHYSFS_DirTreeEntry));
  2471. retval = (__PHYSFS_DirTreeEntry *) allocator.Malloc(alloclen);
  2472. BAIL_IF(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
  2473. memset(retval, '\0', dt->entrylen);
  2474. retval->name = ((char *) retval) + dt->entrylen;
  2475. strcpy(retval->name, name);
  2476. hashval = hashPathName(dt, name);
  2477. retval->hashnext = dt->hash[hashval];
  2478. dt->hash[hashval] = retval;
  2479. retval->sibling = parent->children;
  2480. retval->isdir = isdir;
  2481. parent->children = retval;
  2482. } /* if */
  2483. return retval;
  2484. } /* __PHYSFS_DirTreeAdd */
  2485. /* Find the __PHYSFS_DirTreeEntry for a path in platform-independent notation. */
  2486. void *__PHYSFS_DirTreeFind(__PHYSFS_DirTree *dt, const char *path)
  2487. {
  2488. PHYSFS_uint32 hashval;
  2489. __PHYSFS_DirTreeEntry *prev = NULL;
  2490. __PHYSFS_DirTreeEntry *retval;
  2491. if (*path == '\0')
  2492. return dt->root;
  2493. hashval = hashPathName(dt, path);
  2494. for (retval = dt->hash[hashval]; retval; retval = retval->hashnext)
  2495. {
  2496. if (strcmp(retval->name, path) == 0)
  2497. {
  2498. if (prev != NULL) /* move this to the front of the list */
  2499. {
  2500. prev->hashnext = retval->hashnext;
  2501. retval->hashnext = dt->hash[hashval];
  2502. dt->hash[hashval] = retval;
  2503. } /* if */
  2504. return retval;
  2505. } /* if */
  2506. prev = retval;
  2507. } /* for */
  2508. BAIL(PHYSFS_ERR_NOT_FOUND, NULL);
  2509. } /* __PHYSFS_DirTreeFind */
  2510. void __PHYSFS_DirTreeEnumerateFiles(void *opaque, const char *dname,
  2511. PHYSFS_EnumFilesCallback cb,
  2512. const char *origdir, void *callbackdata)
  2513. {
  2514. __PHYSFS_DirTree *tree = ((__PHYSFS_DirTree *) opaque);
  2515. const __PHYSFS_DirTreeEntry *entry = __PHYSFS_DirTreeFind(tree, dname);
  2516. if (entry && entry->isdir)
  2517. {
  2518. for (entry = entry->children; entry; entry = entry->sibling)
  2519. {
  2520. const char *ptr = strrchr(entry->name, '/');
  2521. cb(callbackdata, origdir, ptr ? ptr + 1 : entry->name);
  2522. } /* for */
  2523. } /* if */
  2524. } /* __PHYSFS_DirTreeEnumerateFiles */
  2525. void __PHYSFS_DirTreeDeinit(__PHYSFS_DirTree *dt)
  2526. {
  2527. if (!dt)
  2528. return;
  2529. if (dt->root)
  2530. {
  2531. assert(dt->root->sibling == NULL);
  2532. assert(dt->hash || (dt->root->children == NULL));
  2533. allocator.Free(dt->root);
  2534. } /* if */
  2535. if (dt->hash)
  2536. {
  2537. size_t i;
  2538. for (i = 0; i < dt->hashBuckets; i++)
  2539. {
  2540. __PHYSFS_DirTreeEntry *entry;
  2541. __PHYSFS_DirTreeEntry *next;
  2542. for (entry = dt->hash[i]; entry; entry = next)
  2543. {
  2544. next = entry->hashnext;
  2545. allocator.Free(entry);
  2546. } /* for */
  2547. } /* for */
  2548. allocator.Free(dt->hash);
  2549. } /* if */
  2550. } /* __PHYSFS_DirTreeDeinit */
  2551. /* end of physfs.c ... */