physfs.c 56 KB

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