physfs.c 56 KB

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