physfs.c 55 KB

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