1
0

physfs.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208
  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. &__PHYSFS_Archiver_DIR,
  87. #if (defined PHYSFS_SUPPORTS_ZIP)
  88. &__PHYSFS_Archiver_ZIP,
  89. #endif
  90. #if (defined PHYSFS_SUPPORTS_7Z)
  91. &__PHYSFS_Archiver_LZMA,
  92. #endif
  93. #if (defined PHYSFS_SUPPORTS_GRP)
  94. &__PHYSFS_Archiver_GRP,
  95. #endif
  96. #if (defined PHYSFS_SUPPORTS_QPAK)
  97. &__PHYSFS_Archiver_QPAK,
  98. #endif
  99. #if (defined PHYSFS_SUPPORTS_HOG)
  100. &__PHYSFS_Archiver_HOG,
  101. #endif
  102. #if (defined PHYSFS_SUPPORTS_MVL)
  103. &__PHYSFS_Archiver_MVL,
  104. #endif
  105. #if (defined PHYSFS_SUPPORTS_WAD)
  106. &__PHYSFS_Archiver_WAD,
  107. #endif
  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. char *tmpmntpnt = NULL;
  442. GOTO_IF_MACRO(!newDir, ERR_INVALID_ARGUMENT, badDirHandle);
  443. if (mountPoint != NULL)
  444. {
  445. const size_t len = strlen(mountPoint) + 1;
  446. tmpmntpnt = (char *) __PHYSFS_smallAlloc(len);
  447. GOTO_IF_MACRO(!tmpmntpnt, ERR_OUT_OF_MEMORY, badDirHandle);
  448. if (!sanitizePlatformIndependentPath(mountPoint, tmpmntpnt))
  449. goto badDirHandle;
  450. mountPoint = tmpmntpnt; /* sanitized version. */
  451. } /* if */
  452. dirHandle = openDirectory(newDir, forWriting);
  453. GOTO_IF_MACRO(!dirHandle, NULL, badDirHandle);
  454. dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
  455. GOTO_IF_MACRO(!dirHandle->dirName, ERR_OUT_OF_MEMORY, badDirHandle);
  456. strcpy(dirHandle->dirName, newDir);
  457. if ((mountPoint != NULL) && (*mountPoint != '\0'))
  458. {
  459. dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
  460. GOTO_IF_MACRO(!dirHandle->mountPoint, ERR_OUT_OF_MEMORY, badDirHandle);
  461. strcpy(dirHandle->mountPoint, mountPoint);
  462. strcat(dirHandle->mountPoint, "/");
  463. } /* if */
  464. __PHYSFS_smallFree(tmpmntpnt);
  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. __PHYSFS_smallFree(tmpmntpnt);
  475. return(NULL);
  476. } /* createDirHandle */
  477. /* MAKE SURE you've got the stateLock held before calling this! */
  478. static int freeDirHandle(DirHandle *dh, FileHandle *openList)
  479. {
  480. FileHandle *i;
  481. if (dh == NULL)
  482. return(1);
  483. for (i = openList; i != NULL; i = i->next)
  484. BAIL_IF_MACRO(i->dirHandle == dh, ERR_FILES_STILL_OPEN, 0);
  485. dh->funcs->dirClose(dh->opaque);
  486. allocator.Free(dh->dirName);
  487. allocator.Free(dh->mountPoint);
  488. allocator.Free(dh);
  489. return(1);
  490. } /* freeDirHandle */
  491. static char *calculateUserDir(void)
  492. {
  493. char *retval = NULL;
  494. const char *str = NULL;
  495. str = __PHYSFS_platformGetUserDir();
  496. if (str != NULL)
  497. retval = (char *) str;
  498. else
  499. {
  500. const char *dirsep = PHYSFS_getDirSeparator();
  501. const char *uname = __PHYSFS_platformGetUserName();
  502. str = (uname != NULL) ? uname : "default";
  503. retval = (char *) allocator.Malloc(strlen(baseDir) + strlen(str) +
  504. strlen(dirsep) + 6);
  505. if (retval == NULL)
  506. __PHYSFS_setError(ERR_OUT_OF_MEMORY);
  507. else
  508. sprintf(retval, "%susers%s%s", baseDir, dirsep, str);
  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. char *retval = NULL;
  532. const char *dirsep = NULL;
  533. char *ptr = NULL;
  534. /* Give the platform layer first shot at this. */
  535. retval = __PHYSFS_platformCalcBaseDir(argv0);
  536. if (retval != NULL)
  537. return(retval);
  538. /* We need argv0 to go on. */
  539. BAIL_IF_MACRO(argv0 == NULL, ERR_ARGV0_IS_NULL, NULL);
  540. dirsep = PHYSFS_getDirSeparator();
  541. if (strlen(dirsep) == 1) /* fast path. */
  542. ptr = strrchr(argv0, *dirsep);
  543. else
  544. {
  545. ptr = strstr(argv0, dirsep);
  546. if (ptr != NULL)
  547. {
  548. char *p = ptr;
  549. while (p != NULL)
  550. {
  551. ptr = p;
  552. p = strstr(p + 1, dirsep);
  553. } /* while */
  554. } /* if */
  555. } /* else */
  556. if (ptr != NULL)
  557. {
  558. size_t size = (size_t) (ptr - argv0);
  559. retval = (char *) allocator.Malloc(size + 1);
  560. BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
  561. memcpy(retval, argv0, size);
  562. retval[size] = '\0';
  563. return(retval);
  564. } /* if */
  565. /* argv0 wasn't helpful. */
  566. BAIL_MACRO(ERR_INVALID_ARGUMENT, NULL);
  567. return(NULL);
  568. } /* calculateBaseDir */
  569. static int initializeMutexes(void)
  570. {
  571. errorLock = __PHYSFS_platformCreateMutex();
  572. if (errorLock == NULL)
  573. goto initializeMutexes_failed;
  574. stateLock = __PHYSFS_platformCreateMutex();
  575. if (stateLock == NULL)
  576. goto initializeMutexes_failed;
  577. return(1); /* success. */
  578. initializeMutexes_failed:
  579. if (errorLock != NULL)
  580. __PHYSFS_platformDestroyMutex(errorLock);
  581. if (stateLock != NULL)
  582. __PHYSFS_platformDestroyMutex(stateLock);
  583. errorLock = stateLock = NULL;
  584. return(0); /* failed. */
  585. } /* initializeMutexes */
  586. static void setDefaultAllocator(void);
  587. int PHYSFS_init(const char *argv0)
  588. {
  589. char *ptr;
  590. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  591. if (!externalAllocator)
  592. setDefaultAllocator();
  593. if (allocator.Init != NULL)
  594. BAIL_IF_MACRO(!allocator.Init(), NULL, 0);
  595. BAIL_IF_MACRO(!__PHYSFS_platformInit(), NULL, 0);
  596. BAIL_IF_MACRO(!initializeMutexes(), NULL, 0);
  597. baseDir = calculateBaseDir(argv0);
  598. BAIL_IF_MACRO(baseDir == NULL, NULL, 0);
  599. /* !!! FIXME: only call this if we got this from argv0 (unreliable). */
  600. ptr = __PHYSFS_platformRealPath(baseDir);
  601. allocator.Free(baseDir);
  602. BAIL_IF_MACRO(ptr == NULL, NULL, 0);
  603. baseDir = ptr;
  604. BAIL_IF_MACRO(!appendDirSep(&baseDir), NULL, 0);
  605. userDir = calculateUserDir();
  606. if (userDir != NULL)
  607. {
  608. ptr = __PHYSFS_platformRealPath(userDir);
  609. allocator.Free(userDir);
  610. userDir = ptr;
  611. } /* if */
  612. if ((userDir == NULL) || (!appendDirSep(&userDir)))
  613. {
  614. allocator.Free(baseDir);
  615. baseDir = NULL;
  616. return(0);
  617. } /* if */
  618. initialized = 1;
  619. /* This makes sure that the error subsystem is initialized. */
  620. __PHYSFS_setError(PHYSFS_getLastError());
  621. return(1);
  622. } /* PHYSFS_init */
  623. /* MAKE SURE you hold stateLock before calling this! */
  624. static int closeFileHandleList(FileHandle **list)
  625. {
  626. FileHandle *i;
  627. FileHandle *next = NULL;
  628. for (i = *list; i != NULL; i = next)
  629. {
  630. next = i->next;
  631. if (!i->funcs->fileClose(i->opaque))
  632. {
  633. *list = i;
  634. return(0);
  635. } /* if */
  636. allocator.Free(i);
  637. } /* for */
  638. *list = NULL;
  639. return(1);
  640. } /* closeFileHandleList */
  641. /* MAKE SURE you hold the stateLock before calling this! */
  642. static void freeSearchPath(void)
  643. {
  644. DirHandle *i;
  645. DirHandle *next = NULL;
  646. closeFileHandleList(&openReadList);
  647. if (searchPath != NULL)
  648. {
  649. for (i = searchPath; i != NULL; i = next)
  650. {
  651. next = i->next;
  652. freeDirHandle(i, openReadList);
  653. } /* for */
  654. searchPath = NULL;
  655. } /* if */
  656. } /* freeSearchPath */
  657. int PHYSFS_deinit(void)
  658. {
  659. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  660. BAIL_IF_MACRO(!__PHYSFS_platformDeinit(), NULL, 0);
  661. closeFileHandleList(&openWriteList);
  662. BAIL_IF_MACRO(!PHYSFS_setWriteDir(NULL), ERR_FILES_STILL_OPEN, 0);
  663. freeSearchPath();
  664. freeErrorMessages();
  665. if (baseDir != NULL)
  666. {
  667. allocator.Free(baseDir);
  668. baseDir = NULL;
  669. } /* if */
  670. if (userDir != NULL)
  671. {
  672. allocator.Free(userDir);
  673. userDir = NULL;
  674. } /* if */
  675. allowSymLinks = 0;
  676. initialized = 0;
  677. __PHYSFS_platformDestroyMutex(errorLock);
  678. __PHYSFS_platformDestroyMutex(stateLock);
  679. if (allocator.Deinit != NULL)
  680. allocator.Deinit();
  681. errorLock = stateLock = NULL;
  682. return(1);
  683. } /* PHYSFS_deinit */
  684. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  685. {
  686. return(supported_types);
  687. } /* PHYSFS_supportedArchiveTypes */
  688. void PHYSFS_freeList(void *list)
  689. {
  690. void **i;
  691. for (i = (void **) list; *i != NULL; i++)
  692. allocator.Free(*i);
  693. allocator.Free(list);
  694. } /* PHYSFS_freeList */
  695. const char *PHYSFS_getDirSeparator(void)
  696. {
  697. return(__PHYSFS_platformDirSeparator);
  698. } /* PHYSFS_getDirSeparator */
  699. char **PHYSFS_getCdRomDirs(void)
  700. {
  701. return(doEnumStringList(__PHYSFS_platformDetectAvailableCDs));
  702. } /* PHYSFS_getCdRomDirs */
  703. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  704. {
  705. __PHYSFS_platformDetectAvailableCDs(callback, data);
  706. } /* PHYSFS_getCdRomDirsCallback */
  707. const char *PHYSFS_getBaseDir(void)
  708. {
  709. return(baseDir); /* this is calculated in PHYSFS_init()... */
  710. } /* PHYSFS_getBaseDir */
  711. const char *PHYSFS_getUserDir(void)
  712. {
  713. return(userDir); /* this is calculated in PHYSFS_init()... */
  714. } /* PHYSFS_getUserDir */
  715. const char *PHYSFS_getWriteDir(void)
  716. {
  717. const char *retval = NULL;
  718. __PHYSFS_platformGrabMutex(stateLock);
  719. if (writeDir != NULL)
  720. retval = writeDir->dirName;
  721. __PHYSFS_platformReleaseMutex(stateLock);
  722. return(retval);
  723. } /* PHYSFS_getWriteDir */
  724. int PHYSFS_setWriteDir(const char *newDir)
  725. {
  726. int retval = 1;
  727. __PHYSFS_platformGrabMutex(stateLock);
  728. if (writeDir != NULL)
  729. {
  730. BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), NULL,
  731. stateLock, 0);
  732. writeDir = NULL;
  733. } /* if */
  734. if (newDir != NULL)
  735. {
  736. writeDir = createDirHandle(newDir, NULL, 1);
  737. retval = (writeDir != NULL);
  738. } /* if */
  739. __PHYSFS_platformReleaseMutex(stateLock);
  740. return(retval);
  741. } /* PHYSFS_setWriteDir */
  742. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  743. {
  744. DirHandle *dh;
  745. DirHandle *prev = NULL;
  746. DirHandle *i;
  747. BAIL_IF_MACRO(newDir == NULL, ERR_INVALID_ARGUMENT, 0);
  748. if (mountPoint == NULL)
  749. mountPoint = "/";
  750. __PHYSFS_platformGrabMutex(stateLock);
  751. for (i = searchPath; i != NULL; i = i->next)
  752. {
  753. /* already in search path? */
  754. BAIL_IF_MACRO_MUTEX(strcmp(newDir, i->dirName)==0, NULL, stateLock, 1);
  755. prev = i;
  756. } /* for */
  757. dh = createDirHandle(newDir, mountPoint, 0);
  758. BAIL_IF_MACRO_MUTEX(dh == NULL, NULL, stateLock, 0);
  759. if (appendToPath)
  760. {
  761. if (prev == NULL)
  762. searchPath = dh;
  763. else
  764. prev->next = dh;
  765. } /* if */
  766. else
  767. {
  768. dh->next = searchPath;
  769. searchPath = dh;
  770. } /* else */
  771. __PHYSFS_platformReleaseMutex(stateLock);
  772. return(1);
  773. } /* PHYSFS_mount */
  774. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  775. {
  776. return(PHYSFS_mount(newDir, NULL, appendToPath));
  777. } /* PHYSFS_addToSearchPath */
  778. int PHYSFS_removeFromSearchPath(const char *oldDir)
  779. {
  780. DirHandle *i;
  781. DirHandle *prev = NULL;
  782. DirHandle *next = NULL;
  783. BAIL_IF_MACRO(oldDir == NULL, ERR_INVALID_ARGUMENT, 0);
  784. __PHYSFS_platformGrabMutex(stateLock);
  785. for (i = searchPath; i != NULL; i = i->next)
  786. {
  787. if (strcmp(i->dirName, oldDir) == 0)
  788. {
  789. next = i->next;
  790. BAIL_IF_MACRO_MUTEX(!freeDirHandle(i, openReadList), NULL,
  791. stateLock, 0);
  792. if (prev == NULL)
  793. searchPath = next;
  794. else
  795. prev->next = next;
  796. BAIL_MACRO_MUTEX(NULL, stateLock, 1);
  797. } /* if */
  798. prev = i;
  799. } /* for */
  800. BAIL_MACRO_MUTEX(ERR_NOT_IN_SEARCH_PATH, stateLock, 0);
  801. } /* PHYSFS_removeFromSearchPath */
  802. char **PHYSFS_getSearchPath(void)
  803. {
  804. return(doEnumStringList(PHYSFS_getSearchPathCallback));
  805. } /* PHYSFS_getSearchPath */
  806. const char *PHYSFS_getMountPoint(const char *dir)
  807. {
  808. DirHandle *i;
  809. __PHYSFS_platformGrabMutex(stateLock);
  810. for (i = searchPath; i != NULL; i = i->next)
  811. {
  812. if (strcmp(i->dirName, dir) == 0)
  813. {
  814. const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
  815. __PHYSFS_platformReleaseMutex(stateLock);
  816. return(retval);
  817. } /* if */
  818. } /* for */
  819. __PHYSFS_platformReleaseMutex(stateLock);
  820. BAIL_MACRO(ERR_NOT_IN_SEARCH_PATH, NULL);
  821. } /* PHYSFS_getMountPoint */
  822. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  823. {
  824. DirHandle *i;
  825. __PHYSFS_platformGrabMutex(stateLock);
  826. for (i = searchPath; i != NULL; i = i->next)
  827. callback(data, i->dirName);
  828. __PHYSFS_platformReleaseMutex(stateLock);
  829. } /* PHYSFS_getSearchPathCallback */
  830. /* Split out to avoid stack allocation in a loop. */
  831. static void setSaneCfgAddPath(const char *i, const size_t l, const char *dirsep,
  832. int archivesFirst)
  833. {
  834. const char *d = PHYSFS_getRealDir(i);
  835. const size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
  836. char *str = (char *) __PHYSFS_smallAlloc(allocsize);
  837. if (str != NULL)
  838. {
  839. sprintf(str, "%s%s%s", d, dirsep, i);
  840. PHYSFS_addToSearchPath(str, archivesFirst == 0);
  841. __PHYSFS_smallFree(str);
  842. } /* if */
  843. } /* setSaneCfgAddPath */
  844. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  845. const char *archiveExt, int includeCdRoms,
  846. int archivesFirst)
  847. {
  848. const char *basedir = PHYSFS_getBaseDir();
  849. const char *userdir = PHYSFS_getUserDir();
  850. const char *dirsep = PHYSFS_getDirSeparator();
  851. PHYSFS_uint64 len = 0;
  852. char *str = NULL;
  853. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  854. /* set write dir... */
  855. len = (strlen(userdir) + (strlen(organization) * 2) +
  856. (strlen(appName) * 2) + (strlen(dirsep) * 3) + 2);
  857. str = (char *) __PHYSFS_smallAlloc(len);
  858. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
  859. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  860. if (!PHYSFS_setWriteDir(str))
  861. {
  862. int no_write = 0;
  863. sprintf(str, ".%s/%s", organization, appName);
  864. if ( (PHYSFS_setWriteDir(userdir)) &&
  865. (PHYSFS_mkdir(str)) )
  866. {
  867. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  868. if (!PHYSFS_setWriteDir(str))
  869. no_write = 1;
  870. } /* if */
  871. else
  872. {
  873. no_write = 1;
  874. } /* else */
  875. if (no_write)
  876. {
  877. PHYSFS_setWriteDir(NULL); /* just in case. */
  878. __PHYSFS_smallFree(str);
  879. BAIL_MACRO(ERR_CANT_SET_WRITE_DIR, 0);
  880. } /* if */
  881. } /* if */
  882. /* Put write dir first in search path... */
  883. PHYSFS_addToSearchPath(str, 0);
  884. __PHYSFS_smallFree(str);
  885. /* Put base path on search path... */
  886. PHYSFS_addToSearchPath(basedir, 1);
  887. /* handle CD-ROMs... */
  888. if (includeCdRoms)
  889. {
  890. char **cds = PHYSFS_getCdRomDirs();
  891. char **i;
  892. for (i = cds; *i != NULL; i++)
  893. PHYSFS_addToSearchPath(*i, 1);
  894. PHYSFS_freeList(cds);
  895. } /* if */
  896. /* Root out archives, and add them to search path... */
  897. if (archiveExt != NULL)
  898. {
  899. char **rc = PHYSFS_enumerateFiles("/");
  900. char **i;
  901. size_t extlen = strlen(archiveExt);
  902. char *ext;
  903. for (i = rc; *i != NULL; i++)
  904. {
  905. size_t l = strlen(*i);
  906. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  907. {
  908. ext = (*i) + (l - extlen);
  909. if (__PHYSFS_stricmpASCII(ext, archiveExt) == 0)
  910. setSaneCfgAddPath(*i, l, dirsep, archivesFirst);
  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. static int doMkdir(const char *_dname, 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. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_dname, dname), NULL, 0);
  1067. __PHYSFS_platformGrabMutex(stateLock);
  1068. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1069. h = writeDir;
  1070. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &dname, 1), NULL, stateLock, 0);
  1071. start = dname;
  1072. while (1)
  1073. {
  1074. end = strchr(start, '/');
  1075. if (end != NULL)
  1076. *end = '\0';
  1077. /* only check for existance if all parent dirs existed, too... */
  1078. if (exists)
  1079. retval = h->funcs->isDirectory(h->opaque, dname, &exists);
  1080. if (!exists)
  1081. retval = h->funcs->mkdir(h->opaque, dname);
  1082. if (!retval)
  1083. break;
  1084. if (end == NULL)
  1085. break;
  1086. *end = '/';
  1087. start = end + 1;
  1088. } /* while */
  1089. __PHYSFS_platformReleaseMutex(stateLock);
  1090. return(retval);
  1091. } /* doMkdir */
  1092. int PHYSFS_mkdir(const char *_dname)
  1093. {
  1094. int retval = 0;
  1095. char *dname;
  1096. size_t len;
  1097. BAIL_IF_MACRO(_dname == NULL, ERR_INVALID_ARGUMENT, 0);
  1098. len = strlen(_dname) + 1;
  1099. dname = (char *) __PHYSFS_smallAlloc(len);
  1100. BAIL_IF_MACRO(dname == NULL, ERR_OUT_OF_MEMORY, 0);
  1101. retval = doMkdir(_dname, dname);
  1102. __PHYSFS_smallFree(dname);
  1103. return(retval);
  1104. } /* PHYSFS_mkdir */
  1105. static int doDelete(const char *_fname, char *fname)
  1106. {
  1107. int retval;
  1108. DirHandle *h;
  1109. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1110. __PHYSFS_platformGrabMutex(stateLock);
  1111. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1112. h = writeDir;
  1113. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, 0);
  1114. retval = h->funcs->remove(h->opaque, fname);
  1115. __PHYSFS_platformReleaseMutex(stateLock);
  1116. return(retval);
  1117. } /* doDelete */
  1118. int PHYSFS_delete(const char *_fname)
  1119. {
  1120. int retval;
  1121. char *fname;
  1122. size_t len;
  1123. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1124. len = strlen(_fname) + 1;
  1125. fname = (char *) __PHYSFS_smallAlloc(len);
  1126. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1127. retval = doDelete(_fname, fname);
  1128. __PHYSFS_smallFree(fname);
  1129. return(retval);
  1130. } /* PHYSFS_delete */
  1131. const char *PHYSFS_getRealDir(const char *_fname)
  1132. {
  1133. const char *retval = NULL;
  1134. char *fname = NULL;
  1135. size_t len;
  1136. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1137. len = strlen(_fname) + 1;
  1138. fname = __PHYSFS_smallAlloc(len);
  1139. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, NULL);
  1140. if (sanitizePlatformIndependentPath(_fname, fname))
  1141. {
  1142. DirHandle *i;
  1143. __PHYSFS_platformGrabMutex(stateLock);
  1144. for (i = searchPath; ((i != NULL) && (retval == NULL)); i = i->next)
  1145. {
  1146. char *arcfname = fname;
  1147. if (partOfMountPoint(i, arcfname))
  1148. retval = i->dirName;
  1149. else if (verifyPath(i, &arcfname, 0))
  1150. {
  1151. if (i->funcs->exists(i->opaque, arcfname))
  1152. retval = i->dirName;
  1153. } /* if */
  1154. } /* for */
  1155. __PHYSFS_platformReleaseMutex(stateLock);
  1156. } /* if */
  1157. __PHYSFS_smallFree(fname);
  1158. return(retval);
  1159. } /* PHYSFS_getRealDir */
  1160. static int locateInStringList(const char *str,
  1161. char **list,
  1162. PHYSFS_uint32 *pos)
  1163. {
  1164. PHYSFS_uint32 len = *pos;
  1165. PHYSFS_uint32 half_len;
  1166. PHYSFS_uint32 lo = 0;
  1167. PHYSFS_uint32 middle;
  1168. int cmp;
  1169. while (len > 0)
  1170. {
  1171. half_len = len >> 1;
  1172. middle = lo + half_len;
  1173. cmp = strcmp(list[middle], str);
  1174. if (cmp == 0) /* it's in the list already. */
  1175. return(1);
  1176. else if (cmp > 0)
  1177. len = half_len;
  1178. else
  1179. {
  1180. lo = middle + 1;
  1181. len -= half_len + 1;
  1182. } /* else */
  1183. } /* while */
  1184. *pos = lo;
  1185. return(0);
  1186. } /* locateInStringList */
  1187. static void enumFilesCallback(void *data, const char *origdir, const char *str)
  1188. {
  1189. PHYSFS_uint32 pos;
  1190. void *ptr;
  1191. char *newstr;
  1192. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1193. /*
  1194. * See if file is in the list already, and if not, insert it in there
  1195. * alphabetically...
  1196. */
  1197. pos = pecd->size;
  1198. if (locateInStringList(str, pecd->list, &pos))
  1199. return; /* already in the list. */
  1200. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1201. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1202. if (ptr != NULL)
  1203. pecd->list = (char **) ptr;
  1204. if ((ptr == NULL) || (newstr == NULL))
  1205. return; /* better luck next time. */
  1206. strcpy(newstr, str);
  1207. if (pos != pecd->size)
  1208. {
  1209. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1210. sizeof (char *) * ((pecd->size) - pos));
  1211. } /* if */
  1212. pecd->list[pos] = newstr;
  1213. pecd->size++;
  1214. } /* enumFilesCallback */
  1215. char **PHYSFS_enumerateFiles(const char *path)
  1216. {
  1217. EnumStringListCallbackData ecd;
  1218. memset(&ecd, '\0', sizeof (ecd));
  1219. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1220. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  1221. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1222. ecd.list[ecd.size] = NULL;
  1223. return(ecd.list);
  1224. } /* PHYSFS_enumerateFiles */
  1225. /*
  1226. * Broke out to seperate function so we can use stack allocation gratuitously.
  1227. */
  1228. static void enumerateFromMountPoint(DirHandle *i, const char *arcfname,
  1229. PHYSFS_EnumFilesCallback callback,
  1230. const char *_fname, void *data)
  1231. {
  1232. const size_t len = strlen(arcfname);
  1233. char *ptr = NULL;
  1234. char *end = NULL;
  1235. const size_t slen = strlen(i->mountPoint) + 1;
  1236. char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
  1237. if (mountPoint == NULL)
  1238. return; /* oh well. */
  1239. strcpy(mountPoint, i->mountPoint);
  1240. ptr = mountPoint + ((len) ? len + 1 : 0);
  1241. end = strchr(ptr, '/');
  1242. assert(end); /* should always find a terminating '/'. */
  1243. *end = '\0';
  1244. callback(data, _fname, ptr);
  1245. __PHYSFS_smallFree(mountPoint);
  1246. } /* enumerateFromMountPoint */
  1247. /* !!! FIXME: this should report error conditions. */
  1248. void PHYSFS_enumerateFilesCallback(const char *_fname,
  1249. PHYSFS_EnumFilesCallback callback,
  1250. void *data)
  1251. {
  1252. size_t len;
  1253. char *fname;
  1254. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
  1255. BAIL_IF_MACRO(callback == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
  1256. len = strlen(_fname) + 1;
  1257. fname = (char *) __PHYSFS_smallAlloc(len);
  1258. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, ) /*0*/;
  1259. if (sanitizePlatformIndependentPath(_fname, fname))
  1260. {
  1261. DirHandle *i;
  1262. int noSyms;
  1263. __PHYSFS_platformGrabMutex(stateLock);
  1264. noSyms = !allowSymLinks;
  1265. for (i = searchPath; i != NULL; i = i->next)
  1266. {
  1267. char *arcfname = fname;
  1268. if (partOfMountPoint(i, arcfname))
  1269. enumerateFromMountPoint(i, arcfname, callback, _fname, data);
  1270. else if (verifyPath(i, &arcfname, 0))
  1271. {
  1272. i->funcs->enumerateFiles(i->opaque, arcfname, noSyms,
  1273. callback, _fname, data);
  1274. } /* else if */
  1275. } /* for */
  1276. __PHYSFS_platformReleaseMutex(stateLock);
  1277. } /* if */
  1278. __PHYSFS_smallFree(fname);
  1279. } /* PHYSFS_enumerateFilesCallback */
  1280. int PHYSFS_exists(const char *fname)
  1281. {
  1282. return(PHYSFS_getRealDir(fname) != NULL);
  1283. } /* PHYSFS_exists */
  1284. PHYSFS_sint64 PHYSFS_getLastModTime(const char *_fname)
  1285. {
  1286. PHYSFS_sint64 retval = -1;
  1287. char *fname;
  1288. size_t len;
  1289. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, -1);
  1290. len = strlen(_fname) + 1;
  1291. fname = (char *) __PHYSFS_smallAlloc(len);
  1292. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, -1);
  1293. if (sanitizePlatformIndependentPath(_fname, fname))
  1294. {
  1295. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1296. retval = 1; /* !!! FIXME: Maybe this should be an error? */
  1297. else
  1298. {
  1299. DirHandle *i;
  1300. int exists = 0;
  1301. __PHYSFS_platformGrabMutex(stateLock);
  1302. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  1303. {
  1304. char *arcfname = fname;
  1305. exists = partOfMountPoint(i, arcfname);
  1306. if (exists)
  1307. retval = 1; /* !!! FIXME: What's the right value? */
  1308. else if (verifyPath(i, &arcfname, 0))
  1309. {
  1310. retval = i->funcs->getLastModTime(i->opaque, arcfname,
  1311. &exists);
  1312. } /* else if */
  1313. } /* for */
  1314. __PHYSFS_platformReleaseMutex(stateLock);
  1315. } /* else */
  1316. } /* if */
  1317. __PHYSFS_smallFree(fname);
  1318. return(retval);
  1319. } /* PHYSFS_getLastModTime */
  1320. int PHYSFS_isDirectory(const char *_fname)
  1321. {
  1322. int retval = 0;
  1323. size_t len;
  1324. char *fname;
  1325. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1326. len = strlen(_fname) + 1;
  1327. fname = (char *) __PHYSFS_smallAlloc(len);
  1328. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1329. if (!sanitizePlatformIndependentPath(_fname, fname))
  1330. retval = 0;
  1331. else if (*fname == '\0')
  1332. retval = 1; /* Root is always a dir. :) */
  1333. else
  1334. {
  1335. DirHandle *i;
  1336. int exists = 0;
  1337. __PHYSFS_platformGrabMutex(stateLock);
  1338. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  1339. {
  1340. char *arcfname = fname;
  1341. if ((exists = partOfMountPoint(i, arcfname)) != 0)
  1342. retval = 1;
  1343. else if (verifyPath(i, &arcfname, 0))
  1344. retval = i->funcs->isDirectory(i->opaque, arcfname, &exists);
  1345. } /* for */
  1346. __PHYSFS_platformReleaseMutex(stateLock);
  1347. } /* else */
  1348. __PHYSFS_smallFree(fname);
  1349. return(retval);
  1350. } /* PHYSFS_isDirectory */
  1351. int PHYSFS_isSymbolicLink(const char *_fname)
  1352. {
  1353. int retval = 0;
  1354. size_t len;
  1355. char *fname;
  1356. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1357. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1358. len = strlen(_fname) + 1;
  1359. fname = (char *) __PHYSFS_smallAlloc(len);
  1360. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1361. if (!sanitizePlatformIndependentPath(_fname, fname))
  1362. retval = 0;
  1363. else if (*fname == '\0')
  1364. retval = 1; /* Root is never a symlink. */
  1365. else
  1366. {
  1367. DirHandle *i;
  1368. int fileExists = 0;
  1369. __PHYSFS_platformGrabMutex(stateLock);
  1370. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1371. {
  1372. char *arcfname = fname;
  1373. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1374. retval = 0; /* virtual dir...not a symlink. */
  1375. else if (verifyPath(i, &arcfname, 0))
  1376. retval = i->funcs->isSymLink(i->opaque, arcfname, &fileExists);
  1377. } /* for */
  1378. __PHYSFS_platformReleaseMutex(stateLock);
  1379. } /* else */
  1380. __PHYSFS_smallFree(fname);
  1381. return(retval);
  1382. } /* PHYSFS_isSymbolicLink */
  1383. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1384. {
  1385. FileHandle *fh = NULL;
  1386. size_t len;
  1387. char *fname;
  1388. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1389. len = strlen(_fname) + 1;
  1390. fname = (char *) __PHYSFS_smallAlloc(len);
  1391. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1392. if (sanitizePlatformIndependentPath(_fname, fname))
  1393. {
  1394. void *opaque = NULL;
  1395. DirHandle *h = NULL;
  1396. const PHYSFS_Archiver *f;
  1397. __PHYSFS_platformGrabMutex(stateLock);
  1398. GOTO_IF_MACRO(!writeDir, ERR_NO_WRITE_DIR, doOpenWriteEnd);
  1399. h = writeDir;
  1400. GOTO_IF_MACRO(!verifyPath(h, &fname, 0), NULL, doOpenWriteEnd);
  1401. f = h->funcs;
  1402. if (appending)
  1403. opaque = f->openAppend(h->opaque, fname);
  1404. else
  1405. opaque = f->openWrite(h->opaque, fname);
  1406. GOTO_IF_MACRO(opaque == NULL, NULL, doOpenWriteEnd);
  1407. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1408. if (fh == NULL)
  1409. {
  1410. f->fileClose(opaque);
  1411. GOTO_MACRO(ERR_OUT_OF_MEMORY, doOpenWriteEnd);
  1412. } /* if */
  1413. else
  1414. {
  1415. memset(fh, '\0', sizeof (FileHandle));
  1416. fh->opaque = opaque;
  1417. fh->dirHandle = h;
  1418. fh->funcs = h->funcs;
  1419. fh->next = openWriteList;
  1420. openWriteList = fh;
  1421. } /* else */
  1422. doOpenWriteEnd:
  1423. __PHYSFS_platformReleaseMutex(stateLock);
  1424. } /* if */
  1425. __PHYSFS_smallFree(fname);
  1426. return((PHYSFS_File *) fh);
  1427. } /* doOpenWrite */
  1428. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1429. {
  1430. return(doOpenWrite(filename, 0));
  1431. } /* PHYSFS_openWrite */
  1432. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1433. {
  1434. return(doOpenWrite(filename, 1));
  1435. } /* PHYSFS_openAppend */
  1436. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  1437. {
  1438. FileHandle *fh = NULL;
  1439. char *fname;
  1440. size_t len;
  1441. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1442. len = strlen(_fname) + 1;
  1443. fname = (char *) __PHYSFS_smallAlloc(len);
  1444. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1445. if (sanitizePlatformIndependentPath(_fname, fname))
  1446. {
  1447. int fileExists = 0;
  1448. DirHandle *i = NULL;
  1449. fvoid *opaque = NULL;
  1450. __PHYSFS_platformGrabMutex(stateLock);
  1451. GOTO_IF_MACRO(!searchPath, ERR_NO_SUCH_PATH, openReadEnd);
  1452. /* !!! FIXME: Why aren't we using a for loop here? */
  1453. i = searchPath;
  1454. do
  1455. {
  1456. char *arcfname = fname;
  1457. if (verifyPath(i, &arcfname, 0))
  1458. {
  1459. opaque = i->funcs->openRead(i->opaque, arcfname, &fileExists);
  1460. if (opaque)
  1461. break;
  1462. } /* if */
  1463. i = i->next;
  1464. } while ((i != NULL) && (!fileExists));
  1465. /* !!! FIXME: may not set an error if openRead didn't fail. */
  1466. GOTO_IF_MACRO(opaque == NULL, NULL, openReadEnd);
  1467. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1468. if (fh == NULL)
  1469. {
  1470. i->funcs->fileClose(opaque);
  1471. GOTO_MACRO(ERR_OUT_OF_MEMORY, openReadEnd);
  1472. } /* if */
  1473. memset(fh, '\0', sizeof (FileHandle));
  1474. fh->opaque = opaque;
  1475. fh->forReading = 1;
  1476. fh->dirHandle = i;
  1477. fh->funcs = i->funcs;
  1478. fh->next = openReadList;
  1479. openReadList = fh;
  1480. openReadEnd:
  1481. __PHYSFS_platformReleaseMutex(stateLock);
  1482. } /* if */
  1483. __PHYSFS_smallFree(fname);
  1484. return((PHYSFS_File *) fh);
  1485. } /* PHYSFS_openRead */
  1486. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1487. {
  1488. FileHandle *prev = NULL;
  1489. FileHandle *i;
  1490. int rc = 1;
  1491. for (i = *list; i != NULL; i = i->next)
  1492. {
  1493. if (i == handle) /* handle is in this list? */
  1494. {
  1495. PHYSFS_uint8 *tmp = handle->buffer;
  1496. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1497. if (rc)
  1498. rc = handle->funcs->fileClose(handle->opaque);
  1499. if (!rc)
  1500. return(-1);
  1501. if (tmp != NULL) /* free any associated buffer. */
  1502. allocator.Free(tmp);
  1503. if (prev == NULL)
  1504. *list = handle->next;
  1505. else
  1506. prev->next = handle->next;
  1507. allocator.Free(handle);
  1508. return(1);
  1509. } /* if */
  1510. prev = i;
  1511. } /* for */
  1512. return(0);
  1513. } /* closeHandleInOpenList */
  1514. int PHYSFS_close(PHYSFS_File *_handle)
  1515. {
  1516. FileHandle *handle = (FileHandle *) _handle;
  1517. int rc;
  1518. __PHYSFS_platformGrabMutex(stateLock);
  1519. /* -1 == close failure. 0 == not found. 1 == success. */
  1520. rc = closeHandleInOpenList(&openReadList, handle);
  1521. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1522. if (!rc)
  1523. {
  1524. rc = closeHandleInOpenList(&openWriteList, handle);
  1525. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1526. } /* if */
  1527. __PHYSFS_platformReleaseMutex(stateLock);
  1528. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1529. return(1);
  1530. } /* PHYSFS_close */
  1531. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1532. PHYSFS_uint32 objSize,
  1533. PHYSFS_uint32 objCount)
  1534. {
  1535. PHYSFS_sint64 retval = 0;
  1536. PHYSFS_uint32 remainder = 0;
  1537. while (objCount > 0)
  1538. {
  1539. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1540. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1541. PHYSFS_uint32 copied;
  1542. if (buffered == 0) /* need to refill buffer? */
  1543. {
  1544. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1545. 1, fh->bufsize);
  1546. if (rc <= 0)
  1547. {
  1548. fh->bufpos -= remainder;
  1549. return(((rc == -1) && (retval == 0)) ? -1 : retval);
  1550. } /* if */
  1551. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1552. fh->bufpos = 0;
  1553. } /* if */
  1554. if (buffered > mustread)
  1555. buffered = (PHYSFS_uint32) mustread;
  1556. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1557. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1558. fh->bufpos += buffered;
  1559. buffered += remainder; /* take remainder into account. */
  1560. copied = (buffered / objSize);
  1561. remainder = (buffered % objSize);
  1562. retval += copied;
  1563. objCount -= copied;
  1564. } /* while */
  1565. return(retval);
  1566. } /* doBufferedRead */
  1567. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1568. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1569. {
  1570. FileHandle *fh = (FileHandle *) handle;
  1571. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1572. if (fh->buffer != NULL)
  1573. return(doBufferedRead(fh, buffer, objSize, objCount));
  1574. return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
  1575. } /* PHYSFS_read */
  1576. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1577. PHYSFS_uint32 objSize,
  1578. PHYSFS_uint32 objCount)
  1579. {
  1580. FileHandle *fh = (FileHandle *) handle;
  1581. /* whole thing fits in the buffer? */
  1582. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1583. {
  1584. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1585. fh->buffill += (objSize * objCount);
  1586. return(objCount);
  1587. } /* if */
  1588. /* would overflow buffer. Flush and then write the new objects, too. */
  1589. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1590. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1591. } /* doBufferedWrite */
  1592. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1593. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1594. {
  1595. FileHandle *fh = (FileHandle *) handle;
  1596. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1597. if (fh->buffer != NULL)
  1598. return(doBufferedWrite(handle, buffer, objSize, objCount));
  1599. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1600. } /* PHYSFS_write */
  1601. int PHYSFS_eof(PHYSFS_File *handle)
  1602. {
  1603. FileHandle *fh = (FileHandle *) handle;
  1604. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1605. return(0);
  1606. /* eof if buffer is empty and archiver says so. */
  1607. return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
  1608. } /* PHYSFS_eof */
  1609. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1610. {
  1611. FileHandle *fh = (FileHandle *) handle;
  1612. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1613. PHYSFS_sint64 retval = fh->forReading ?
  1614. (pos - fh->buffill) + fh->bufpos :
  1615. (pos + fh->buffill);
  1616. return(retval);
  1617. } /* PHYSFS_tell */
  1618. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1619. {
  1620. FileHandle *fh = (FileHandle *) handle;
  1621. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1622. if (fh->buffer && fh->forReading)
  1623. {
  1624. /* avoid throwing away our precious buffer if seeking within it. */
  1625. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1626. if ( /* seeking within the already-buffered range? */
  1627. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1628. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1629. {
  1630. fh->bufpos += (PHYSFS_uint32) offset;
  1631. return(1); /* successful seek */
  1632. } /* if */
  1633. } /* if */
  1634. /* we have to fall back to a 'raw' seek. */
  1635. fh->buffill = fh->bufpos = 0;
  1636. return(fh->funcs->seek(fh->opaque, pos));
  1637. } /* PHYSFS_seek */
  1638. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1639. {
  1640. FileHandle *fh = (FileHandle *) handle;
  1641. return(fh->funcs->fileLength(fh->opaque));
  1642. } /* PHYSFS_filelength */
  1643. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1644. {
  1645. FileHandle *fh = (FileHandle *) handle;
  1646. PHYSFS_uint32 bufsize;
  1647. /* !!! FIXME: Unlocalized string. */
  1648. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1649. bufsize = (PHYSFS_uint32) _bufsize;
  1650. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1651. /*
  1652. * For reads, we need to move the file pointer to where it would be
  1653. * if we weren't buffering, so that the next read will get the
  1654. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1655. */
  1656. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1657. {
  1658. PHYSFS_uint64 pos;
  1659. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1660. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1661. pos = ((curpos - fh->buffill) + fh->bufpos);
  1662. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1663. } /* if */
  1664. if (bufsize == 0) /* delete existing buffer. */
  1665. {
  1666. if (fh->buffer != NULL)
  1667. {
  1668. allocator.Free(fh->buffer);
  1669. fh->buffer = NULL;
  1670. } /* if */
  1671. } /* if */
  1672. else
  1673. {
  1674. PHYSFS_uint8 *newbuf;
  1675. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  1676. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1677. fh->buffer = newbuf;
  1678. } /* else */
  1679. fh->bufsize = bufsize;
  1680. fh->buffill = fh->bufpos = 0;
  1681. return(1);
  1682. } /* PHYSFS_setBuffer */
  1683. int PHYSFS_flush(PHYSFS_File *handle)
  1684. {
  1685. FileHandle *fh = (FileHandle *) handle;
  1686. PHYSFS_sint64 rc;
  1687. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1688. return(1); /* open for read or buffer empty are successful no-ops. */
  1689. /* dump buffer to disk. */
  1690. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1691. fh->buffill - fh->bufpos, 1);
  1692. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1693. fh->bufpos = fh->buffill = 0;
  1694. return(1);
  1695. } /* PHYSFS_flush */
  1696. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  1697. {
  1698. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1699. externalAllocator = (a != NULL);
  1700. if (externalAllocator)
  1701. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1702. return(1);
  1703. } /* PHYSFS_setAllocator */
  1704. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  1705. {
  1706. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1707. #undef malloc
  1708. return(malloc((size_t) s));
  1709. } /* mallocAllocatorMalloc */
  1710. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  1711. {
  1712. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1713. #undef realloc
  1714. return(realloc(ptr, (size_t) s));
  1715. } /* mallocAllocatorRealloc */
  1716. static void mallocAllocatorFree(void *ptr)
  1717. {
  1718. #undef free
  1719. free(ptr);
  1720. } /* mallocAllocatorFree */
  1721. static void setDefaultAllocator(void)
  1722. {
  1723. assert(!externalAllocator);
  1724. if (!__PHYSFS_platformSetDefaultAllocator(&allocator))
  1725. {
  1726. allocator.Init = NULL;
  1727. allocator.Deinit = NULL;
  1728. allocator.Malloc = mallocAllocatorMalloc;
  1729. allocator.Realloc = mallocAllocatorRealloc;
  1730. allocator.Free = mallocAllocatorFree;
  1731. } /* if */
  1732. } /* setDefaultAllocator */
  1733. void *__PHYSFS_initSmallAlloc(void *ptr, PHYSFS_uint64 len)
  1734. {
  1735. const char useHeap = ((ptr == NULL) ? 1 : 0);
  1736. if (useHeap) /* too large for stack allocation or alloca() failed. */
  1737. ptr = allocator.Malloc(len+1);
  1738. if (ptr != NULL)
  1739. {
  1740. char *retval = (char *) ptr;
  1741. /*printf("%s alloc'd (%d) bytes at (%p).\n",
  1742. useHeap ? "heap" : "stack", (int) len, ptr);*/
  1743. *retval = useHeap;
  1744. return(retval+1);
  1745. } /* if */
  1746. return(NULL); /* allocation failed. */
  1747. } /* __PHYSFS_initSmallAlloc */
  1748. void __PHYSFS_smallFree(void *ptr)
  1749. {
  1750. if (ptr != NULL)
  1751. {
  1752. char *block = ((char *) ptr) - 1;
  1753. const char useHeap = *block;
  1754. if (useHeap)
  1755. allocator.Free(block);
  1756. /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
  1757. } /* if */
  1758. } /* __PHYSFS_smallFree */
  1759. /* end of physfs.c ... */