physfs.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043
  1. /**
  2. * PhysicsFS; a portable, flexible file i/o abstraction.
  3. *
  4. * Documentation is in physfs.h. It's verbose, honest. :)
  5. *
  6. * Please see the file LICENSE.txt in the source's root directory.
  7. *
  8. * This file written by Ryan C. Gordon.
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include "physfs.h"
  14. #define __PHYSICSFS_INTERNAL__
  15. #include "physfs_internal.h"
  16. typedef struct __PHYSFS_DIRHANDLE__
  17. {
  18. void *opaque; /* Instance data unique to the archiver. */
  19. char *dirName; /* Path to archive in platform-dependent notation. */
  20. char *mountPoint; /* Mountpoint in virtual file tree. */
  21. const PHYSFS_Archiver *funcs; /* Ptr to archiver info for this handle. */
  22. struct __PHYSFS_DIRHANDLE__ *next; /* linked list stuff. */
  23. } DirHandle;
  24. typedef struct __PHYSFS_FILEHANDLE__
  25. {
  26. void *opaque; /* Instance data unique to the archiver for this file. */
  27. PHYSFS_uint8 forReading; /* Non-zero if reading, zero if write/append */
  28. const DirHandle *dirHandle; /* Archiver instance that created this */
  29. const PHYSFS_Archiver *funcs; /* Ptr to archiver info for this handle. */
  30. PHYSFS_uint8 *buffer; /* Buffer, if set (NULL otherwise). Don't touch! */
  31. PHYSFS_uint32 bufsize; /* Bufsize, if set (0 otherwise). Don't touch! */
  32. PHYSFS_uint32 buffill; /* Buffer fill size. Don't touch! */
  33. PHYSFS_uint32 bufpos; /* Buffer position. Don't touch! */
  34. struct __PHYSFS_FILEHANDLE__ *next; /* linked list stuff. */
  35. } FileHandle;
  36. typedef struct __PHYSFS_ERRMSGTYPE__
  37. {
  38. PHYSFS_uint64 tid;
  39. int errorAvailable;
  40. char errorString[80];
  41. struct __PHYSFS_ERRMSGTYPE__ *next;
  42. } ErrMsg;
  43. /* The various i/o drivers...some of these may not be compiled in. */
  44. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_ZIP;
  45. extern const PHYSFS_Archiver __PHYSFS_Archiver_ZIP;
  46. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_LZMA;
  47. extern const PHYSFS_Archiver __PHYSFS_Archiver_LZMA;
  48. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_GRP;
  49. extern const PHYSFS_Archiver __PHYSFS_Archiver_GRP;
  50. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_QPAK;
  51. extern const PHYSFS_Archiver __PHYSFS_Archiver_QPAK;
  52. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_HOG;
  53. extern const PHYSFS_Archiver __PHYSFS_Archiver_HOG;
  54. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_MVL;
  55. extern const PHYSFS_Archiver __PHYSFS_Archiver_MVL;
  56. extern const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_WAD;
  57. extern const PHYSFS_Archiver __PHYSFS_Archiver_WAD;
  58. extern const PHYSFS_Archiver __PHYSFS_Archiver_DIR;
  59. static const PHYSFS_ArchiveInfo *supported_types[] =
  60. {
  61. #if (defined PHYSFS_SUPPORTS_ZIP)
  62. &__PHYSFS_ArchiveInfo_ZIP,
  63. #endif
  64. #if (defined PHYSFS_SUPPORTS_7Z)
  65. &__PHYSFS_ArchiveInfo_LZMA,
  66. #endif
  67. #if (defined PHYSFS_SUPPORTS_GRP)
  68. &__PHYSFS_ArchiveInfo_GRP,
  69. #endif
  70. #if (defined PHYSFS_SUPPORTS_QPAK)
  71. &__PHYSFS_ArchiveInfo_QPAK,
  72. #endif
  73. #if (defined PHYSFS_SUPPORTS_HOG)
  74. &__PHYSFS_ArchiveInfo_HOG,
  75. #endif
  76. #if (defined PHYSFS_SUPPORTS_MVL)
  77. &__PHYSFS_ArchiveInfo_MVL,
  78. #endif
  79. #if (defined PHYSFS_SUPPORTS_WAD)
  80. &__PHYSFS_ArchiveInfo_WAD,
  81. #endif
  82. NULL
  83. };
  84. static const PHYSFS_Archiver *archivers[] =
  85. {
  86. #if (defined PHYSFS_SUPPORTS_ZIP)
  87. &__PHYSFS_Archiver_ZIP,
  88. #endif
  89. #if (defined PHYSFS_SUPPORTS_7Z)
  90. &__PHYSFS_Archiver_LZMA,
  91. #endif
  92. #if (defined PHYSFS_SUPPORTS_GRP)
  93. &__PHYSFS_Archiver_GRP,
  94. #endif
  95. #if (defined PHYSFS_SUPPORTS_QPAK)
  96. &__PHYSFS_Archiver_QPAK,
  97. #endif
  98. #if (defined PHYSFS_SUPPORTS_HOG)
  99. &__PHYSFS_Archiver_HOG,
  100. #endif
  101. #if (defined PHYSFS_SUPPORTS_MVL)
  102. &__PHYSFS_Archiver_MVL,
  103. #endif
  104. #if (defined PHYSFS_SUPPORTS_WAD)
  105. &__PHYSFS_Archiver_WAD,
  106. #endif
  107. &__PHYSFS_Archiver_DIR,
  108. NULL
  109. };
  110. /* General PhysicsFS state ... */
  111. static int initialized = 0;
  112. static ErrMsg *errorMessages = NULL;
  113. static DirHandle *searchPath = NULL;
  114. static DirHandle *writeDir = NULL;
  115. static FileHandle *openWriteList = NULL;
  116. static FileHandle *openReadList = NULL;
  117. static char *baseDir = NULL;
  118. static char *userDir = NULL;
  119. static int allowSymLinks = 0;
  120. /* mutexes ... */
  121. static void *errorLock = NULL; /* protects error message list. */
  122. static void *stateLock = NULL; /* protects other PhysFS static state. */
  123. /* allocator ... */
  124. static int externalAllocator = 0;
  125. PHYSFS_Allocator allocator;
  126. /* functions ... */
  127. typedef struct
  128. {
  129. char **list;
  130. PHYSFS_uint32 size;
  131. const char *errorstr;
  132. } EnumStringListCallbackData;
  133. static void enumStringListCallback(void *data, const char *str)
  134. {
  135. void *ptr;
  136. char *newstr;
  137. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  138. if (pecd->errorstr)
  139. return;
  140. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  141. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  142. if (ptr != NULL)
  143. pecd->list = (char **) ptr;
  144. if ((ptr == NULL) || (newstr == NULL))
  145. {
  146. pecd->errorstr = ERR_OUT_OF_MEMORY;
  147. pecd->list[pecd->size] = NULL;
  148. PHYSFS_freeList(pecd->list);
  149. return;
  150. } /* if */
  151. strcpy(newstr, str);
  152. pecd->list[pecd->size] = newstr;
  153. pecd->size++;
  154. } /* enumStringListCallback */
  155. static char **doEnumStringList(void (*func)(PHYSFS_StringCallback, void *))
  156. {
  157. EnumStringListCallbackData ecd;
  158. memset(&ecd, '\0', sizeof (ecd));
  159. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  160. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  161. func(enumStringListCallback, &ecd);
  162. BAIL_IF_MACRO(ecd.errorstr != NULL, ecd.errorstr, NULL);
  163. ecd.list[ecd.size] = NULL;
  164. return(ecd.list);
  165. } /* doEnumStringList */
  166. static void __PHYSFS_bubble_sort(void *a, PHYSFS_uint32 lo, PHYSFS_uint32 hi,
  167. int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
  168. void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
  169. {
  170. PHYSFS_uint32 i;
  171. int sorted;
  172. do
  173. {
  174. sorted = 1;
  175. for (i = lo; i < hi; i++)
  176. {
  177. if (cmpfn(a, i, i + 1) > 0)
  178. {
  179. swapfn(a, i, i + 1);
  180. sorted = 0;
  181. } /* if */
  182. } /* for */
  183. } while (!sorted);
  184. } /* __PHYSFS_bubble_sort */
  185. static void __PHYSFS_quick_sort(void *a, PHYSFS_uint32 lo, PHYSFS_uint32 hi,
  186. int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
  187. void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
  188. {
  189. PHYSFS_uint32 i;
  190. PHYSFS_uint32 j;
  191. PHYSFS_uint32 v;
  192. if ((hi - lo) <= PHYSFS_QUICKSORT_THRESHOLD)
  193. __PHYSFS_bubble_sort(a, lo, hi, cmpfn, swapfn);
  194. else
  195. {
  196. i = (hi + lo) / 2;
  197. if (cmpfn(a, lo, i) > 0) swapfn(a, lo, i);
  198. if (cmpfn(a, lo, hi) > 0) swapfn(a, lo, hi);
  199. if (cmpfn(a, i, hi) > 0) swapfn(a, i, hi);
  200. j = hi - 1;
  201. swapfn(a, i, j);
  202. i = lo;
  203. v = j;
  204. while (1)
  205. {
  206. while(cmpfn(a, ++i, v) < 0) { /* do nothing */ }
  207. while(cmpfn(a, --j, v) > 0) { /* do nothing */ }
  208. if (j < i)
  209. break;
  210. swapfn(a, i, j);
  211. } /* while */
  212. swapfn(a, i, hi-1);
  213. __PHYSFS_quick_sort(a, lo, j, cmpfn, swapfn);
  214. __PHYSFS_quick_sort(a, i+1, hi, cmpfn, swapfn);
  215. } /* else */
  216. } /* __PHYSFS_quick_sort */
  217. void __PHYSFS_sort(void *entries, PHYSFS_uint32 max,
  218. int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
  219. void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
  220. {
  221. /*
  222. * Quicksort w/ Bubblesort fallback algorithm inspired by code from here:
  223. * http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
  224. */
  225. __PHYSFS_quick_sort(entries, 0, max - 1, cmpfn, swapfn);
  226. } /* __PHYSFS_sort */
  227. static ErrMsg *findErrorForCurrentThread(void)
  228. {
  229. ErrMsg *i;
  230. PHYSFS_uint64 tid;
  231. if (errorLock != NULL)
  232. __PHYSFS_platformGrabMutex(errorLock);
  233. if (errorMessages != NULL)
  234. {
  235. tid = __PHYSFS_platformGetThreadID();
  236. for (i = errorMessages; i != NULL; i = i->next)
  237. {
  238. if (i->tid == tid)
  239. {
  240. if (errorLock != NULL)
  241. __PHYSFS_platformReleaseMutex(errorLock);
  242. return(i);
  243. } /* if */
  244. } /* for */
  245. } /* if */
  246. if (errorLock != NULL)
  247. __PHYSFS_platformReleaseMutex(errorLock);
  248. return(NULL); /* no error available. */
  249. } /* findErrorForCurrentThread */
  250. void __PHYSFS_setError(const char *str)
  251. {
  252. ErrMsg *err;
  253. if (str == NULL)
  254. return;
  255. err = findErrorForCurrentThread();
  256. if (err == NULL)
  257. {
  258. err = (ErrMsg *) allocator.Malloc(sizeof (ErrMsg));
  259. if (err == NULL)
  260. return; /* uhh...? */
  261. memset((void *) err, '\0', sizeof (ErrMsg));
  262. err->tid = __PHYSFS_platformGetThreadID();
  263. if (errorLock != NULL)
  264. __PHYSFS_platformGrabMutex(errorLock);
  265. err->next = errorMessages;
  266. errorMessages = err;
  267. if (errorLock != NULL)
  268. __PHYSFS_platformReleaseMutex(errorLock);
  269. } /* if */
  270. err->errorAvailable = 1;
  271. strncpy(err->errorString, str, sizeof (err->errorString));
  272. err->errorString[sizeof (err->errorString) - 1] = '\0';
  273. } /* __PHYSFS_setError */
  274. const char *PHYSFS_getLastError(void)
  275. {
  276. ErrMsg *err = findErrorForCurrentThread();
  277. if ((err == NULL) || (!err->errorAvailable))
  278. return(NULL);
  279. err->errorAvailable = 0;
  280. return(err->errorString);
  281. } /* PHYSFS_getLastError */
  282. /* MAKE SURE that errorLock is held before calling this! */
  283. static void freeErrorMessages(void)
  284. {
  285. ErrMsg *i;
  286. ErrMsg *next;
  287. for (i = errorMessages; i != NULL; i = next)
  288. {
  289. next = i->next;
  290. allocator.Free(i);
  291. } /* for */
  292. errorMessages = NULL;
  293. } /* freeErrorMessages */
  294. void PHYSFS_getLinkedVersion(PHYSFS_Version *ver)
  295. {
  296. if (ver != NULL)
  297. {
  298. ver->major = PHYSFS_VER_MAJOR;
  299. ver->minor = PHYSFS_VER_MINOR;
  300. ver->patch = PHYSFS_VER_PATCH;
  301. } /* if */
  302. } /* PHYSFS_getLinkedVersion */
  303. static const char *find_filename_extension(const char *fname)
  304. {
  305. const char *retval = strchr(fname, '.');
  306. const char *p = retval;
  307. while (p != NULL)
  308. {
  309. p = strchr(p + 1, '.');
  310. if (p != NULL)
  311. retval = p;
  312. } /* while */
  313. if (retval != NULL)
  314. retval++; /* skip '.' */
  315. return(retval);
  316. } /* find_filename_extension */
  317. static DirHandle *tryOpenDir(const PHYSFS_Archiver *funcs,
  318. const char *d, int forWriting)
  319. {
  320. DirHandle *retval = NULL;
  321. if (funcs->isArchive(d, forWriting))
  322. {
  323. void *opaque = funcs->openArchive(d, forWriting);
  324. if (opaque != NULL)
  325. {
  326. retval = (DirHandle *) allocator.Malloc(sizeof (DirHandle));
  327. if (retval == NULL)
  328. funcs->dirClose(opaque);
  329. else
  330. {
  331. memset(retval, '\0', sizeof (DirHandle));
  332. retval->mountPoint = NULL;
  333. retval->funcs = funcs;
  334. retval->opaque = opaque;
  335. } /* else */
  336. } /* if */
  337. } /* if */
  338. return(retval);
  339. } /* tryOpenDir */
  340. static DirHandle *openDirectory(const char *d, int forWriting)
  341. {
  342. DirHandle *retval = NULL;
  343. const PHYSFS_Archiver **i;
  344. const char *ext;
  345. BAIL_IF_MACRO(!__PHYSFS_platformExists(d), ERR_NO_SUCH_FILE, NULL);
  346. ext = find_filename_extension(d);
  347. if (ext != NULL)
  348. {
  349. /* Look for archivers with matching file extensions first... */
  350. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  351. {
  352. if (__PHYSFS_stricmpASCII(ext, (*i)->info->extension) == 0)
  353. retval = tryOpenDir(*i, d, forWriting);
  354. } /* for */
  355. /* failing an exact file extension match, try all the others... */
  356. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  357. {
  358. if (__PHYSFS_stricmpASCII(ext, (*i)->info->extension) != 0)
  359. retval = tryOpenDir(*i, d, forWriting);
  360. } /* for */
  361. } /* if */
  362. else /* no extension? Try them all. */
  363. {
  364. for (i = archivers; (*i != NULL) && (retval == NULL); i++)
  365. retval = tryOpenDir(*i, d, forWriting);
  366. } /* else */
  367. BAIL_IF_MACRO(retval == NULL, ERR_UNSUPPORTED_ARCHIVE, NULL);
  368. return(retval);
  369. } /* openDirectory */
  370. /*
  371. * Make a platform-independent path string sane. Doesn't actually check the
  372. * file hierarchy, it just cleans up the string.
  373. * (dst) must be a buffer at least as big as (src), as this is where the
  374. * cleaned up string is deposited.
  375. * If there are illegal bits in the path (".." entries, etc) then we
  376. * return zero and (dst) is undefined. Non-zero if the path was sanitized.
  377. */
  378. static int sanitizePlatformIndependentPath(const char *src, char *dst)
  379. {
  380. char *prev;
  381. char ch;
  382. while (*src == '/') /* skip initial '/' chars... */
  383. src++;
  384. prev = dst;
  385. do
  386. {
  387. ch = *(src++);
  388. if ((ch == ':') || (ch == '\\')) /* illegal chars in a physfs path. */
  389. BAIL_MACRO(ERR_INSECURE_FNAME, 0);
  390. if (ch == '/') /* path separator. */
  391. {
  392. *dst = '\0'; /* "." and ".." are illegal pathnames. */
  393. if ((strcmp(prev, ".") == 0) || (strcmp(prev, "..") == 0))
  394. BAIL_MACRO(ERR_INSECURE_FNAME, 0);
  395. while (*src == '/') /* chop out doubles... */
  396. src++;
  397. if (*src == '\0') /* ends with a pathsep? */
  398. break; /* we're done, don't add final pathsep to dst. */
  399. prev = dst + 1;
  400. } /* if */
  401. *(dst++) = ch;
  402. } while (ch != '\0');
  403. return(1);
  404. } /* sanitizePlatformIndependentPath */
  405. /*
  406. * Figure out if (fname) is part of (h)'s mountpoint. (fname) must be an
  407. * output from sanitizePlatformIndependentPath(), so that it is in a known
  408. * state.
  409. *
  410. * This only finds legitimate segments of a mountpoint. If the mountpoint is
  411. * "/a/b/c" and (fname) is "/a/b/c", "/", or "/a/b/c/d", then the results are
  412. * all zero. "/a/b" will succeed, though.
  413. */
  414. static int partOfMountPoint(DirHandle *h, char *fname)
  415. {
  416. /* !!! FIXME: This code feels gross. */
  417. int rc;
  418. size_t len, mntpntlen;
  419. if (h->mountPoint == NULL)
  420. return(0);
  421. else if (*fname == '\0')
  422. return(1);
  423. len = strlen(fname);
  424. mntpntlen = strlen(h->mountPoint);
  425. if (len > mntpntlen) /* can't be a subset of mountpoint. */
  426. return(0);
  427. /* if true, must be not a match or a complete match, but not a subset. */
  428. if ((len + 1) == mntpntlen)
  429. return(0);
  430. rc = strncmp(fname, h->mountPoint, len); /* !!! FIXME: case insensitive? */
  431. if (rc != 0)
  432. return(0); /* not a match. */
  433. /* make sure /a/b matches /a/b/ and not /a/bc ... */
  434. return(h->mountPoint[len] == '/');
  435. } /* partOfMountPoint */
  436. static DirHandle *createDirHandle(const char *newDir,
  437. const char *mountPoint,
  438. int forWriting)
  439. {
  440. DirHandle *dirHandle = NULL;
  441. GOTO_IF_MACRO(!newDir, ERR_INVALID_ARGUMENT, badDirHandle);
  442. if (mountPoint != NULL)
  443. {
  444. char *mntpnt = (char *) alloca(strlen(mountPoint) + 1);
  445. GOTO_IF_MACRO(!mntpnt, ERR_OUT_OF_MEMORY, badDirHandle);
  446. if (!sanitizePlatformIndependentPath(mountPoint, mntpnt))
  447. goto badDirHandle;
  448. mountPoint = mntpnt; /* sanitized version. */
  449. } /* if */
  450. dirHandle = openDirectory(newDir, forWriting);
  451. GOTO_IF_MACRO(!dirHandle, NULL, badDirHandle);
  452. dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
  453. GOTO_IF_MACRO(!dirHandle->dirName, ERR_OUT_OF_MEMORY, badDirHandle);
  454. strcpy(dirHandle->dirName, newDir);
  455. if ((mountPoint != NULL) && (*mountPoint != '\0'))
  456. {
  457. dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
  458. GOTO_IF_MACRO(!dirHandle->mountPoint, ERR_OUT_OF_MEMORY, badDirHandle);
  459. strcpy(dirHandle->mountPoint, mountPoint);
  460. strcat(dirHandle->mountPoint, "/");
  461. } /* if */
  462. return(dirHandle);
  463. badDirHandle:
  464. if (dirHandle != NULL)
  465. {
  466. dirHandle->funcs->dirClose(dirHandle->opaque);
  467. allocator.Free(dirHandle->dirName);
  468. allocator.Free(dirHandle->mountPoint);
  469. allocator.Free(dirHandle);
  470. } /* if */
  471. return(NULL);
  472. } /* createDirHandle */
  473. /* MAKE SURE you've got the stateLock held before calling this! */
  474. static int freeDirHandle(DirHandle *dh, FileHandle *openList)
  475. {
  476. FileHandle *i;
  477. if (dh == NULL)
  478. return(1);
  479. for (i = openList; i != NULL; i = i->next)
  480. BAIL_IF_MACRO(i->dirHandle == dh, ERR_FILES_STILL_OPEN, 0);
  481. dh->funcs->dirClose(dh->opaque);
  482. allocator.Free(dh->dirName);
  483. allocator.Free(dh->mountPoint);
  484. allocator.Free(dh);
  485. return(1);
  486. } /* freeDirHandle */
  487. static char *calculateUserDir(void)
  488. {
  489. char *retval = NULL;
  490. const char *str = NULL;
  491. str = __PHYSFS_platformGetUserDir();
  492. if (str != NULL)
  493. retval = (char *) str;
  494. else
  495. {
  496. const char *dirsep = PHYSFS_getDirSeparator();
  497. const char *uname = __PHYSFS_platformGetUserName();
  498. str = (uname != NULL) ? uname : "default";
  499. retval = (char *) allocator.Malloc(strlen(baseDir) + strlen(str) +
  500. strlen(dirsep) + 6);
  501. if (retval == NULL)
  502. __PHYSFS_setError(ERR_OUT_OF_MEMORY);
  503. else
  504. sprintf(retval, "%susers%s%s", baseDir, dirsep, str);
  505. if (uname != NULL)
  506. allocator.Free((void *) uname);
  507. } /* else */
  508. return(retval);
  509. } /* calculateUserDir */
  510. static int appendDirSep(char **dir)
  511. {
  512. const char *dirsep = PHYSFS_getDirSeparator();
  513. char *ptr;
  514. if (strcmp((*dir + strlen(*dir)) - strlen(dirsep), dirsep) == 0)
  515. return(1);
  516. ptr = (char *) allocator.Realloc(*dir, strlen(*dir) + strlen(dirsep) + 1);
  517. if (!ptr)
  518. {
  519. allocator.Free(*dir);
  520. return(0);
  521. } /* if */
  522. strcat(ptr, dirsep);
  523. *dir = ptr;
  524. return(1);
  525. } /* appendDirSep */
  526. static char *calculateBaseDir(const char *argv0)
  527. {
  528. 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. /* we need argv0 to be sane to go on. */
  538. BAIL_IF_MACRO(argv0 == NULL, ERR_INVALID_ARGUMENT, NULL);
  539. /*
  540. * Determine if there's a path on argv0. If there is, that's the base dir.
  541. */
  542. ptr = strstr(argv0, dirsep);
  543. if (ptr != NULL)
  544. {
  545. char *p = ptr;
  546. size_t size;
  547. while (p != NULL)
  548. {
  549. ptr = p;
  550. p = strstr(p + 1, dirsep);
  551. } /* while */
  552. size = (size_t) (ptr - argv0);
  553. retval = (char *) allocator.Malloc(size + 1);
  554. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  555. memcpy(retval, argv0, size);
  556. retval[size] = '\0';
  557. return(retval);
  558. } /* if */
  559. /* !!! FIXME: should probably just fail here instead of being heroic. */
  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_stricmpASCII(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 *ptr = NULL;
  1206. char *end = NULL;
  1207. char *mountPoint = (char *) alloca(strlen(i->mountPoint) + 1);
  1208. strcpy(mountPoint, i->mountPoint);
  1209. ptr = mountPoint + ((len) ? len + 1 : 0);
  1210. end = strchr(ptr, '/');
  1211. assert(end); /* should always find a terminating '/'. */
  1212. *end = '\0';
  1213. callback(data, _fname, ptr);
  1214. } /* enumerateFromMountPoint */
  1215. void PHYSFS_enumerateFilesCallback(const char *_fname,
  1216. PHYSFS_EnumFilesCallback callback,
  1217. void *data)
  1218. {
  1219. DirHandle *i;
  1220. int noSyms;
  1221. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1222. if ((fname == NULL) || (callback == NULL))
  1223. return; /* oh well. */
  1224. if (!sanitizePlatformIndependentPath(_fname, fname))
  1225. return;
  1226. __PHYSFS_platformGrabMutex(stateLock);
  1227. noSyms = !allowSymLinks;
  1228. for (i = searchPath; i != NULL; i = i->next)
  1229. {
  1230. char *arcfname = fname;
  1231. if (partOfMountPoint(i, arcfname))
  1232. enumerateFromMountPoint(i, arcfname, callback, _fname, data);
  1233. else if (verifyPath(i, &arcfname, 0))
  1234. {
  1235. i->funcs->enumerateFiles(i->opaque, arcfname, noSyms,
  1236. callback, _fname, data);
  1237. } /* else if */
  1238. } /* for */
  1239. __PHYSFS_platformReleaseMutex(stateLock);
  1240. } /* PHYSFS_enumerateFilesCallback */
  1241. int PHYSFS_exists(const char *fname)
  1242. {
  1243. return(PHYSFS_getRealDir(fname) != NULL);
  1244. } /* PHYSFS_exists */
  1245. PHYSFS_sint64 PHYSFS_getLastModTime(const char *_fname)
  1246. {
  1247. DirHandle *i;
  1248. PHYSFS_sint64 retval = -1;
  1249. int fileExists = 0;
  1250. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1251. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1252. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1253. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1254. return(1); /* !!! FIXME: Maybe this should be an error? */
  1255. __PHYSFS_platformGrabMutex(stateLock);
  1256. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1257. {
  1258. char *arcfname = fname;
  1259. fileExists = partOfMountPoint(i, arcfname);
  1260. if (fileExists)
  1261. retval = 1; /* !!! FIXME: What's the right value? */
  1262. else if (verifyPath(i, &arcfname, 0))
  1263. retval = i->funcs->getLastModTime(i->opaque,arcfname,&fileExists);
  1264. } /* for */
  1265. __PHYSFS_platformReleaseMutex(stateLock);
  1266. return(retval);
  1267. } /* PHYSFS_getLastModTime */
  1268. int PHYSFS_isDirectory(const char *_fname)
  1269. {
  1270. DirHandle *i;
  1271. int retval = 0;
  1272. int fileExists = 0;
  1273. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1274. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1275. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1276. BAIL_IF_MACRO(*fname == '\0', NULL, 1); /* Root is always a dir. :) */
  1277. __PHYSFS_platformGrabMutex(stateLock);
  1278. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1279. {
  1280. char *arcfname = fname;
  1281. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1282. retval = 1;
  1283. else if (verifyPath(i, &arcfname, 0))
  1284. retval = i->funcs->isDirectory(i->opaque, arcfname, &fileExists);
  1285. } /* for */
  1286. __PHYSFS_platformReleaseMutex(stateLock);
  1287. return(retval);
  1288. } /* PHYSFS_isDirectory */
  1289. int PHYSFS_isSymbolicLink(const char *_fname)
  1290. {
  1291. DirHandle *i;
  1292. int retval = 0;
  1293. int fileExists = 0;
  1294. char *fname;
  1295. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1296. fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1297. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1298. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1299. BAIL_IF_MACRO(*fname == '\0', NULL, 0); /* Root is never a symlink */
  1300. __PHYSFS_platformGrabMutex(stateLock);
  1301. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1302. {
  1303. char *arcfname = fname;
  1304. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1305. retval = 0; /* virtual dir...not a symlink. */
  1306. else if (verifyPath(i, &arcfname, 0))
  1307. retval = i->funcs->isSymLink(i->opaque, arcfname, &fileExists);
  1308. } /* for */
  1309. __PHYSFS_platformReleaseMutex(stateLock);
  1310. return(retval);
  1311. } /* PHYSFS_isSymbolicLink */
  1312. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1313. {
  1314. void *opaque = NULL;
  1315. FileHandle *fh = NULL;
  1316. DirHandle *h = NULL;
  1317. const PHYSFS_Archiver *f;
  1318. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1319. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1320. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1321. __PHYSFS_platformGrabMutex(stateLock);
  1322. BAIL_IF_MACRO_MUTEX(!writeDir, ERR_NO_WRITE_DIR, stateLock, NULL);
  1323. h = writeDir;
  1324. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, NULL);
  1325. f = h->funcs;
  1326. if (appending)
  1327. opaque = f->openAppend(h->opaque, fname);
  1328. else
  1329. opaque = f->openWrite(h->opaque, fname);
  1330. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1331. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1332. if (fh == NULL)
  1333. {
  1334. f->fileClose(opaque);
  1335. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1336. } /* if */
  1337. else
  1338. {
  1339. memset(fh, '\0', sizeof (FileHandle));
  1340. fh->opaque = opaque;
  1341. fh->dirHandle = h;
  1342. fh->funcs = h->funcs;
  1343. fh->next = openWriteList;
  1344. openWriteList = fh;
  1345. } /* else */
  1346. __PHYSFS_platformReleaseMutex(stateLock);
  1347. return((PHYSFS_File *) fh);
  1348. } /* doOpenWrite */
  1349. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1350. {
  1351. return(doOpenWrite(filename, 0));
  1352. } /* PHYSFS_openWrite */
  1353. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1354. {
  1355. return(doOpenWrite(filename, 1));
  1356. } /* PHYSFS_openAppend */
  1357. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  1358. {
  1359. FileHandle *fh = NULL;
  1360. int fileExists = 0;
  1361. DirHandle *i = NULL;
  1362. fvoid *opaque = NULL;
  1363. char *fname = ((_fname) ? (char *) alloca(strlen(_fname) + 1) : NULL);
  1364. BAIL_IF_MACRO(fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1365. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1366. __PHYSFS_platformGrabMutex(stateLock);
  1367. BAIL_IF_MACRO_MUTEX(!searchPath, ERR_NO_SUCH_PATH, stateLock, NULL);
  1368. /* !!! FIXME: Why aren't we using a for loop here? */
  1369. i = searchPath;
  1370. do
  1371. {
  1372. char *arcfname = fname;
  1373. if (verifyPath(i, &arcfname, 0))
  1374. {
  1375. opaque = i->funcs->openRead(i->opaque, arcfname, &fileExists);
  1376. if (opaque)
  1377. break;
  1378. } /* if */
  1379. i = i->next;
  1380. } while ((i != NULL) && (!fileExists));
  1381. BAIL_IF_MACRO_MUTEX(opaque == NULL, NULL, stateLock, NULL);
  1382. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1383. if (fh == NULL)
  1384. {
  1385. i->funcs->fileClose(opaque);
  1386. BAIL_MACRO_MUTEX(ERR_OUT_OF_MEMORY, stateLock, NULL);
  1387. } /* if */
  1388. memset(fh, '\0', sizeof (FileHandle));
  1389. fh->opaque = opaque;
  1390. fh->forReading = 1;
  1391. fh->dirHandle = i;
  1392. fh->funcs = i->funcs;
  1393. fh->next = openReadList;
  1394. openReadList = fh;
  1395. __PHYSFS_platformReleaseMutex(stateLock);
  1396. return((PHYSFS_File *) fh);
  1397. } /* PHYSFS_openRead */
  1398. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1399. {
  1400. FileHandle *prev = NULL;
  1401. FileHandle *i;
  1402. int rc = 1;
  1403. for (i = *list; i != NULL; i = i->next)
  1404. {
  1405. if (i == handle) /* handle is in this list? */
  1406. {
  1407. PHYSFS_uint8 *tmp = handle->buffer;
  1408. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1409. if (rc)
  1410. rc = handle->funcs->fileClose(handle->opaque);
  1411. if (!rc)
  1412. return(-1);
  1413. if (tmp != NULL) /* free any associated buffer. */
  1414. allocator.Free(tmp);
  1415. if (prev == NULL)
  1416. *list = handle->next;
  1417. else
  1418. prev->next = handle->next;
  1419. allocator.Free(handle);
  1420. return(1);
  1421. } /* if */
  1422. prev = i;
  1423. } /* for */
  1424. return(0);
  1425. } /* closeHandleInOpenList */
  1426. int PHYSFS_close(PHYSFS_File *_handle)
  1427. {
  1428. FileHandle *handle = (FileHandle *) _handle;
  1429. int rc;
  1430. __PHYSFS_platformGrabMutex(stateLock);
  1431. /* -1 == close failure. 0 == not found. 1 == success. */
  1432. rc = closeHandleInOpenList(&openReadList, handle);
  1433. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1434. if (!rc)
  1435. {
  1436. rc = closeHandleInOpenList(&openWriteList, handle);
  1437. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1438. } /* if */
  1439. __PHYSFS_platformReleaseMutex(stateLock);
  1440. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1441. return(1);
  1442. } /* PHYSFS_close */
  1443. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1444. PHYSFS_uint32 objSize,
  1445. PHYSFS_uint32 objCount)
  1446. {
  1447. PHYSFS_sint64 retval = 0;
  1448. PHYSFS_uint32 remainder = 0;
  1449. while (objCount > 0)
  1450. {
  1451. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1452. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1453. PHYSFS_uint32 copied;
  1454. if (buffered == 0) /* need to refill buffer? */
  1455. {
  1456. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1457. 1, fh->bufsize);
  1458. if (rc <= 0)
  1459. {
  1460. fh->bufpos -= remainder;
  1461. return(((rc == -1) && (retval == 0)) ? -1 : retval);
  1462. } /* if */
  1463. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1464. fh->bufpos = 0;
  1465. } /* if */
  1466. if (buffered > mustread)
  1467. buffered = (PHYSFS_uint32) mustread;
  1468. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1469. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1470. fh->bufpos += buffered;
  1471. buffered += remainder; /* take remainder into account. */
  1472. copied = (buffered / objSize);
  1473. remainder = (buffered % objSize);
  1474. retval += copied;
  1475. objCount -= copied;
  1476. } /* while */
  1477. return(retval);
  1478. } /* doBufferedRead */
  1479. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1480. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1481. {
  1482. FileHandle *fh = (FileHandle *) handle;
  1483. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1484. if (fh->buffer != NULL)
  1485. return(doBufferedRead(fh, buffer, objSize, objCount));
  1486. return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
  1487. } /* PHYSFS_read */
  1488. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1489. PHYSFS_uint32 objSize,
  1490. PHYSFS_uint32 objCount)
  1491. {
  1492. FileHandle *fh = (FileHandle *) handle;
  1493. /* whole thing fits in the buffer? */
  1494. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1495. {
  1496. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1497. fh->buffill += (objSize * objCount);
  1498. return(objCount);
  1499. } /* if */
  1500. /* would overflow buffer. Flush and then write the new objects, too. */
  1501. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1502. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1503. } /* doBufferedWrite */
  1504. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1505. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1506. {
  1507. FileHandle *fh = (FileHandle *) handle;
  1508. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1509. if (fh->buffer != NULL)
  1510. return(doBufferedWrite(handle, buffer, objSize, objCount));
  1511. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1512. } /* PHYSFS_write */
  1513. int PHYSFS_eof(PHYSFS_File *handle)
  1514. {
  1515. FileHandle *fh = (FileHandle *) handle;
  1516. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1517. return(0);
  1518. /* eof if buffer is empty and archiver says so. */
  1519. return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
  1520. } /* PHYSFS_eof */
  1521. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1522. {
  1523. FileHandle *fh = (FileHandle *) handle;
  1524. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1525. PHYSFS_sint64 retval = fh->forReading ?
  1526. (pos - fh->buffill) + fh->bufpos :
  1527. (pos + fh->buffill);
  1528. return(retval);
  1529. } /* PHYSFS_tell */
  1530. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1531. {
  1532. FileHandle *fh = (FileHandle *) handle;
  1533. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1534. if (fh->buffer && fh->forReading)
  1535. {
  1536. /* avoid throwing away our precious buffer if seeking within it. */
  1537. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1538. if ( /* seeking within the already-buffered range? */
  1539. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1540. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1541. {
  1542. fh->bufpos += (PHYSFS_uint32) offset;
  1543. return(1); /* successful seek */
  1544. } /* if */
  1545. } /* if */
  1546. /* we have to fall back to a 'raw' seek. */
  1547. fh->buffill = fh->bufpos = 0;
  1548. return(fh->funcs->seek(fh->opaque, pos));
  1549. } /* PHYSFS_seek */
  1550. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1551. {
  1552. FileHandle *fh = (FileHandle *) handle;
  1553. return(fh->funcs->fileLength(fh->opaque));
  1554. } /* PHYSFS_filelength */
  1555. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1556. {
  1557. FileHandle *fh = (FileHandle *) handle;
  1558. PHYSFS_uint32 bufsize;
  1559. /* !!! FIXME: Unlocalized string. */
  1560. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1561. bufsize = (PHYSFS_uint32) _bufsize;
  1562. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1563. /*
  1564. * For reads, we need to move the file pointer to where it would be
  1565. * if we weren't buffering, so that the next read will get the
  1566. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1567. */
  1568. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1569. {
  1570. PHYSFS_uint64 pos;
  1571. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1572. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1573. pos = ((curpos - fh->buffill) + fh->bufpos);
  1574. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1575. } /* if */
  1576. if (bufsize == 0) /* delete existing buffer. */
  1577. {
  1578. if (fh->buffer != NULL)
  1579. {
  1580. allocator.Free(fh->buffer);
  1581. fh->buffer = NULL;
  1582. } /* if */
  1583. } /* if */
  1584. else
  1585. {
  1586. PHYSFS_uint8 *newbuf;
  1587. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  1588. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1589. fh->buffer = newbuf;
  1590. } /* else */
  1591. fh->bufsize = bufsize;
  1592. fh->buffill = fh->bufpos = 0;
  1593. return(1);
  1594. } /* PHYSFS_setBuffer */
  1595. int PHYSFS_flush(PHYSFS_File *handle)
  1596. {
  1597. FileHandle *fh = (FileHandle *) handle;
  1598. PHYSFS_sint64 rc;
  1599. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1600. return(1); /* open for read or buffer empty are successful no-ops. */
  1601. /* dump buffer to disk. */
  1602. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1603. fh->buffill - fh->bufpos, 1);
  1604. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1605. fh->bufpos = fh->buffill = 0;
  1606. return(1);
  1607. } /* PHYSFS_flush */
  1608. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  1609. {
  1610. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1611. externalAllocator = (a != NULL);
  1612. if (externalAllocator)
  1613. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1614. return(1);
  1615. } /* PHYSFS_setAllocator */
  1616. static void setDefaultAllocator(void)
  1617. {
  1618. assert(!externalAllocator);
  1619. allocator.Init = __PHYSFS_platformAllocatorInit;
  1620. allocator.Deinit = __PHYSFS_platformAllocatorDeinit;
  1621. allocator.Malloc = __PHYSFS_platformAllocatorMalloc;
  1622. allocator.Realloc = __PHYSFS_platformAllocatorRealloc;
  1623. allocator.Free = __PHYSFS_platformAllocatorFree;
  1624. } /* setDefaultAllocator */
  1625. /* end of physfs.c ... */