physfs.c 63 KB

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