physfs.c 73 KB

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