physfs.c 60 KB

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