physfs.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284
  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. 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. 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. void *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 = NULL;
  495. const char *str = NULL;
  496. str = __PHYSFS_platformGetUserDir();
  497. if (str != NULL)
  498. retval = (char *) str;
  499. else
  500. {
  501. const char *dirsep = PHYSFS_getDirSeparator();
  502. const char *uname = __PHYSFS_platformGetUserName();
  503. str = (uname != NULL) ? uname : "default";
  504. retval = (char *) allocator.Malloc(strlen(baseDir) + strlen(str) +
  505. strlen(dirsep) + 6);
  506. if (retval == NULL)
  507. __PHYSFS_setError(ERR_OUT_OF_MEMORY);
  508. else
  509. sprintf(retval, "%susers%s%s", baseDir, dirsep, str);
  510. allocator.Free((void *) uname);
  511. } /* else */
  512. return retval;
  513. } /* calculateUserDir */
  514. static int appendDirSep(char **dir)
  515. {
  516. const char *dirsep = PHYSFS_getDirSeparator();
  517. char *ptr;
  518. if (strcmp((*dir + strlen(*dir)) - strlen(dirsep), dirsep) == 0)
  519. return 1;
  520. ptr = (char *) allocator.Realloc(*dir, strlen(*dir) + strlen(dirsep) + 1);
  521. if (!ptr)
  522. {
  523. allocator.Free(*dir);
  524. return 0;
  525. } /* if */
  526. strcat(ptr, dirsep);
  527. *dir = ptr;
  528. return 1;
  529. } /* appendDirSep */
  530. static char *calculateBaseDir(const char *argv0)
  531. {
  532. char *retval = NULL;
  533. const char *dirsep = NULL;
  534. char *ptr = NULL;
  535. /* Give the platform layer first shot at this. */
  536. retval = __PHYSFS_platformCalcBaseDir(argv0);
  537. if (retval != NULL)
  538. return retval;
  539. /* We need argv0 to go on. */
  540. BAIL_IF_MACRO(argv0 == NULL, ERR_ARGV0_IS_NULL, NULL);
  541. dirsep = PHYSFS_getDirSeparator();
  542. if (strlen(dirsep) == 1) /* fast path. */
  543. ptr = strrchr(argv0, *dirsep);
  544. else
  545. {
  546. ptr = strstr(argv0, dirsep);
  547. if (ptr != NULL)
  548. {
  549. char *p = ptr;
  550. while (p != NULL)
  551. {
  552. ptr = p;
  553. p = strstr(p + 1, dirsep);
  554. } /* while */
  555. } /* if */
  556. } /* else */
  557. if (ptr != NULL)
  558. {
  559. size_t size = (size_t) (ptr - argv0);
  560. retval = (char *) allocator.Malloc(size + 1);
  561. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  562. memcpy(retval, argv0, size);
  563. retval[size] = '\0';
  564. return retval;
  565. } /* if */
  566. /* argv0 wasn't helpful. */
  567. BAIL_MACRO(ERR_INVALID_ARGUMENT, NULL);
  568. } /* calculateBaseDir */
  569. static int initializeMutexes(void)
  570. {
  571. errorLock = __PHYSFS_platformCreateMutex();
  572. if (errorLock == NULL)
  573. goto initializeMutexes_failed;
  574. stateLock = __PHYSFS_platformCreateMutex();
  575. if (stateLock == NULL)
  576. goto initializeMutexes_failed;
  577. return 1; /* success. */
  578. initializeMutexes_failed:
  579. if (errorLock != NULL)
  580. __PHYSFS_platformDestroyMutex(errorLock);
  581. if (stateLock != NULL)
  582. __PHYSFS_platformDestroyMutex(stateLock);
  583. errorLock = stateLock = NULL;
  584. return 0; /* failed. */
  585. } /* initializeMutexes */
  586. static void setDefaultAllocator(void);
  587. int PHYSFS_init(const char *argv0)
  588. {
  589. char *ptr;
  590. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  591. if (!externalAllocator)
  592. setDefaultAllocator();
  593. if (allocator.Init != NULL)
  594. BAIL_IF_MACRO(!allocator.Init(), NULL, 0);
  595. BAIL_IF_MACRO(!__PHYSFS_platformInit(), NULL, 0);
  596. BAIL_IF_MACRO(!initializeMutexes(), NULL, 0);
  597. baseDir = calculateBaseDir(argv0);
  598. BAIL_IF_MACRO(baseDir == NULL, NULL, 0);
  599. /* !!! FIXME: only call this if we got this from argv0 (unreliable). */
  600. ptr = __PHYSFS_platformRealPath(baseDir);
  601. allocator.Free(baseDir);
  602. BAIL_IF_MACRO(ptr == NULL, NULL, 0);
  603. baseDir = ptr;
  604. BAIL_IF_MACRO(!appendDirSep(&baseDir), NULL, 0);
  605. userDir = calculateUserDir();
  606. if (userDir != NULL)
  607. {
  608. ptr = __PHYSFS_platformRealPath(userDir);
  609. allocator.Free(userDir);
  610. userDir = ptr;
  611. } /* if */
  612. if ((userDir == NULL) || (!appendDirSep(&userDir)))
  613. {
  614. allocator.Free(baseDir);
  615. baseDir = NULL;
  616. return 0;
  617. } /* if */
  618. initialized = 1;
  619. /* This makes sure that the error subsystem is initialized. */
  620. __PHYSFS_setError(PHYSFS_getLastError());
  621. return 1;
  622. } /* PHYSFS_init */
  623. /* MAKE SURE you hold stateLock before calling this! */
  624. static int closeFileHandleList(FileHandle **list)
  625. {
  626. FileHandle *i;
  627. FileHandle *next = NULL;
  628. for (i = *list; i != NULL; i = next)
  629. {
  630. next = i->next;
  631. if (!i->funcs->fileClose(i->opaque))
  632. {
  633. *list = i;
  634. return 0;
  635. } /* if */
  636. allocator.Free(i);
  637. } /* for */
  638. *list = NULL;
  639. return 1;
  640. } /* closeFileHandleList */
  641. /* MAKE SURE you hold the stateLock before calling this! */
  642. static void freeSearchPath(void)
  643. {
  644. DirHandle *i;
  645. DirHandle *next = NULL;
  646. closeFileHandleList(&openReadList);
  647. if (searchPath != NULL)
  648. {
  649. for (i = searchPath; i != NULL; i = next)
  650. {
  651. next = i->next;
  652. freeDirHandle(i, openReadList);
  653. } /* for */
  654. searchPath = NULL;
  655. } /* if */
  656. } /* freeSearchPath */
  657. int PHYSFS_deinit(void)
  658. {
  659. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  660. BAIL_IF_MACRO(!__PHYSFS_platformDeinit(), NULL, 0);
  661. closeFileHandleList(&openWriteList);
  662. BAIL_IF_MACRO(!PHYSFS_setWriteDir(NULL), ERR_FILES_STILL_OPEN, 0);
  663. freeSearchPath();
  664. freeErrorMessages();
  665. if (baseDir != NULL)
  666. {
  667. allocator.Free(baseDir);
  668. baseDir = NULL;
  669. } /* if */
  670. if (userDir != NULL)
  671. {
  672. allocator.Free(userDir);
  673. userDir = NULL;
  674. } /* if */
  675. allowSymLinks = 0;
  676. initialized = 0;
  677. __PHYSFS_platformDestroyMutex(errorLock);
  678. __PHYSFS_platformDestroyMutex(stateLock);
  679. if (allocator.Deinit != NULL)
  680. allocator.Deinit();
  681. errorLock = stateLock = NULL;
  682. return 1;
  683. } /* PHYSFS_deinit */
  684. int PHYSFS_isInit(void)
  685. {
  686. return initialized;
  687. } /* PHYSFS_isInit */
  688. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  689. {
  690. return supported_types;
  691. } /* PHYSFS_supportedArchiveTypes */
  692. void PHYSFS_freeList(void *list)
  693. {
  694. void **i;
  695. if (list != NULL)
  696. {
  697. for (i = (void **) list; *i != NULL; i++)
  698. allocator.Free(*i);
  699. allocator.Free(list);
  700. } /* if */
  701. } /* PHYSFS_freeList */
  702. const char *PHYSFS_getDirSeparator(void)
  703. {
  704. return __PHYSFS_platformDirSeparator;
  705. } /* PHYSFS_getDirSeparator */
  706. char **PHYSFS_getCdRomDirs(void)
  707. {
  708. return doEnumStringList(__PHYSFS_platformDetectAvailableCDs);
  709. } /* PHYSFS_getCdRomDirs */
  710. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  711. {
  712. __PHYSFS_platformDetectAvailableCDs(callback, data);
  713. } /* PHYSFS_getCdRomDirsCallback */
  714. const char *PHYSFS_getBaseDir(void)
  715. {
  716. return baseDir; /* this is calculated in PHYSFS_init()... */
  717. } /* PHYSFS_getBaseDir */
  718. const char *PHYSFS_getUserDir(void)
  719. {
  720. return userDir; /* this is calculated in PHYSFS_init()... */
  721. } /* PHYSFS_getUserDir */
  722. const char *PHYSFS_getWriteDir(void)
  723. {
  724. const char *retval = NULL;
  725. __PHYSFS_platformGrabMutex(stateLock);
  726. if (writeDir != NULL)
  727. retval = writeDir->dirName;
  728. __PHYSFS_platformReleaseMutex(stateLock);
  729. return retval;
  730. } /* PHYSFS_getWriteDir */
  731. int PHYSFS_setWriteDir(const char *newDir)
  732. {
  733. int retval = 1;
  734. __PHYSFS_platformGrabMutex(stateLock);
  735. if (writeDir != NULL)
  736. {
  737. BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), NULL,
  738. stateLock, 0);
  739. writeDir = NULL;
  740. } /* if */
  741. if (newDir != NULL)
  742. {
  743. writeDir = createDirHandle(newDir, NULL, 1);
  744. retval = (writeDir != NULL);
  745. } /* if */
  746. __PHYSFS_platformReleaseMutex(stateLock);
  747. return retval;
  748. } /* PHYSFS_setWriteDir */
  749. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  750. {
  751. DirHandle *dh;
  752. DirHandle *prev = NULL;
  753. DirHandle *i;
  754. BAIL_IF_MACRO(newDir == NULL, ERR_INVALID_ARGUMENT, 0);
  755. if (mountPoint == NULL)
  756. mountPoint = "/";
  757. __PHYSFS_platformGrabMutex(stateLock);
  758. for (i = searchPath; i != NULL; i = i->next)
  759. {
  760. /* already in search path? */
  761. BAIL_IF_MACRO_MUTEX(strcmp(newDir, i->dirName)==0, NULL, stateLock, 1);
  762. prev = i;
  763. } /* for */
  764. dh = createDirHandle(newDir, mountPoint, 0);
  765. BAIL_IF_MACRO_MUTEX(dh == NULL, NULL, stateLock, 0);
  766. if (appendToPath)
  767. {
  768. if (prev == NULL)
  769. searchPath = dh;
  770. else
  771. prev->next = dh;
  772. } /* if */
  773. else
  774. {
  775. dh->next = searchPath;
  776. searchPath = dh;
  777. } /* else */
  778. __PHYSFS_platformReleaseMutex(stateLock);
  779. return 1;
  780. } /* PHYSFS_mount */
  781. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  782. {
  783. return PHYSFS_mount(newDir, NULL, appendToPath);
  784. } /* PHYSFS_addToSearchPath */
  785. int PHYSFS_removeFromSearchPath(const char *oldDir)
  786. {
  787. DirHandle *i;
  788. DirHandle *prev = NULL;
  789. DirHandle *next = NULL;
  790. BAIL_IF_MACRO(oldDir == NULL, ERR_INVALID_ARGUMENT, 0);
  791. __PHYSFS_platformGrabMutex(stateLock);
  792. for (i = searchPath; i != NULL; i = i->next)
  793. {
  794. if (strcmp(i->dirName, oldDir) == 0)
  795. {
  796. next = i->next;
  797. BAIL_IF_MACRO_MUTEX(!freeDirHandle(i, openReadList), NULL,
  798. stateLock, 0);
  799. if (prev == NULL)
  800. searchPath = next;
  801. else
  802. prev->next = next;
  803. BAIL_MACRO_MUTEX(NULL, stateLock, 1);
  804. } /* if */
  805. prev = i;
  806. } /* for */
  807. BAIL_MACRO_MUTEX(ERR_NOT_IN_SEARCH_PATH, stateLock, 0);
  808. } /* PHYSFS_removeFromSearchPath */
  809. char **PHYSFS_getSearchPath(void)
  810. {
  811. return doEnumStringList(PHYSFS_getSearchPathCallback);
  812. } /* PHYSFS_getSearchPath */
  813. const char *PHYSFS_getMountPoint(const char *dir)
  814. {
  815. DirHandle *i;
  816. __PHYSFS_platformGrabMutex(stateLock);
  817. for (i = searchPath; i != NULL; i = i->next)
  818. {
  819. if (strcmp(i->dirName, dir) == 0)
  820. {
  821. const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
  822. __PHYSFS_platformReleaseMutex(stateLock);
  823. return retval;
  824. } /* if */
  825. } /* for */
  826. __PHYSFS_platformReleaseMutex(stateLock);
  827. BAIL_MACRO(ERR_NOT_IN_SEARCH_PATH, NULL);
  828. } /* PHYSFS_getMountPoint */
  829. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  830. {
  831. DirHandle *i;
  832. __PHYSFS_platformGrabMutex(stateLock);
  833. for (i = searchPath; i != NULL; i = i->next)
  834. callback(data, i->dirName);
  835. __PHYSFS_platformReleaseMutex(stateLock);
  836. } /* PHYSFS_getSearchPathCallback */
  837. /* Split out to avoid stack allocation in a loop. */
  838. static void setSaneCfgAddPath(const char *i, const size_t l, const char *dirsep,
  839. int archivesFirst)
  840. {
  841. const char *d = PHYSFS_getRealDir(i);
  842. const size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
  843. char *str = (char *) __PHYSFS_smallAlloc(allocsize);
  844. if (str != NULL)
  845. {
  846. sprintf(str, "%s%s%s", d, dirsep, i);
  847. PHYSFS_addToSearchPath(str, archivesFirst == 0);
  848. __PHYSFS_smallFree(str);
  849. } /* if */
  850. } /* setSaneCfgAddPath */
  851. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  852. const char *archiveExt, int includeCdRoms,
  853. int archivesFirst)
  854. {
  855. const char *basedir = PHYSFS_getBaseDir();
  856. const char *userdir = PHYSFS_getUserDir();
  857. const char *dirsep = PHYSFS_getDirSeparator();
  858. PHYSFS_uint64 len = 0;
  859. char *str = NULL;
  860. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  861. /* set write dir... */
  862. len = (strlen(userdir) + (strlen(organization) * 2) +
  863. (strlen(appName) * 2) + (strlen(dirsep) * 3) + 2);
  864. str = (char *) __PHYSFS_smallAlloc(len);
  865. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
  866. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  867. if (!PHYSFS_setWriteDir(str))
  868. {
  869. int no_write = 0;
  870. sprintf(str, ".%s/%s", organization, appName);
  871. if ( (PHYSFS_setWriteDir(userdir)) &&
  872. (PHYSFS_mkdir(str)) )
  873. {
  874. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  875. if (!PHYSFS_setWriteDir(str))
  876. no_write = 1;
  877. } /* if */
  878. else
  879. {
  880. no_write = 1;
  881. } /* else */
  882. if (no_write)
  883. {
  884. PHYSFS_setWriteDir(NULL); /* just in case. */
  885. __PHYSFS_smallFree(str);
  886. BAIL_MACRO(ERR_CANT_SET_WRITE_DIR, 0);
  887. } /* if */
  888. } /* if */
  889. /* Put write dir first in search path... */
  890. PHYSFS_addToSearchPath(str, 0);
  891. __PHYSFS_smallFree(str);
  892. /* Put base path on search path... */
  893. PHYSFS_addToSearchPath(basedir, 1);
  894. /* handle CD-ROMs... */
  895. if (includeCdRoms)
  896. {
  897. char **cds = PHYSFS_getCdRomDirs();
  898. char **i;
  899. for (i = cds; *i != NULL; i++)
  900. PHYSFS_addToSearchPath(*i, 1);
  901. PHYSFS_freeList(cds);
  902. } /* if */
  903. /* Root out archives, and add them to search path... */
  904. if (archiveExt != NULL)
  905. {
  906. char **rc = PHYSFS_enumerateFiles("/");
  907. char **i;
  908. size_t extlen = strlen(archiveExt);
  909. char *ext;
  910. for (i = rc; *i != NULL; i++)
  911. {
  912. size_t l = strlen(*i);
  913. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  914. {
  915. ext = (*i) + (l - extlen);
  916. if (__PHYSFS_stricmpASCII(ext, archiveExt) == 0)
  917. setSaneCfgAddPath(*i, l, dirsep, archivesFirst);
  918. } /* if */
  919. } /* for */
  920. PHYSFS_freeList(rc);
  921. } /* if */
  922. return 1;
  923. } /* PHYSFS_setSaneConfig */
  924. void PHYSFS_permitSymbolicLinks(int allow)
  925. {
  926. allowSymLinks = allow;
  927. } /* PHYSFS_permitSymbolicLinks */
  928. int PHYSFS_symbolicLinksPermitted(void)
  929. {
  930. return allowSymLinks;
  931. } /* PHYSFS_symbolicLinksPermitted */
  932. /* string manipulation in C makes my ass itch. */
  933. char *__PHYSFS_convertToDependent(const char *prepend,
  934. const char *dirName,
  935. const char *append)
  936. {
  937. const char *dirsep = __PHYSFS_platformDirSeparator;
  938. size_t sepsize = strlen(dirsep);
  939. char *str;
  940. char *i1;
  941. char *i2;
  942. size_t allocSize;
  943. while (*dirName == '/') /* !!! FIXME: pass through sanitize function. */
  944. dirName++;
  945. allocSize = strlen(dirName) + 1;
  946. if (prepend != NULL)
  947. allocSize += strlen(prepend) + sepsize;
  948. if (append != NULL)
  949. allocSize += strlen(append) + sepsize;
  950. /* make sure there's enough space if the dir separator is bigger. */
  951. if (sepsize > 1)
  952. {
  953. str = (char *) dirName;
  954. do
  955. {
  956. str = strchr(str, '/');
  957. if (str != NULL)
  958. {
  959. allocSize += (sepsize - 1);
  960. str++;
  961. } /* if */
  962. } while (str != NULL);
  963. } /* if */
  964. str = (char *) allocator.Malloc(allocSize);
  965. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, NULL);
  966. if (prepend == NULL)
  967. *str = '\0';
  968. else
  969. {
  970. strcpy(str, prepend);
  971. strcat(str, dirsep);
  972. } /* else */
  973. for (i1 = (char *) dirName, i2 = str + strlen(str); *i1; i1++, i2++)
  974. {
  975. if (*i1 == '/')
  976. {
  977. strcpy(i2, dirsep);
  978. i2 += sepsize;
  979. } /* if */
  980. else
  981. {
  982. *i2 = *i1;
  983. } /* else */
  984. } /* for */
  985. *i2 = '\0';
  986. if (append)
  987. {
  988. strcat(str, dirsep);
  989. strcat(str, append);
  990. } /* if */
  991. return str;
  992. } /* __PHYSFS_convertToDependent */
  993. /*
  994. * Verify that (fname) (in platform-independent notation), in relation
  995. * to (h) is secure. That means that each element of fname is checked
  996. * for symlinks (if they aren't permitted). This also allows for quick
  997. * rejection of files that exist outside an archive's mountpoint.
  998. *
  999. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  1000. * at a time), you should always pass zero for "allowMissing" for efficiency.
  1001. *
  1002. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  1003. * since it will make sure that path names are in the right format for
  1004. * passing certain checks. It will also do checks for "insecure" pathnames
  1005. * like ".." which should be done once instead of once per archive. This also
  1006. * gives us license to treat (fname) as scratch space in this function.
  1007. *
  1008. * Returns non-zero if string is safe, zero if there's a security issue.
  1009. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  1010. * updated to point past any mount point elements so it is prepared to
  1011. * be used with the archiver directly.
  1012. */
  1013. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1014. {
  1015. char *fname = *_fname;
  1016. int retval = 1;
  1017. char *start;
  1018. char *end;
  1019. if (*fname == '\0') /* quick rejection. */
  1020. return 1;
  1021. /* !!! FIXME: This codeblock sucks. */
  1022. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1023. {
  1024. size_t mntpntlen = strlen(h->mountPoint);
  1025. size_t len = strlen(fname);
  1026. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1027. /* not under the mountpoint, so skip this archive. */
  1028. BAIL_IF_MACRO(len < mntpntlen-1, ERR_NO_SUCH_PATH, 0);
  1029. /* !!! FIXME: Case insensitive? */
  1030. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1031. BAIL_IF_MACRO(retval != 0, ERR_NO_SUCH_PATH, 0);
  1032. if (len > mntpntlen-1) /* corner case... */
  1033. BAIL_IF_MACRO(fname[mntpntlen-1] != '/', ERR_NO_SUCH_PATH, 0);
  1034. fname += mntpntlen-1; /* move to start of actual archive path. */
  1035. if (*fname == '/')
  1036. fname++;
  1037. *_fname = fname; /* skip mountpoint for later use. */
  1038. retval = 1; /* may be reset, below. */
  1039. } /* if */
  1040. start = fname;
  1041. if (!allowSymLinks)
  1042. {
  1043. while (1)
  1044. {
  1045. int rc = 0;
  1046. end = strchr(start, '/');
  1047. if (end != NULL) *end = '\0';
  1048. rc = h->funcs->isSymLink(h->opaque, fname, &retval);
  1049. if (end != NULL) *end = '/';
  1050. BAIL_IF_MACRO(rc, ERR_SYMLINK_DISALLOWED, 0); /* insecure. */
  1051. /* break out early if path element is missing. */
  1052. if (!retval)
  1053. {
  1054. /*
  1055. * We need to clear it if it's the last element of the path,
  1056. * since this might be a non-existant file we're opening
  1057. * for writing...
  1058. */
  1059. if ((end == NULL) || (allowMissing))
  1060. retval = 1;
  1061. break;
  1062. } /* if */
  1063. if (end == NULL)
  1064. break;
  1065. start = end + 1;
  1066. } /* while */
  1067. } /* if */
  1068. return retval;
  1069. } /* verifyPath */
  1070. static int doMkdir(const char *_dname, char *dname)
  1071. {
  1072. DirHandle *h;
  1073. char *start;
  1074. char *end;
  1075. int retval = 0;
  1076. int exists = 1; /* force existance check on first path element. */
  1077. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_dname, dname), NULL, 0);
  1078. __PHYSFS_platformGrabMutex(stateLock);
  1079. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1080. h = writeDir;
  1081. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &dname, 1), NULL, stateLock, 0);
  1082. start = dname;
  1083. while (1)
  1084. {
  1085. end = strchr(start, '/');
  1086. if (end != NULL)
  1087. *end = '\0';
  1088. /* only check for existance if all parent dirs existed, too... */
  1089. if (exists)
  1090. retval = h->funcs->isDirectory(h->opaque, dname, &exists);
  1091. if (!exists)
  1092. retval = h->funcs->mkdir(h->opaque, dname);
  1093. if (!retval)
  1094. break;
  1095. if (end == NULL)
  1096. break;
  1097. *end = '/';
  1098. start = end + 1;
  1099. } /* while */
  1100. __PHYSFS_platformReleaseMutex(stateLock);
  1101. return retval;
  1102. } /* doMkdir */
  1103. int PHYSFS_mkdir(const char *_dname)
  1104. {
  1105. int retval = 0;
  1106. char *dname;
  1107. size_t len;
  1108. BAIL_IF_MACRO(_dname == NULL, ERR_INVALID_ARGUMENT, 0);
  1109. len = strlen(_dname) + 1;
  1110. dname = (char *) __PHYSFS_smallAlloc(len);
  1111. BAIL_IF_MACRO(dname == NULL, ERR_OUT_OF_MEMORY, 0);
  1112. retval = doMkdir(_dname, dname);
  1113. __PHYSFS_smallFree(dname);
  1114. return retval;
  1115. } /* PHYSFS_mkdir */
  1116. static int doDelete(const char *_fname, char *fname)
  1117. {
  1118. int retval;
  1119. DirHandle *h;
  1120. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1121. __PHYSFS_platformGrabMutex(stateLock);
  1122. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1123. h = writeDir;
  1124. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, 0);
  1125. retval = h->funcs->remove(h->opaque, fname);
  1126. __PHYSFS_platformReleaseMutex(stateLock);
  1127. return retval;
  1128. } /* doDelete */
  1129. int PHYSFS_delete(const char *_fname)
  1130. {
  1131. int retval;
  1132. char *fname;
  1133. size_t len;
  1134. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1135. len = strlen(_fname) + 1;
  1136. fname = (char *) __PHYSFS_smallAlloc(len);
  1137. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1138. retval = doDelete(_fname, fname);
  1139. __PHYSFS_smallFree(fname);
  1140. return retval;
  1141. } /* PHYSFS_delete */
  1142. const char *PHYSFS_getRealDir(const char *_fname)
  1143. {
  1144. const char *retval = NULL;
  1145. char *fname = NULL;
  1146. size_t len;
  1147. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1148. len = strlen(_fname) + 1;
  1149. fname = __PHYSFS_smallAlloc(len);
  1150. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, NULL);
  1151. if (sanitizePlatformIndependentPath(_fname, fname))
  1152. {
  1153. DirHandle *i;
  1154. __PHYSFS_platformGrabMutex(stateLock);
  1155. for (i = searchPath; ((i != NULL) && (retval == NULL)); i = i->next)
  1156. {
  1157. char *arcfname = fname;
  1158. if (partOfMountPoint(i, arcfname))
  1159. retval = i->dirName;
  1160. else if (verifyPath(i, &arcfname, 0))
  1161. {
  1162. if (i->funcs->exists(i->opaque, arcfname))
  1163. retval = i->dirName;
  1164. } /* if */
  1165. } /* for */
  1166. __PHYSFS_platformReleaseMutex(stateLock);
  1167. } /* if */
  1168. __PHYSFS_smallFree(fname);
  1169. return retval;
  1170. } /* PHYSFS_getRealDir */
  1171. static int locateInStringList(const char *str,
  1172. char **list,
  1173. PHYSFS_uint32 *pos)
  1174. {
  1175. PHYSFS_uint32 len = *pos;
  1176. PHYSFS_uint32 half_len;
  1177. PHYSFS_uint32 lo = 0;
  1178. PHYSFS_uint32 middle;
  1179. int cmp;
  1180. while (len > 0)
  1181. {
  1182. half_len = len >> 1;
  1183. middle = lo + half_len;
  1184. cmp = strcmp(list[middle], str);
  1185. if (cmp == 0) /* it's in the list already. */
  1186. return 1;
  1187. else if (cmp > 0)
  1188. len = half_len;
  1189. else
  1190. {
  1191. lo = middle + 1;
  1192. len -= half_len + 1;
  1193. } /* else */
  1194. } /* while */
  1195. *pos = lo;
  1196. return 0;
  1197. } /* locateInStringList */
  1198. static void enumFilesCallback(void *data, const char *origdir, const char *str)
  1199. {
  1200. PHYSFS_uint32 pos;
  1201. void *ptr;
  1202. char *newstr;
  1203. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1204. /*
  1205. * See if file is in the list already, and if not, insert it in there
  1206. * alphabetically...
  1207. */
  1208. pos = pecd->size;
  1209. if (locateInStringList(str, pecd->list, &pos))
  1210. return; /* already in the list. */
  1211. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1212. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1213. if (ptr != NULL)
  1214. pecd->list = (char **) ptr;
  1215. if ((ptr == NULL) || (newstr == NULL))
  1216. return; /* better luck next time. */
  1217. strcpy(newstr, str);
  1218. if (pos != pecd->size)
  1219. {
  1220. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1221. sizeof (char *) * ((pecd->size) - pos));
  1222. } /* if */
  1223. pecd->list[pos] = newstr;
  1224. pecd->size++;
  1225. } /* enumFilesCallback */
  1226. char **PHYSFS_enumerateFiles(const char *path)
  1227. {
  1228. EnumStringListCallbackData ecd;
  1229. memset(&ecd, '\0', sizeof (ecd));
  1230. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1231. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  1232. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1233. ecd.list[ecd.size] = NULL;
  1234. return ecd.list;
  1235. } /* PHYSFS_enumerateFiles */
  1236. /*
  1237. * Broke out to seperate function so we can use stack allocation gratuitously.
  1238. */
  1239. static void enumerateFromMountPoint(DirHandle *i, const char *arcfname,
  1240. PHYSFS_EnumFilesCallback callback,
  1241. const char *_fname, void *data)
  1242. {
  1243. const size_t len = strlen(arcfname);
  1244. char *ptr = NULL;
  1245. char *end = NULL;
  1246. const size_t slen = strlen(i->mountPoint) + 1;
  1247. char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
  1248. if (mountPoint == NULL)
  1249. return; /* oh well. */
  1250. strcpy(mountPoint, i->mountPoint);
  1251. ptr = mountPoint + ((len) ? len + 1 : 0);
  1252. end = strchr(ptr, '/');
  1253. assert(end); /* should always find a terminating '/'. */
  1254. *end = '\0';
  1255. callback(data, _fname, ptr);
  1256. __PHYSFS_smallFree(mountPoint);
  1257. } /* enumerateFromMountPoint */
  1258. /* !!! FIXME: this should report error conditions. */
  1259. void PHYSFS_enumerateFilesCallback(const char *_fname,
  1260. PHYSFS_EnumFilesCallback callback,
  1261. void *data)
  1262. {
  1263. size_t len;
  1264. char *fname;
  1265. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
  1266. BAIL_IF_MACRO(callback == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
  1267. len = strlen(_fname) + 1;
  1268. fname = (char *) __PHYSFS_smallAlloc(len);
  1269. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, ) /*0*/;
  1270. if (sanitizePlatformIndependentPath(_fname, fname))
  1271. {
  1272. DirHandle *i;
  1273. int noSyms;
  1274. __PHYSFS_platformGrabMutex(stateLock);
  1275. noSyms = !allowSymLinks;
  1276. for (i = searchPath; i != NULL; i = i->next)
  1277. {
  1278. char *arcfname = fname;
  1279. if (partOfMountPoint(i, arcfname))
  1280. enumerateFromMountPoint(i, arcfname, callback, _fname, data);
  1281. else if (verifyPath(i, &arcfname, 0))
  1282. {
  1283. i->funcs->enumerateFiles(i->opaque, arcfname, noSyms,
  1284. callback, _fname, data);
  1285. } /* else if */
  1286. } /* for */
  1287. __PHYSFS_platformReleaseMutex(stateLock);
  1288. } /* if */
  1289. __PHYSFS_smallFree(fname);
  1290. } /* PHYSFS_enumerateFilesCallback */
  1291. int PHYSFS_exists(const char *fname)
  1292. {
  1293. return (PHYSFS_getRealDir(fname) != NULL);
  1294. } /* PHYSFS_exists */
  1295. PHYSFS_sint64 PHYSFS_getLastModTime(const char *_fname)
  1296. {
  1297. PHYSFS_sint64 retval = -1;
  1298. char *fname;
  1299. size_t len;
  1300. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, -1);
  1301. len = strlen(_fname) + 1;
  1302. fname = (char *) __PHYSFS_smallAlloc(len);
  1303. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, -1);
  1304. if (sanitizePlatformIndependentPath(_fname, fname))
  1305. {
  1306. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1307. retval = 1; /* !!! FIXME: Maybe this should be an error? */
  1308. else
  1309. {
  1310. DirHandle *i;
  1311. int exists = 0;
  1312. __PHYSFS_platformGrabMutex(stateLock);
  1313. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  1314. {
  1315. char *arcfname = fname;
  1316. exists = partOfMountPoint(i, arcfname);
  1317. if (exists)
  1318. retval = 1; /* !!! FIXME: What's the right value? */
  1319. else if (verifyPath(i, &arcfname, 0))
  1320. {
  1321. retval = i->funcs->getLastModTime(i->opaque, arcfname,
  1322. &exists);
  1323. } /* else if */
  1324. } /* for */
  1325. __PHYSFS_platformReleaseMutex(stateLock);
  1326. } /* else */
  1327. } /* if */
  1328. __PHYSFS_smallFree(fname);
  1329. return retval;
  1330. } /* PHYSFS_getLastModTime */
  1331. int PHYSFS_isDirectory(const char *_fname)
  1332. {
  1333. int retval = 0;
  1334. size_t len;
  1335. char *fname;
  1336. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1337. len = strlen(_fname) + 1;
  1338. fname = (char *) __PHYSFS_smallAlloc(len);
  1339. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1340. if (!sanitizePlatformIndependentPath(_fname, fname))
  1341. retval = 0;
  1342. else if (*fname == '\0')
  1343. retval = 1; /* Root is always a dir. :) */
  1344. else
  1345. {
  1346. DirHandle *i;
  1347. int exists = 0;
  1348. __PHYSFS_platformGrabMutex(stateLock);
  1349. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  1350. {
  1351. char *arcfname = fname;
  1352. if ((exists = partOfMountPoint(i, arcfname)) != 0)
  1353. retval = 1;
  1354. else if (verifyPath(i, &arcfname, 0))
  1355. retval = i->funcs->isDirectory(i->opaque, arcfname, &exists);
  1356. } /* for */
  1357. __PHYSFS_platformReleaseMutex(stateLock);
  1358. } /* else */
  1359. __PHYSFS_smallFree(fname);
  1360. return retval;
  1361. } /* PHYSFS_isDirectory */
  1362. int PHYSFS_isSymbolicLink(const char *_fname)
  1363. {
  1364. int retval = 0;
  1365. size_t len;
  1366. char *fname;
  1367. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1368. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1369. len = strlen(_fname) + 1;
  1370. fname = (char *) __PHYSFS_smallAlloc(len);
  1371. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1372. if (!sanitizePlatformIndependentPath(_fname, fname))
  1373. retval = 0;
  1374. else if (*fname == '\0')
  1375. retval = 1; /* Root is never a symlink. */
  1376. else
  1377. {
  1378. DirHandle *i;
  1379. int fileExists = 0;
  1380. __PHYSFS_platformGrabMutex(stateLock);
  1381. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1382. {
  1383. char *arcfname = fname;
  1384. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1385. retval = 0; /* virtual dir...not a symlink. */
  1386. else if (verifyPath(i, &arcfname, 0))
  1387. retval = i->funcs->isSymLink(i->opaque, arcfname, &fileExists);
  1388. } /* for */
  1389. __PHYSFS_platformReleaseMutex(stateLock);
  1390. } /* else */
  1391. __PHYSFS_smallFree(fname);
  1392. return retval;
  1393. } /* PHYSFS_isSymbolicLink */
  1394. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1395. {
  1396. FileHandle *fh = NULL;
  1397. size_t len;
  1398. char *fname;
  1399. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1400. len = strlen(_fname) + 1;
  1401. fname = (char *) __PHYSFS_smallAlloc(len);
  1402. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1403. if (sanitizePlatformIndependentPath(_fname, fname))
  1404. {
  1405. void *opaque = NULL;
  1406. DirHandle *h = NULL;
  1407. const PHYSFS_Archiver *f;
  1408. __PHYSFS_platformGrabMutex(stateLock);
  1409. GOTO_IF_MACRO(!writeDir, ERR_NO_WRITE_DIR, doOpenWriteEnd);
  1410. h = writeDir;
  1411. GOTO_IF_MACRO(!verifyPath(h, &fname, 0), NULL, doOpenWriteEnd);
  1412. f = h->funcs;
  1413. if (appending)
  1414. opaque = f->openAppend(h->opaque, fname);
  1415. else
  1416. opaque = f->openWrite(h->opaque, fname);
  1417. GOTO_IF_MACRO(opaque == NULL, NULL, doOpenWriteEnd);
  1418. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1419. if (fh == NULL)
  1420. {
  1421. f->fileClose(opaque);
  1422. GOTO_MACRO(ERR_OUT_OF_MEMORY, doOpenWriteEnd);
  1423. } /* if */
  1424. else
  1425. {
  1426. memset(fh, '\0', sizeof (FileHandle));
  1427. fh->opaque = opaque;
  1428. fh->dirHandle = h;
  1429. fh->funcs = h->funcs;
  1430. fh->next = openWriteList;
  1431. openWriteList = fh;
  1432. } /* else */
  1433. doOpenWriteEnd:
  1434. __PHYSFS_platformReleaseMutex(stateLock);
  1435. } /* if */
  1436. __PHYSFS_smallFree(fname);
  1437. return ((PHYSFS_File *) fh);
  1438. } /* doOpenWrite */
  1439. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1440. {
  1441. return doOpenWrite(filename, 0);
  1442. } /* PHYSFS_openWrite */
  1443. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1444. {
  1445. return doOpenWrite(filename, 1);
  1446. } /* PHYSFS_openAppend */
  1447. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  1448. {
  1449. FileHandle *fh = NULL;
  1450. char *fname;
  1451. size_t len;
  1452. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1453. len = strlen(_fname) + 1;
  1454. fname = (char *) __PHYSFS_smallAlloc(len);
  1455. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1456. if (sanitizePlatformIndependentPath(_fname, fname))
  1457. {
  1458. int fileExists = 0;
  1459. DirHandle *i = NULL;
  1460. fvoid *opaque = NULL;
  1461. __PHYSFS_platformGrabMutex(stateLock);
  1462. GOTO_IF_MACRO(!searchPath, ERR_NO_SUCH_PATH, openReadEnd);
  1463. /* !!! FIXME: Why aren't we using a for loop here? */
  1464. i = searchPath;
  1465. do
  1466. {
  1467. char *arcfname = fname;
  1468. if (verifyPath(i, &arcfname, 0))
  1469. {
  1470. opaque = i->funcs->openRead(i->opaque, arcfname, &fileExists);
  1471. if (opaque)
  1472. break;
  1473. } /* if */
  1474. i = i->next;
  1475. } while ((i != NULL) && (!fileExists));
  1476. /* !!! FIXME: may not set an error if openRead didn't fail. */
  1477. GOTO_IF_MACRO(opaque == NULL, NULL, openReadEnd);
  1478. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1479. if (fh == NULL)
  1480. {
  1481. i->funcs->fileClose(opaque);
  1482. GOTO_MACRO(ERR_OUT_OF_MEMORY, openReadEnd);
  1483. } /* if */
  1484. memset(fh, '\0', sizeof (FileHandle));
  1485. fh->opaque = opaque;
  1486. fh->forReading = 1;
  1487. fh->dirHandle = i;
  1488. fh->funcs = i->funcs;
  1489. fh->next = openReadList;
  1490. openReadList = fh;
  1491. openReadEnd:
  1492. __PHYSFS_platformReleaseMutex(stateLock);
  1493. } /* if */
  1494. __PHYSFS_smallFree(fname);
  1495. return ((PHYSFS_File *) fh);
  1496. } /* PHYSFS_openRead */
  1497. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1498. {
  1499. FileHandle *prev = NULL;
  1500. FileHandle *i;
  1501. int rc = 1;
  1502. for (i = *list; i != NULL; i = i->next)
  1503. {
  1504. if (i == handle) /* handle is in this list? */
  1505. {
  1506. PHYSFS_uint8 *tmp = handle->buffer;
  1507. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1508. if (rc)
  1509. rc = handle->funcs->fileClose(handle->opaque);
  1510. if (!rc)
  1511. return -1;
  1512. if (tmp != NULL) /* free any associated buffer. */
  1513. allocator.Free(tmp);
  1514. if (prev == NULL)
  1515. *list = handle->next;
  1516. else
  1517. prev->next = handle->next;
  1518. allocator.Free(handle);
  1519. return 1;
  1520. } /* if */
  1521. prev = i;
  1522. } /* for */
  1523. return 0;
  1524. } /* closeHandleInOpenList */
  1525. int PHYSFS_close(PHYSFS_File *_handle)
  1526. {
  1527. FileHandle *handle = (FileHandle *) _handle;
  1528. int rc;
  1529. __PHYSFS_platformGrabMutex(stateLock);
  1530. /* -1 == close failure. 0 == not found. 1 == success. */
  1531. rc = closeHandleInOpenList(&openReadList, handle);
  1532. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1533. if (!rc)
  1534. {
  1535. rc = closeHandleInOpenList(&openWriteList, handle);
  1536. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1537. } /* if */
  1538. __PHYSFS_platformReleaseMutex(stateLock);
  1539. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1540. return 1;
  1541. } /* PHYSFS_close */
  1542. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1543. PHYSFS_uint32 objSize,
  1544. PHYSFS_uint32 objCount)
  1545. {
  1546. PHYSFS_sint64 retval = 0;
  1547. PHYSFS_uint32 remainder = 0;
  1548. while (objCount > 0)
  1549. {
  1550. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1551. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1552. PHYSFS_uint32 copied;
  1553. if (buffered == 0) /* need to refill buffer? */
  1554. {
  1555. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1556. 1, fh->bufsize);
  1557. if (rc <= 0)
  1558. {
  1559. fh->bufpos -= remainder;
  1560. return ( ((rc == -1) && (retval == 0)) ? -1 : retval );
  1561. } /* if */
  1562. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1563. fh->bufpos = 0;
  1564. } /* if */
  1565. if (buffered > mustread)
  1566. buffered = (PHYSFS_uint32) mustread;
  1567. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1568. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1569. fh->bufpos += buffered;
  1570. buffered += remainder; /* take remainder into account. */
  1571. copied = (buffered / objSize);
  1572. remainder = (buffered % objSize);
  1573. retval += copied;
  1574. objCount -= copied;
  1575. } /* while */
  1576. return retval;
  1577. } /* doBufferedRead */
  1578. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1579. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1580. {
  1581. FileHandle *fh = (FileHandle *) handle;
  1582. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1583. BAIL_IF_MACRO(objSize == 0, NULL, 0);
  1584. BAIL_IF_MACRO(objCount == 0, NULL, 0);
  1585. if (fh->buffer != NULL)
  1586. return doBufferedRead(fh, buffer, objSize, objCount);
  1587. return fh->funcs->read(fh->opaque, buffer, objSize, objCount);
  1588. } /* PHYSFS_read */
  1589. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1590. PHYSFS_uint32 objSize,
  1591. PHYSFS_uint32 objCount)
  1592. {
  1593. FileHandle *fh = (FileHandle *) handle;
  1594. /* whole thing fits in the buffer? */
  1595. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1596. {
  1597. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1598. fh->buffill += (objSize * objCount);
  1599. return objCount;
  1600. } /* if */
  1601. /* would overflow buffer. Flush and then write the new objects, too. */
  1602. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1603. return fh->funcs->write(fh->opaque, buffer, objSize, objCount);
  1604. } /* doBufferedWrite */
  1605. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1606. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1607. {
  1608. FileHandle *fh = (FileHandle *) handle;
  1609. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1610. BAIL_IF_MACRO(objSize == 0, NULL, 0);
  1611. BAIL_IF_MACRO(objCount == 0, NULL, 0);
  1612. if (fh->buffer != NULL)
  1613. return doBufferedWrite(handle, buffer, objSize, objCount);
  1614. return fh->funcs->write(fh->opaque, buffer, objSize, objCount);
  1615. } /* PHYSFS_write */
  1616. int PHYSFS_eof(PHYSFS_File *handle)
  1617. {
  1618. FileHandle *fh = (FileHandle *) handle;
  1619. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1620. return 0;
  1621. /* eof if buffer is empty and archiver says so. */
  1622. return (fh->bufpos == fh->buffill && (fh->funcs->eof(fh->opaque)));
  1623. } /* PHYSFS_eof */
  1624. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1625. {
  1626. FileHandle *fh = (FileHandle *) handle;
  1627. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1628. PHYSFS_sint64 retval = fh->forReading ?
  1629. (pos - fh->buffill) + fh->bufpos :
  1630. (pos + fh->buffill);
  1631. return retval;
  1632. } /* PHYSFS_tell */
  1633. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1634. {
  1635. FileHandle *fh = (FileHandle *) handle;
  1636. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1637. if (fh->buffer && fh->forReading)
  1638. {
  1639. /* avoid throwing away our precious buffer if seeking within it. */
  1640. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1641. if ( /* seeking within the already-buffered range? */
  1642. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1643. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1644. {
  1645. fh->bufpos += (PHYSFS_uint32) offset;
  1646. return 1; /* successful seek */
  1647. } /* if */
  1648. } /* if */
  1649. /* we have to fall back to a 'raw' seek. */
  1650. fh->buffill = fh->bufpos = 0;
  1651. return fh->funcs->seek(fh->opaque, pos);
  1652. } /* PHYSFS_seek */
  1653. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1654. {
  1655. FileHandle *fh = (FileHandle *) handle;
  1656. return fh->funcs->fileLength(fh->opaque);
  1657. } /* PHYSFS_filelength */
  1658. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1659. {
  1660. FileHandle *fh = (FileHandle *) handle;
  1661. PHYSFS_uint32 bufsize;
  1662. /* !!! FIXME: Unlocalized string. */
  1663. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1664. bufsize = (PHYSFS_uint32) _bufsize;
  1665. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1666. /*
  1667. * For reads, we need to move the file pointer to where it would be
  1668. * if we weren't buffering, so that the next read will get the
  1669. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1670. */
  1671. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1672. {
  1673. PHYSFS_uint64 pos;
  1674. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1675. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1676. pos = ((curpos - fh->buffill) + fh->bufpos);
  1677. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1678. } /* if */
  1679. if (bufsize == 0) /* delete existing buffer. */
  1680. {
  1681. if (fh->buffer != NULL)
  1682. {
  1683. allocator.Free(fh->buffer);
  1684. fh->buffer = NULL;
  1685. } /* if */
  1686. } /* if */
  1687. else
  1688. {
  1689. PHYSFS_uint8 *newbuf;
  1690. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  1691. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1692. fh->buffer = newbuf;
  1693. } /* else */
  1694. fh->bufsize = bufsize;
  1695. fh->buffill = fh->bufpos = 0;
  1696. return 1;
  1697. } /* PHYSFS_setBuffer */
  1698. int PHYSFS_flush(PHYSFS_File *handle)
  1699. {
  1700. FileHandle *fh = (FileHandle *) handle;
  1701. PHYSFS_sint64 rc;
  1702. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1703. return 1; /* open for read or buffer empty are successful no-ops. */
  1704. /* dump buffer to disk. */
  1705. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1706. fh->buffill - fh->bufpos, 1);
  1707. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1708. fh->bufpos = fh->buffill = 0;
  1709. return 1;
  1710. } /* PHYSFS_flush */
  1711. int PHYSFS_stat(const char *_fname, PHYSFS_Stat *stat)
  1712. {
  1713. int retval = 0;
  1714. char *fname;
  1715. size_t len;
  1716. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, -1);
  1717. BAIL_IF_MACRO(stat == NULL, ERR_INVALID_ARGUMENT, -1);
  1718. len = strlen(_fname) + 1;
  1719. fname = (char *) __PHYSFS_smallAlloc(len);
  1720. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, -1);
  1721. /* !!! FIXME: what should this be set to if we fail completely? */
  1722. memset(stat, '\0', sizeof (PHYSFS_Stat));
  1723. if (sanitizePlatformIndependentPath(_fname, fname))
  1724. {
  1725. if (*fname == '\0')
  1726. {
  1727. stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
  1728. stat->readonly = !writeDir; /* Writeable if we have a writeDir */
  1729. retval = 0;
  1730. } /* if */
  1731. else
  1732. {
  1733. DirHandle *i;
  1734. int exists = 0;
  1735. __PHYSFS_platformGrabMutex(stateLock);
  1736. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  1737. {
  1738. char *arcfname = fname;
  1739. exists = partOfMountPoint(i, arcfname);
  1740. if (exists)
  1741. retval = 1; /* !!! FIXME: What's the right value? */
  1742. else if (verifyPath(i, &arcfname, 0))
  1743. {
  1744. stat->readonly = !(writeDir &&
  1745. (strcmp(writeDir->dirName, i->dirName) == 0));
  1746. retval = i->funcs->stat(i->opaque, arcfname, &exists, stat);
  1747. } /* else if */
  1748. } /* for */
  1749. __PHYSFS_platformReleaseMutex(stateLock);
  1750. } /* else */
  1751. } /* if */
  1752. __PHYSFS_smallFree(fname);
  1753. return retval;
  1754. } /* PHYSFS_stat */
  1755. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  1756. {
  1757. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1758. externalAllocator = (a != NULL);
  1759. if (externalAllocator)
  1760. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1761. return 1;
  1762. } /* PHYSFS_setAllocator */
  1763. const PHYSFS_Allocator *PHYSFS_getAllocator(void)
  1764. {
  1765. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, NULL);
  1766. return &allocator;
  1767. } /* PHYSFS_getAllocator */
  1768. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  1769. {
  1770. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1771. #undef malloc
  1772. return malloc((size_t) s);
  1773. } /* mallocAllocatorMalloc */
  1774. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  1775. {
  1776. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1777. #undef realloc
  1778. return realloc(ptr, (size_t) s);
  1779. } /* mallocAllocatorRealloc */
  1780. static void mallocAllocatorFree(void *ptr)
  1781. {
  1782. #undef free
  1783. free(ptr);
  1784. } /* mallocAllocatorFree */
  1785. static void setDefaultAllocator(void)
  1786. {
  1787. assert(!externalAllocator);
  1788. if (!__PHYSFS_platformSetDefaultAllocator(&allocator))
  1789. {
  1790. allocator.Init = NULL;
  1791. allocator.Deinit = NULL;
  1792. allocator.Malloc = mallocAllocatorMalloc;
  1793. allocator.Realloc = mallocAllocatorRealloc;
  1794. allocator.Free = mallocAllocatorFree;
  1795. } /* if */
  1796. } /* setDefaultAllocator */
  1797. void *__PHYSFS_initSmallAlloc(void *ptr, PHYSFS_uint64 len)
  1798. {
  1799. const char useHeap = ((ptr == NULL) ? 1 : 0);
  1800. if (useHeap) /* too large for stack allocation or alloca() failed. */
  1801. ptr = allocator.Malloc(len+1);
  1802. if (ptr != NULL)
  1803. {
  1804. char *retval = (char *) ptr;
  1805. /*printf("%s alloc'd (%d) bytes at (%p).\n",
  1806. useHeap ? "heap" : "stack", (int) len, ptr);*/
  1807. *retval = useHeap;
  1808. return (retval + 1);
  1809. } /* if */
  1810. return NULL; /* allocation failed. */
  1811. } /* __PHYSFS_initSmallAlloc */
  1812. void __PHYSFS_smallFree(void *ptr)
  1813. {
  1814. if (ptr != NULL)
  1815. {
  1816. char *block = ((char *) ptr) - 1;
  1817. const char useHeap = *block;
  1818. if (useHeap)
  1819. allocator.Free(block);
  1820. /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
  1821. } /* if */
  1822. } /* __PHYSFS_smallFree */
  1823. /* end of physfs.c ... */