physfs.c 56 KB

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