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