physfs.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  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. BAIL_IF_MACRO(!allocator.Init(), NULL, 0);
  614. BAIL_IF_MACRO(!__PHYSFS_platformInit(), NULL, 0);
  615. BAIL_IF_MACRO(!initializeMutexes(), NULL, 0);
  616. baseDir = calculateBaseDir(argv0);
  617. BAIL_IF_MACRO(baseDir == NULL, NULL, 0);
  618. ptr = __PHYSFS_platformRealPath(baseDir);
  619. allocator.Free(baseDir);
  620. BAIL_IF_MACRO(ptr == NULL, NULL, 0);
  621. baseDir = ptr;
  622. BAIL_IF_MACRO(!appendDirSep(&baseDir), NULL, 0);
  623. userDir = calculateUserDir();
  624. if (userDir != NULL)
  625. {
  626. ptr = __PHYSFS_platformRealPath(userDir);
  627. allocator.Free(userDir);
  628. userDir = ptr;
  629. } /* if */
  630. if ((userDir == NULL) || (!appendDirSep(&userDir)))
  631. {
  632. allocator.Free(baseDir);
  633. baseDir = NULL;
  634. return(0);
  635. } /* if */
  636. initialized = 1;
  637. /* This makes sure that the error subsystem is initialized. */
  638. __PHYSFS_setError(PHYSFS_getLastError());
  639. return(1);
  640. } /* PHYSFS_init */
  641. /* MAKE SURE you hold stateLock before calling this! */
  642. static int closeFileHandleList(FileHandle **list)
  643. {
  644. FileHandle *i;
  645. FileHandle *next = NULL;
  646. for (i = *list; i != NULL; i = next)
  647. {
  648. next = i->next;
  649. if (!i->funcs->fileClose(i->opaque))
  650. {
  651. *list = i;
  652. return(0);
  653. } /* if */
  654. allocator.Free(i);
  655. } /* for */
  656. *list = NULL;
  657. return(1);
  658. } /* closeFileHandleList */
  659. /* MAKE SURE you hold the stateLock before calling this! */
  660. static void freeSearchPath(void)
  661. {
  662. DirHandle *i;
  663. DirHandle *next = NULL;
  664. closeFileHandleList(&openReadList);
  665. if (searchPath != NULL)
  666. {
  667. for (i = searchPath; i != NULL; i = next)
  668. {
  669. next = i->next;
  670. freeDirHandle(i, openReadList);
  671. } /* for */
  672. searchPath = NULL;
  673. } /* if */
  674. } /* freeSearchPath */
  675. int PHYSFS_deinit(void)
  676. {
  677. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  678. BAIL_IF_MACRO(!__PHYSFS_platformDeinit(), NULL, 0);
  679. closeFileHandleList(&openWriteList);
  680. BAIL_IF_MACRO(!PHYSFS_setWriteDir(NULL), ERR_FILES_STILL_OPEN, 0);
  681. freeSearchPath();
  682. freeErrorMessages();
  683. if (baseDir != NULL)
  684. {
  685. allocator.Free(baseDir);
  686. baseDir = NULL;
  687. } /* if */
  688. if (userDir != NULL)
  689. {
  690. allocator.Free(userDir);
  691. userDir = NULL;
  692. } /* if */
  693. allowSymLinks = 0;
  694. initialized = 0;
  695. __PHYSFS_platformDestroyMutex(errorLock);
  696. __PHYSFS_platformDestroyMutex(stateLock);
  697. allocator.Deinit();
  698. errorLock = stateLock = NULL;
  699. return(1);
  700. } /* PHYSFS_deinit */
  701. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  702. {
  703. return(supported_types);
  704. } /* PHYSFS_supportedArchiveTypes */
  705. void PHYSFS_freeList(void *list)
  706. {
  707. void **i;
  708. for (i = (void **) list; *i != NULL; i++)
  709. allocator.Free(*i);
  710. allocator.Free(list);
  711. } /* PHYSFS_freeList */
  712. const char *PHYSFS_getDirSeparator(void)
  713. {
  714. return(__PHYSFS_platformDirSeparator);
  715. } /* PHYSFS_getDirSeparator */
  716. char **PHYSFS_getCdRomDirs(void)
  717. {
  718. return(doEnumStringList(__PHYSFS_platformDetectAvailableCDs));
  719. } /* PHYSFS_getCdRomDirs */
  720. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  721. {
  722. __PHYSFS_platformDetectAvailableCDs(callback, data);
  723. } /* PHYSFS_getCdRomDirsCallback */
  724. const char *PHYSFS_getBaseDir(void)
  725. {
  726. return(baseDir); /* this is calculated in PHYSFS_init()... */
  727. } /* PHYSFS_getBaseDir */
  728. const char *PHYSFS_getUserDir(void)
  729. {
  730. return(userDir); /* this is calculated in PHYSFS_init()... */
  731. } /* PHYSFS_getUserDir */
  732. const char *PHYSFS_getWriteDir(void)
  733. {
  734. const char *retval = NULL;
  735. __PHYSFS_platformGrabMutex(stateLock);
  736. if (writeDir != NULL)
  737. retval = writeDir->dirName;
  738. __PHYSFS_platformReleaseMutex(stateLock);
  739. return(retval);
  740. } /* PHYSFS_getWriteDir */
  741. int PHYSFS_setWriteDir(const char *newDir)
  742. {
  743. int retval = 1;
  744. __PHYSFS_platformGrabMutex(stateLock);
  745. if (writeDir != NULL)
  746. {
  747. BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), NULL,
  748. stateLock, 0);
  749. writeDir = NULL;
  750. } /* if */
  751. if (newDir != NULL)
  752. {
  753. writeDir = createDirHandle(newDir, NULL, 1);
  754. retval = (writeDir != NULL);
  755. } /* if */
  756. __PHYSFS_platformReleaseMutex(stateLock);
  757. return(retval);
  758. } /* PHYSFS_setWriteDir */
  759. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  760. {
  761. DirHandle *dh;
  762. DirHandle *prev = NULL;
  763. DirHandle *i;
  764. BAIL_IF_MACRO(newDir == NULL, ERR_INVALID_ARGUMENT, 0);
  765. if (mountPoint == NULL)
  766. mountPoint = "/";
  767. __PHYSFS_platformGrabMutex(stateLock);
  768. for (i = searchPath; i != NULL; i = i->next)
  769. {
  770. /* already in search path? */
  771. BAIL_IF_MACRO_MUTEX(strcmp(newDir, i->dirName)==0, NULL, stateLock, 1);
  772. prev = i;
  773. } /* for */
  774. dh = createDirHandle(newDir, mountPoint, 0);
  775. BAIL_IF_MACRO_MUTEX(dh == NULL, NULL, stateLock, 0);
  776. if (appendToPath)
  777. {
  778. if (prev == NULL)
  779. searchPath = dh;
  780. else
  781. prev->next = dh;
  782. } /* if */
  783. else
  784. {
  785. dh->next = searchPath;
  786. searchPath = dh;
  787. } /* else */
  788. __PHYSFS_platformReleaseMutex(stateLock);
  789. return(1);
  790. } /* PHYSFS_mount */
  791. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  792. {
  793. return(PHYSFS_mount(newDir, NULL, appendToPath));
  794. } /* PHYSFS_addToSearchPath */
  795. int PHYSFS_removeFromSearchPath(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_removeFromSearchPath */
  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. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  848. const char *archiveExt, int includeCdRoms,
  849. int archivesFirst)
  850. {
  851. const char *basedir = PHYSFS_getBaseDir();
  852. const char *userdir = PHYSFS_getUserDir();
  853. const char *dirsep = PHYSFS_getDirSeparator();
  854. char *str;
  855. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  856. /* set write dir... */
  857. str = (char *) allocator.Malloc(
  858. strlen(userdir) + (strlen(organization) * 2) +
  859. (strlen(appName) * 2) + (strlen(dirsep) * 3) + 2);
  860. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
  861. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  862. if (!PHYSFS_setWriteDir(str))
  863. {
  864. int no_write = 0;
  865. sprintf(str, ".%s/%s", organization, appName);
  866. if ( (PHYSFS_setWriteDir(userdir)) &&
  867. (PHYSFS_mkdir(str)) )
  868. {
  869. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  870. if (!PHYSFS_setWriteDir(str))
  871. no_write = 1;
  872. } /* if */
  873. else
  874. {
  875. no_write = 1;
  876. } /* else */
  877. if (no_write)
  878. {
  879. PHYSFS_setWriteDir(NULL); /* just in case. */
  880. allocator.Free(str);
  881. BAIL_MACRO(ERR_CANT_SET_WRITE_DIR, 0);
  882. } /* if */
  883. } /* if */
  884. /* Put write dir first in search path... */
  885. PHYSFS_addToSearchPath(str, 0);
  886. allocator.Free(str);
  887. /* Put base path on search path... */
  888. PHYSFS_addToSearchPath(basedir, 1);
  889. /* handle CD-ROMs... */
  890. if (includeCdRoms)
  891. {
  892. char **cds = PHYSFS_getCdRomDirs();
  893. char **i;
  894. for (i = cds; *i != NULL; i++)
  895. PHYSFS_addToSearchPath(*i, 1);
  896. PHYSFS_freeList(cds);
  897. } /* if */
  898. /* Root out archives, and add them to search path... */
  899. if (archiveExt != NULL)
  900. {
  901. char **rc = PHYSFS_enumerateFiles("/");
  902. char **i;
  903. size_t extlen = strlen(archiveExt);
  904. char *ext;
  905. for (i = rc; *i != NULL; i++)
  906. {
  907. size_t l = strlen(*i);
  908. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  909. {
  910. ext = (*i) + (l - extlen);
  911. if (__PHYSFS_platformStricmp(ext, archiveExt) == 0)
  912. {
  913. const char *d = PHYSFS_getRealDir(*i);
  914. size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
  915. str = (char *) allocator.Malloc(allocsize);
  916. if (str != NULL)
  917. {
  918. sprintf(str, "%s%s%s", d, dirsep, *i);
  919. PHYSFS_addToSearchPath(str, archivesFirst == 0);
  920. allocator.Free(str);
  921. } /* if */
  922. } /* if */
  923. } /* if */
  924. } /* for */
  925. PHYSFS_freeList(rc);
  926. } /* if */
  927. return(1);
  928. } /* PHYSFS_setSaneConfig */
  929. void PHYSFS_permitSymbolicLinks(int allow)
  930. {
  931. allowSymLinks = allow;
  932. } /* PHYSFS_permitSymbolicLinks */
  933. /* string manipulation in C makes my ass itch. */
  934. char *__PHYSFS_convertToDependent(const char *prepend,
  935. const char *dirName,
  936. const char *append)
  937. {
  938. const char *dirsep = __PHYSFS_platformDirSeparator;
  939. size_t sepsize = strlen(dirsep);
  940. char *str;
  941. char *i1;
  942. char *i2;
  943. size_t allocSize;
  944. while (*dirName == '/') /* !!! FIXME: pass through sanitize function. */
  945. dirName++;
  946. allocSize = strlen(dirName) + 1;
  947. if (prepend != NULL)
  948. allocSize += strlen(prepend) + sepsize;
  949. if (append != NULL)
  950. allocSize += strlen(append) + sepsize;
  951. /* make sure there's enough space if the dir separator is bigger. */
  952. if (sepsize > 1)
  953. {
  954. str = (char *) dirName;
  955. do
  956. {
  957. str = strchr(str, '/');
  958. if (str != NULL)
  959. {
  960. allocSize += (sepsize - 1);
  961. str++;
  962. } /* if */
  963. } while (str != NULL);
  964. } /* if */
  965. str = (char *) allocator.Malloc(allocSize);
  966. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, NULL);
  967. if (prepend == NULL)
  968. *str = '\0';
  969. else
  970. {
  971. strcpy(str, prepend);
  972. strcat(str, dirsep);
  973. } /* else */
  974. for (i1 = (char *) dirName, i2 = str + strlen(str); *i1; i1++, i2++)
  975. {
  976. if (*i1 == '/')
  977. {
  978. strcpy(i2, dirsep);
  979. i2 += sepsize;
  980. } /* if */
  981. else
  982. {
  983. *i2 = *i1;
  984. } /* else */
  985. } /* for */
  986. *i2 = '\0';
  987. if (append)
  988. {
  989. strcat(str, dirsep);
  990. strcat(str, append);
  991. } /* if */
  992. return(str);
  993. } /* __PHYSFS_convertToDependent */
  994. /*
  995. * Verify that (fname) (in platform-independent notation), in relation
  996. * to (h) is secure. That means that each element of fname is checked
  997. * for symlinks (if they aren't permitted). This also allows for quick
  998. * rejection of files that exist outside an archive's mountpoint.
  999. *
  1000. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  1001. * at a time), you should always pass zero for "allowMissing" for efficiency.
  1002. *
  1003. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  1004. * since it will make sure that path names are in the right format for
  1005. * passing certain checks. It will also do checks for "insecure" pathnames
  1006. * like ".." which should be done once instead of once per archive. This also
  1007. * gives us license to treat (fname) as scratch space in this function.
  1008. *
  1009. * Returns non-zero if string is safe, zero if there's a security issue.
  1010. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  1011. * updated to point past any mount point elements so it is prepared to
  1012. * be used with the archiver directly.
  1013. */
  1014. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1015. {
  1016. char *fname = *_fname;
  1017. int retval = 1;
  1018. char *start;
  1019. char *end;
  1020. if (*fname == '\0') /* quick rejection. */
  1021. return(1);
  1022. /* !!! FIXME: This codeblock sucks. */
  1023. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1024. {
  1025. size_t mntpntlen = strlen(h->mountPoint);
  1026. size_t len = strlen(fname);
  1027. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1028. /* not under the mountpoint, so skip this archive. */
  1029. BAIL_IF_MACRO(len < mntpntlen-1, ERR_NO_SUCH_PATH, 0);
  1030. /* !!! FIXME: Case insensitive? */
  1031. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1032. BAIL_IF_MACRO(retval != 0, ERR_NO_SUCH_PATH, 0);
  1033. if (len > mntpntlen-1) /* corner case... */
  1034. BAIL_IF_MACRO(fname[mntpntlen-1] != '/', ERR_NO_SUCH_PATH, 0);
  1035. fname += mntpntlen-1; /* move to start of actual archive path. */
  1036. if (*fname == '/')
  1037. fname++;
  1038. *_fname = fname; /* skip mountpoint for later use. */
  1039. retval = 1; /* may be reset, below. */
  1040. } /* if */
  1041. start = fname;
  1042. if (!allowSymLinks)
  1043. {
  1044. while (1)
  1045. {
  1046. end = strchr(start, '/');
  1047. if (end != NULL)
  1048. *end = '\0';
  1049. if (h->funcs->isSymLink(h->opaque, fname, &retval))
  1050. BAIL_MACRO(ERR_SYMLINK_DISALLOWED, 0); /* insecure. */
  1051. /* break out early if path element is missing. */
  1052. if (!retval)
  1053. {
  1054. /*
  1055. * We need to clear it if it's the last element of the path,
  1056. * since this might be a non-existant file we're opening
  1057. * for writing...
  1058. */
  1059. if ((end == NULL) || (allowMissing))
  1060. retval = 1;
  1061. break;
  1062. } /* if */
  1063. if (end == NULL)
  1064. break;
  1065. *end = '/';
  1066. start = end + 1;
  1067. } /* while */
  1068. } /* if */
  1069. return(retval);
  1070. } /* verifyPath */
  1071. int PHYSFS_mkdir(const char *_dname)
  1072. {
  1073. DirHandle *h;
  1074. char *start;
  1075. char *end;
  1076. int retval = 0;
  1077. int exists = 1; /* force existance check on first path element. */
  1078. char *dname;
  1079. dname = ((_dname) ? (char *) alloca(strlen(_dname) + 1) : NULL);
  1080. BAIL_IF_MACRO(dname == NULL, ERR_INVALID_ARGUMENT, 0);
  1081. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_dname, dname), NULL, 0);
  1082. __PHYSFS_platformGrabMutex(stateLock);
  1083. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1084. h = writeDir;
  1085. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &dname, 1), NULL, stateLock, 0);
  1086. start = dname;
  1087. while (1)
  1088. {
  1089. end = strchr(start, '/');
  1090. if (end != NULL)
  1091. *end = '\0';
  1092. /* only check for existance if all parent dirs existed, too... */
  1093. if (exists)
  1094. retval = h->funcs->isDirectory(h->opaque, dname, &exists);
  1095. if (!exists)
  1096. retval = h->funcs->mkdir(h->opaque, dname);
  1097. if (!retval)
  1098. break;
  1099. if (end == NULL)
  1100. break;
  1101. *end = '/';
  1102. start = end + 1;
  1103. } /* while */
  1104. __PHYSFS_platformReleaseMutex(stateLock);
  1105. return(retval);
  1106. } /* PHYSFS_mkdir */
  1107. int PHYSFS_delete(const char *_fname)
  1108. {
  1109. int retval;
  1110. DirHandle *h;
  1111. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1112. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1113. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1114. __PHYSFS_platformGrabMutex(stateLock);
  1115. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1116. h = writeDir;
  1117. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, 0);
  1118. retval = h->funcs->remove(h->opaque, fname);
  1119. __PHYSFS_platformReleaseMutex(stateLock);
  1120. return(retval);
  1121. } /* PHYSFS_delete */
  1122. const char *PHYSFS_getRealDir(const char *_fname)
  1123. {
  1124. DirHandle *i;
  1125. const char *retval = NULL;
  1126. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1127. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1128. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, NULL);
  1129. __PHYSFS_platformGrabMutex(stateLock);
  1130. for (i = searchPath; ((i != NULL) && (retval == NULL)); i = i->next)
  1131. {
  1132. char *arcfname = fname;
  1133. if (partOfMountPoint(i, arcfname))
  1134. retval = i->dirName;
  1135. else if (verifyPath(i, &arcfname, 0))
  1136. {
  1137. if (i->funcs->exists(i->opaque, arcfname))
  1138. retval = i->dirName;
  1139. } /* if */
  1140. } /* for */
  1141. __PHYSFS_platformReleaseMutex(stateLock);
  1142. return(retval);
  1143. } /* PHYSFS_getRealDir */
  1144. static int locateInStringList(const char *str,
  1145. char **list,
  1146. PHYSFS_uint32 *pos)
  1147. {
  1148. PHYSFS_uint32 hi = *pos - 1;
  1149. PHYSFS_uint32 lo = 0;
  1150. PHYSFS_uint32 i = hi >> 1;
  1151. int cmp;
  1152. assert(*pos != 0); /* this doesn't work with empty lists! */
  1153. while (hi != lo)
  1154. {
  1155. cmp = strcmp(list[i], str);
  1156. if (cmp == 0) /* it's in the list already. */
  1157. return(1);
  1158. else if (cmp < 0)
  1159. {
  1160. hi = i;
  1161. i = lo + ((hi - lo) >> 1);
  1162. } /* else if */
  1163. else
  1164. {
  1165. lo = i + 1;
  1166. i = lo + ((1 + hi - lo) >> 1);
  1167. } /* else */
  1168. } /* while */
  1169. /* hi == lo, check it in case it's the match... */
  1170. cmp = strcmp(list[lo], str);
  1171. if (cmp == 0)
  1172. return(1);
  1173. /* not in the list, set insertion point... */
  1174. *pos = (cmp < 0) ? lo : lo + 1;
  1175. return(0);
  1176. } /* locateInStringList */
  1177. static void enumFilesCallback(void *data, const char *str)
  1178. {
  1179. PHYSFS_uint32 pos;
  1180. void *ptr;
  1181. char *newstr;
  1182. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1183. /*
  1184. * See if file is in the list already, and if not, insert it in there
  1185. * alphabetically...
  1186. */
  1187. pos = pecd->size;
  1188. if (pos > 0)
  1189. {
  1190. if (locateInStringList(str, pecd->list, &pos))
  1191. return; /* already in the list. */
  1192. } /* if */
  1193. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1194. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1195. if (ptr != NULL)
  1196. pecd->list = (char **) ptr;
  1197. if ((ptr == NULL) || (newstr == NULL))
  1198. return; /* better luck next time. */
  1199. strcpy(newstr, str);
  1200. if (pos != pecd->size)
  1201. {
  1202. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1203. sizeof (char *) * ((pecd->size) - pos));
  1204. } /* if */
  1205. pecd->list[pos] = newstr;
  1206. pecd->size++;
  1207. } /* enumFilesCallback */
  1208. char **PHYSFS_enumerateFiles(const char *path)
  1209. {
  1210. EnumStringListCallbackData ecd;
  1211. memset(&ecd, '\0', sizeof (ecd));
  1212. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1213. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  1214. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1215. ecd.list[ecd.size] = NULL;
  1216. return(ecd.list);
  1217. } /* PHYSFS_enumerateFiles */
  1218. void PHYSFS_enumerateFilesCallback(const char *_fname,
  1219. PHYSFS_StringCallback callback,
  1220. void *data)
  1221. {
  1222. DirHandle *i;
  1223. int noSyms;
  1224. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1225. if ((fname == NULL) || (callback == NULL))
  1226. return; /* oh well. */
  1227. if (!sanitizePlatformIndependentPath(_fname, fname))
  1228. return;
  1229. __PHYSFS_platformGrabMutex(stateLock);
  1230. noSyms = !allowSymLinks;
  1231. for (i = searchPath; i != NULL; i = i->next)
  1232. {
  1233. char *arcfname = fname;
  1234. if (partOfMountPoint(i, arcfname))
  1235. {
  1236. size_t len = strlen(arcfname);
  1237. char *ptr = i->mountPoint + ((len) ? len + 1 : 0);
  1238. char *end = strchr(ptr, '/');
  1239. assert(end); /* should always find a terminating '/'. */
  1240. *end = '\0'; /* !!! FIXME: not safe in a callback... */
  1241. callback(data, ptr);
  1242. *end = '/'; /* !!! FIXME: not safe in a callback... */
  1243. } /* if */
  1244. else if (verifyPath(i, &arcfname, 0))
  1245. {
  1246. i->funcs->enumerateFiles(i->opaque,arcfname,noSyms,callback,data);
  1247. } /* else if */
  1248. } /* for */
  1249. __PHYSFS_platformReleaseMutex(stateLock);
  1250. } /* PHYSFS_enumerateFilesCallback */
  1251. int PHYSFS_exists(const char *fname)
  1252. {
  1253. return(PHYSFS_getRealDir(fname) != NULL);
  1254. } /* PHYSFS_exists */
  1255. PHYSFS_sint64 PHYSFS_getLastModTime(const char *_fname)
  1256. {
  1257. DirHandle *i;
  1258. PHYSFS_sint64 retval = -1;
  1259. int fileExists = 0;
  1260. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1261. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1262. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1263. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1264. return(1); /* !!! FIXME: Maybe this should be an error? */
  1265. __PHYSFS_platformGrabMutex(stateLock);
  1266. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1267. {
  1268. char *arcfname = fname;
  1269. fileExists = partOfMountPoint(i, arcfname);
  1270. if (fileExists)
  1271. retval = 1; /* !!! FIXME: What's the right value? */
  1272. else if (verifyPath(i, &arcfname, 0))
  1273. retval = i->funcs->getLastModTime(i->opaque,arcfname,&fileExists);
  1274. } /* for */
  1275. __PHYSFS_platformReleaseMutex(stateLock);
  1276. return(retval);
  1277. } /* PHYSFS_getLastModTime */
  1278. int PHYSFS_isDirectory(const char *_fname)
  1279. {
  1280. DirHandle *i;
  1281. int retval = 0;
  1282. int fileExists = 0;
  1283. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1284. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1285. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1286. BAIL_IF_MACRO(*fname == '\0', NULL, 1); /* Root is always a dir. :) */
  1287. __PHYSFS_platformGrabMutex(stateLock);
  1288. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1289. {
  1290. char *arcfname = fname;
  1291. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1292. retval = 1;
  1293. else if (verifyPath(i, &arcfname, 0))
  1294. retval = i->funcs->isDirectory(i->opaque, arcfname, &fileExists);
  1295. } /* for */
  1296. __PHYSFS_platformReleaseMutex(stateLock);
  1297. return(retval);
  1298. } /* PHYSFS_isDirectory */
  1299. int PHYSFS_isSymbolicLink(const char *_fname)
  1300. {
  1301. DirHandle *i;
  1302. int retval = 0;
  1303. int fileExists = 0;
  1304. char *fname;
  1305. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1306. fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1307. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1308. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1309. BAIL_IF_MACRO(*fname == '\0', NULL, 0); /* Root is never a symlink */
  1310. __PHYSFS_platformGrabMutex(stateLock);
  1311. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1312. {
  1313. char *arcfname = fname;
  1314. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1315. retval = 0; /* virtual dir...not a symlink. */
  1316. else if (verifyPath(i, &arcfname, 0))
  1317. retval = i->funcs->isSymLink(i->opaque, arcfname, &fileExists);
  1318. } /* for */
  1319. __PHYSFS_platformReleaseMutex(stateLock);
  1320. return(retval);
  1321. } /* PHYSFS_isSymbolicLink */
  1322. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1323. {
  1324. void *opaque = NULL;
  1325. FileHandle *fh = NULL;
  1326. DirHandle *h = NULL;
  1327. const PHYSFS_Archiver *f;
  1328. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1329. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1330. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1331. __PHYSFS_platformGrabMutex(stateLock);
  1332. BAIL_IF_MACRO_MUTEX(!writeDir, ERR_NO_WRITE_DIR, stateLock, NULL);
  1333. h = writeDir;
  1334. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, NULL);
  1335. f = h->funcs;
  1336. if (appending)
  1337. opaque = f->openAppend(h->opaque, fname);
  1338. else
  1339. opaque = f->openWrite(h->opaque, fname);
  1340. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1341. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1342. if (fh == NULL)
  1343. {
  1344. f->fileClose(opaque);
  1345. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1346. } /* if */
  1347. else
  1348. {
  1349. memset(fh, '\0', sizeof (FileHandle));
  1350. fh->opaque = opaque;
  1351. fh->dirHandle = h;
  1352. fh->funcs = h->funcs;
  1353. fh->next = openWriteList;
  1354. openWriteList = fh;
  1355. } /* else */
  1356. __PHYSFS_platformReleaseMutex(stateLock);
  1357. return((PHYSFS_File *) fh);
  1358. } /* doOpenWrite */
  1359. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1360. {
  1361. return(doOpenWrite(filename, 0));
  1362. } /* PHYSFS_openWrite */
  1363. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1364. {
  1365. return(doOpenWrite(filename, 1));
  1366. } /* PHYSFS_openAppend */
  1367. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  1368. {
  1369. FileHandle *fh = NULL;
  1370. int fileExists = 0;
  1371. DirHandle *i = NULL;
  1372. fvoid *opaque = NULL;
  1373. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1374. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1375. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1376. __PHYSFS_platformGrabMutex(stateLock);
  1377. BAIL_IF_MACRO_MUTEX(!searchPath, ERR_NO_SUCH_PATH, stateLock, NULL);
  1378. /* !!! FIXME: Why aren't we using a for loop here? */
  1379. i = searchPath;
  1380. do
  1381. {
  1382. char *arcfname = fname;
  1383. if (verifyPath(i, &arcfname, 0))
  1384. {
  1385. opaque = i->funcs->openRead(i->opaque, arcfname, &fileExists);
  1386. if (opaque)
  1387. break;
  1388. } /* if */
  1389. i = i->next;
  1390. } while ((i != NULL) && (!fileExists));
  1391. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1392. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1393. if (fh == NULL)
  1394. {
  1395. i->funcs->fileClose(opaque);
  1396. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1397. } /* if */
  1398. memset(fh, '\0', sizeof (FileHandle));
  1399. fh->opaque = opaque;
  1400. fh->forReading = 1;
  1401. fh->dirHandle = i;
  1402. fh->funcs = i->funcs;
  1403. fh->next = openReadList;
  1404. openReadList = fh;
  1405. __PHYSFS_platformReleaseMutex(stateLock);
  1406. return((PHYSFS_File *) fh);
  1407. } /* PHYSFS_openRead */
  1408. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1409. {
  1410. FileHandle *prev = NULL;
  1411. FileHandle *i;
  1412. int rc = 1;
  1413. for (i = *list; i != NULL; i = i->next)
  1414. {
  1415. if (i == handle) /* handle is in this list? */
  1416. {
  1417. PHYSFS_uint8 *tmp = handle->buffer;
  1418. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1419. if (rc)
  1420. rc = handle->funcs->fileClose(handle->opaque);
  1421. if (!rc)
  1422. return(-1);
  1423. if (tmp != NULL) /* free any associated buffer. */
  1424. allocator.Free(tmp);
  1425. if (prev == NULL)
  1426. *list = handle->next;
  1427. else
  1428. prev->next = handle->next;
  1429. allocator.Free(handle);
  1430. return(1);
  1431. } /* if */
  1432. prev = i;
  1433. } /* for */
  1434. return(0);
  1435. } /* closeHandleInOpenList */
  1436. int PHYSFS_close(PHYSFS_File *_handle)
  1437. {
  1438. FileHandle *handle = (FileHandle *) _handle;
  1439. int rc;
  1440. __PHYSFS_platformGrabMutex(stateLock);
  1441. /* -1 == close failure. 0 == not found. 1 == success. */
  1442. rc = closeHandleInOpenList(&openReadList, handle);
  1443. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1444. if (!rc)
  1445. {
  1446. rc = closeHandleInOpenList(&openWriteList, handle);
  1447. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1448. } /* if */
  1449. __PHYSFS_platformReleaseMutex(stateLock);
  1450. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1451. return(1);
  1452. } /* PHYSFS_close */
  1453. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1454. PHYSFS_uint32 objSize,
  1455. PHYSFS_uint32 objCount)
  1456. {
  1457. PHYSFS_sint64 retval = 0;
  1458. PHYSFS_uint32 remainder = 0;
  1459. while (objCount > 0)
  1460. {
  1461. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1462. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1463. PHYSFS_uint32 copied;
  1464. if (buffered == 0) /* need to refill buffer? */
  1465. {
  1466. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1467. 1, fh->bufsize);
  1468. if (rc <= 0)
  1469. {
  1470. fh->bufpos -= remainder;
  1471. return(((rc == -1) && (retval == 0)) ? -1 : retval);
  1472. } /* if */
  1473. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1474. fh->bufpos = 0;
  1475. } /* if */
  1476. if (buffered > mustread)
  1477. buffered = (PHYSFS_uint32) mustread;
  1478. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1479. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1480. fh->bufpos += buffered;
  1481. buffered += remainder; /* take remainder into account. */
  1482. copied = (buffered / objSize);
  1483. remainder = (buffered % objSize);
  1484. retval += copied;
  1485. objCount -= copied;
  1486. } /* while */
  1487. return(retval);
  1488. } /* doBufferedRead */
  1489. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1490. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1491. {
  1492. FileHandle *fh = (FileHandle *) handle;
  1493. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1494. if (fh->buffer != NULL)
  1495. return(doBufferedRead(fh, buffer, objSize, objCount));
  1496. return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
  1497. } /* PHYSFS_read */
  1498. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1499. PHYSFS_uint32 objSize,
  1500. PHYSFS_uint32 objCount)
  1501. {
  1502. FileHandle *fh = (FileHandle *) handle;
  1503. /* whole thing fits in the buffer? */
  1504. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1505. {
  1506. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1507. fh->buffill += (objSize * objCount);
  1508. return(objCount);
  1509. } /* if */
  1510. /* would overflow buffer. Flush and then write the new objects, too. */
  1511. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1512. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1513. } /* doBufferedWrite */
  1514. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1515. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1516. {
  1517. FileHandle *fh = (FileHandle *) handle;
  1518. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1519. if (fh->buffer != NULL)
  1520. return(doBufferedWrite(handle, buffer, objSize, objCount));
  1521. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1522. } /* PHYSFS_write */
  1523. int PHYSFS_eof(PHYSFS_File *handle)
  1524. {
  1525. FileHandle *fh = (FileHandle *) handle;
  1526. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1527. return(0);
  1528. /* eof if buffer is empty and archiver says so. */
  1529. return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
  1530. } /* PHYSFS_eof */
  1531. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1532. {
  1533. FileHandle *fh = (FileHandle *) handle;
  1534. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1535. PHYSFS_sint64 retval = fh->forReading ?
  1536. (pos - fh->buffill) + fh->bufpos :
  1537. (pos + fh->buffill);
  1538. return(retval);
  1539. } /* PHYSFS_tell */
  1540. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1541. {
  1542. FileHandle *fh = (FileHandle *) handle;
  1543. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1544. if (fh->buffer && fh->forReading)
  1545. {
  1546. /* avoid throwing away our precious buffer if seeking within it. */
  1547. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1548. if ( /* seeking within the already-buffered range? */
  1549. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1550. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1551. {
  1552. fh->bufpos += (PHYSFS_uint32) offset;
  1553. return(1); /* successful seek */
  1554. } /* if */
  1555. } /* if */
  1556. /* we have to fall back to a 'raw' seek. */
  1557. fh->buffill = fh->bufpos = 0;
  1558. return(fh->funcs->seek(fh->opaque, pos));
  1559. } /* PHYSFS_seek */
  1560. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1561. {
  1562. FileHandle *fh = (FileHandle *) handle;
  1563. return(fh->funcs->fileLength(fh->opaque));
  1564. } /* PHYSFS_filelength */
  1565. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1566. {
  1567. FileHandle *fh = (FileHandle *) handle;
  1568. PHYSFS_uint32 bufsize;
  1569. /* !!! FIXME: Unlocalized string. */
  1570. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1571. bufsize = (PHYSFS_uint32) _bufsize;
  1572. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1573. /*
  1574. * For reads, we need to move the file pointer to where it would be
  1575. * if we weren't buffering, so that the next read will get the
  1576. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1577. */
  1578. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1579. {
  1580. PHYSFS_uint64 pos;
  1581. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1582. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1583. pos = ((curpos - fh->buffill) + fh->bufpos);
  1584. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1585. } /* if */
  1586. if (bufsize == 0) /* delete existing buffer. */
  1587. {
  1588. if (fh->buffer != NULL)
  1589. {
  1590. allocator.Free(fh->buffer);
  1591. fh->buffer = NULL;
  1592. } /* if */
  1593. } /* if */
  1594. else
  1595. {
  1596. PHYSFS_uint8 *newbuf;
  1597. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  1598. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1599. fh->buffer = newbuf;
  1600. } /* else */
  1601. fh->bufsize = bufsize;
  1602. fh->buffill = fh->bufpos = 0;
  1603. return(1);
  1604. } /* PHYSFS_setBuffer */
  1605. int PHYSFS_flush(PHYSFS_File *handle)
  1606. {
  1607. FileHandle *fh = (FileHandle *) handle;
  1608. PHYSFS_sint64 rc;
  1609. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1610. return(1); /* open for read or buffer empty are successful no-ops. */
  1611. /* dump buffer to disk. */
  1612. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1613. fh->buffill - fh->bufpos, 1);
  1614. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1615. fh->bufpos = fh->buffill = 0;
  1616. return(1);
  1617. } /* PHYSFS_flush */
  1618. int PHYSFS_setAllocator(PHYSFS_Allocator *a)
  1619. {
  1620. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1621. externalAllocator = (a != NULL);
  1622. if (externalAllocator)
  1623. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1624. return(1);
  1625. } /* PHYSFS_setAllocator */
  1626. static void setDefaultAllocator(void)
  1627. {
  1628. assert(!externalAllocator);
  1629. allocator.Init = __PHYSFS_platformAllocatorInit;
  1630. allocator.Deinit = __PHYSFS_platformAllocatorDeinit;
  1631. allocator.Malloc = __PHYSFS_platformAllocatorMalloc;
  1632. allocator.Realloc = __PHYSFS_platformAllocatorRealloc;
  1633. allocator.Free = __PHYSFS_platformAllocatorFree;
  1634. } /* setDefaultAllocator */
  1635. /* end of physfs.c ... */