1
0

physfs.c 60 KB

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