physfs.c 56 KB

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