physfs.c 56 KB

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