physfs.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220
  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. int PHYSFS_isInit(void)
  685. {
  686. return(initialized);
  687. } /* PHYSFS_isInit */
  688. const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
  689. {
  690. return(supported_types);
  691. } /* PHYSFS_supportedArchiveTypes */
  692. void PHYSFS_freeList(void *list)
  693. {
  694. void **i;
  695. for (i = (void **) list; *i != NULL; i++)
  696. allocator.Free(*i);
  697. allocator.Free(list);
  698. } /* PHYSFS_freeList */
  699. const char *PHYSFS_getDirSeparator(void)
  700. {
  701. return(__PHYSFS_platformDirSeparator);
  702. } /* PHYSFS_getDirSeparator */
  703. char **PHYSFS_getCdRomDirs(void)
  704. {
  705. return(doEnumStringList(__PHYSFS_platformDetectAvailableCDs));
  706. } /* PHYSFS_getCdRomDirs */
  707. void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
  708. {
  709. __PHYSFS_platformDetectAvailableCDs(callback, data);
  710. } /* PHYSFS_getCdRomDirsCallback */
  711. const char *PHYSFS_getBaseDir(void)
  712. {
  713. return(baseDir); /* this is calculated in PHYSFS_init()... */
  714. } /* PHYSFS_getBaseDir */
  715. const char *PHYSFS_getUserDir(void)
  716. {
  717. return(userDir); /* this is calculated in PHYSFS_init()... */
  718. } /* PHYSFS_getUserDir */
  719. const char *PHYSFS_getWriteDir(void)
  720. {
  721. const char *retval = NULL;
  722. __PHYSFS_platformGrabMutex(stateLock);
  723. if (writeDir != NULL)
  724. retval = writeDir->dirName;
  725. __PHYSFS_platformReleaseMutex(stateLock);
  726. return(retval);
  727. } /* PHYSFS_getWriteDir */
  728. int PHYSFS_setWriteDir(const char *newDir)
  729. {
  730. int retval = 1;
  731. __PHYSFS_platformGrabMutex(stateLock);
  732. if (writeDir != NULL)
  733. {
  734. BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), NULL,
  735. stateLock, 0);
  736. writeDir = NULL;
  737. } /* if */
  738. if (newDir != NULL)
  739. {
  740. writeDir = createDirHandle(newDir, NULL, 1);
  741. retval = (writeDir != NULL);
  742. } /* if */
  743. __PHYSFS_platformReleaseMutex(stateLock);
  744. return(retval);
  745. } /* PHYSFS_setWriteDir */
  746. int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
  747. {
  748. DirHandle *dh;
  749. DirHandle *prev = NULL;
  750. DirHandle *i;
  751. BAIL_IF_MACRO(newDir == NULL, ERR_INVALID_ARGUMENT, 0);
  752. if (mountPoint == NULL)
  753. mountPoint = "/";
  754. __PHYSFS_platformGrabMutex(stateLock);
  755. for (i = searchPath; i != NULL; i = i->next)
  756. {
  757. /* already in search path? */
  758. BAIL_IF_MACRO_MUTEX(strcmp(newDir, i->dirName)==0, NULL, stateLock, 1);
  759. prev = i;
  760. } /* for */
  761. dh = createDirHandle(newDir, mountPoint, 0);
  762. BAIL_IF_MACRO_MUTEX(dh == NULL, NULL, stateLock, 0);
  763. if (appendToPath)
  764. {
  765. if (prev == NULL)
  766. searchPath = dh;
  767. else
  768. prev->next = dh;
  769. } /* if */
  770. else
  771. {
  772. dh->next = searchPath;
  773. searchPath = dh;
  774. } /* else */
  775. __PHYSFS_platformReleaseMutex(stateLock);
  776. return(1);
  777. } /* PHYSFS_mount */
  778. int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
  779. {
  780. return(PHYSFS_mount(newDir, NULL, appendToPath));
  781. } /* PHYSFS_addToSearchPath */
  782. int PHYSFS_removeFromSearchPath(const char *oldDir)
  783. {
  784. DirHandle *i;
  785. DirHandle *prev = NULL;
  786. DirHandle *next = NULL;
  787. BAIL_IF_MACRO(oldDir == NULL, ERR_INVALID_ARGUMENT, 0);
  788. __PHYSFS_platformGrabMutex(stateLock);
  789. for (i = searchPath; i != NULL; i = i->next)
  790. {
  791. if (strcmp(i->dirName, oldDir) == 0)
  792. {
  793. next = i->next;
  794. BAIL_IF_MACRO_MUTEX(!freeDirHandle(i, openReadList), NULL,
  795. stateLock, 0);
  796. if (prev == NULL)
  797. searchPath = next;
  798. else
  799. prev->next = next;
  800. BAIL_MACRO_MUTEX(NULL, stateLock, 1);
  801. } /* if */
  802. prev = i;
  803. } /* for */
  804. BAIL_MACRO_MUTEX(ERR_NOT_IN_SEARCH_PATH, stateLock, 0);
  805. } /* PHYSFS_removeFromSearchPath */
  806. char **PHYSFS_getSearchPath(void)
  807. {
  808. return(doEnumStringList(PHYSFS_getSearchPathCallback));
  809. } /* PHYSFS_getSearchPath */
  810. const char *PHYSFS_getMountPoint(const char *dir)
  811. {
  812. DirHandle *i;
  813. __PHYSFS_platformGrabMutex(stateLock);
  814. for (i = searchPath; i != NULL; i = i->next)
  815. {
  816. if (strcmp(i->dirName, dir) == 0)
  817. {
  818. const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
  819. __PHYSFS_platformReleaseMutex(stateLock);
  820. return(retval);
  821. } /* if */
  822. } /* for */
  823. __PHYSFS_platformReleaseMutex(stateLock);
  824. BAIL_MACRO(ERR_NOT_IN_SEARCH_PATH, NULL);
  825. } /* PHYSFS_getMountPoint */
  826. void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
  827. {
  828. DirHandle *i;
  829. __PHYSFS_platformGrabMutex(stateLock);
  830. for (i = searchPath; i != NULL; i = i->next)
  831. callback(data, i->dirName);
  832. __PHYSFS_platformReleaseMutex(stateLock);
  833. } /* PHYSFS_getSearchPathCallback */
  834. /* Split out to avoid stack allocation in a loop. */
  835. static void setSaneCfgAddPath(const char *i, const size_t l, const char *dirsep,
  836. int archivesFirst)
  837. {
  838. const char *d = PHYSFS_getRealDir(i);
  839. const size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
  840. char *str = (char *) __PHYSFS_smallAlloc(allocsize);
  841. if (str != NULL)
  842. {
  843. sprintf(str, "%s%s%s", d, dirsep, i);
  844. PHYSFS_addToSearchPath(str, archivesFirst == 0);
  845. __PHYSFS_smallFree(str);
  846. } /* if */
  847. } /* setSaneCfgAddPath */
  848. int PHYSFS_setSaneConfig(const char *organization, const char *appName,
  849. const char *archiveExt, int includeCdRoms,
  850. int archivesFirst)
  851. {
  852. const char *basedir = PHYSFS_getBaseDir();
  853. const char *userdir = PHYSFS_getUserDir();
  854. const char *dirsep = PHYSFS_getDirSeparator();
  855. PHYSFS_uint64 len = 0;
  856. char *str = NULL;
  857. BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
  858. /* set write dir... */
  859. len = (strlen(userdir) + (strlen(organization) * 2) +
  860. (strlen(appName) * 2) + (strlen(dirsep) * 3) + 2);
  861. str = (char *) __PHYSFS_smallAlloc(len);
  862. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
  863. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  864. if (!PHYSFS_setWriteDir(str))
  865. {
  866. int no_write = 0;
  867. sprintf(str, ".%s/%s", organization, appName);
  868. if ( (PHYSFS_setWriteDir(userdir)) &&
  869. (PHYSFS_mkdir(str)) )
  870. {
  871. sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
  872. if (!PHYSFS_setWriteDir(str))
  873. no_write = 1;
  874. } /* if */
  875. else
  876. {
  877. no_write = 1;
  878. } /* else */
  879. if (no_write)
  880. {
  881. PHYSFS_setWriteDir(NULL); /* just in case. */
  882. __PHYSFS_smallFree(str);
  883. BAIL_MACRO(ERR_CANT_SET_WRITE_DIR, 0);
  884. } /* if */
  885. } /* if */
  886. /* Put write dir first in search path... */
  887. PHYSFS_addToSearchPath(str, 0);
  888. __PHYSFS_smallFree(str);
  889. /* Put base path on search path... */
  890. PHYSFS_addToSearchPath(basedir, 1);
  891. /* handle CD-ROMs... */
  892. if (includeCdRoms)
  893. {
  894. char **cds = PHYSFS_getCdRomDirs();
  895. char **i;
  896. for (i = cds; *i != NULL; i++)
  897. PHYSFS_addToSearchPath(*i, 1);
  898. PHYSFS_freeList(cds);
  899. } /* if */
  900. /* Root out archives, and add them to search path... */
  901. if (archiveExt != NULL)
  902. {
  903. char **rc = PHYSFS_enumerateFiles("/");
  904. char **i;
  905. size_t extlen = strlen(archiveExt);
  906. char *ext;
  907. for (i = rc; *i != NULL; i++)
  908. {
  909. size_t l = strlen(*i);
  910. if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
  911. {
  912. ext = (*i) + (l - extlen);
  913. if (__PHYSFS_stricmpASCII(ext, archiveExt) == 0)
  914. setSaneCfgAddPath(*i, l, dirsep, archivesFirst);
  915. } /* if */
  916. } /* for */
  917. PHYSFS_freeList(rc);
  918. } /* if */
  919. return(1);
  920. } /* PHYSFS_setSaneConfig */
  921. void PHYSFS_permitSymbolicLinks(int allow)
  922. {
  923. allowSymLinks = allow;
  924. } /* PHYSFS_permitSymbolicLinks */
  925. int PHYSFS_symbolicLinksPermitted(void)
  926. {
  927. return(allowSymLinks);
  928. } /* PHYSFS_symbolicLinksPermitted */
  929. /* string manipulation in C makes my ass itch. */
  930. char *__PHYSFS_convertToDependent(const char *prepend,
  931. const char *dirName,
  932. const char *append)
  933. {
  934. const char *dirsep = __PHYSFS_platformDirSeparator;
  935. size_t sepsize = strlen(dirsep);
  936. char *str;
  937. char *i1;
  938. char *i2;
  939. size_t allocSize;
  940. while (*dirName == '/') /* !!! FIXME: pass through sanitize function. */
  941. dirName++;
  942. allocSize = strlen(dirName) + 1;
  943. if (prepend != NULL)
  944. allocSize += strlen(prepend) + sepsize;
  945. if (append != NULL)
  946. allocSize += strlen(append) + sepsize;
  947. /* make sure there's enough space if the dir separator is bigger. */
  948. if (sepsize > 1)
  949. {
  950. str = (char *) dirName;
  951. do
  952. {
  953. str = strchr(str, '/');
  954. if (str != NULL)
  955. {
  956. allocSize += (sepsize - 1);
  957. str++;
  958. } /* if */
  959. } while (str != NULL);
  960. } /* if */
  961. str = (char *) allocator.Malloc(allocSize);
  962. BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, NULL);
  963. if (prepend == NULL)
  964. *str = '\0';
  965. else
  966. {
  967. strcpy(str, prepend);
  968. strcat(str, dirsep);
  969. } /* else */
  970. for (i1 = (char *) dirName, i2 = str + strlen(str); *i1; i1++, i2++)
  971. {
  972. if (*i1 == '/')
  973. {
  974. strcpy(i2, dirsep);
  975. i2 += sepsize;
  976. } /* if */
  977. else
  978. {
  979. *i2 = *i1;
  980. } /* else */
  981. } /* for */
  982. *i2 = '\0';
  983. if (append)
  984. {
  985. strcat(str, dirsep);
  986. strcat(str, append);
  987. } /* if */
  988. return(str);
  989. } /* __PHYSFS_convertToDependent */
  990. /*
  991. * Verify that (fname) (in platform-independent notation), in relation
  992. * to (h) is secure. That means that each element of fname is checked
  993. * for symlinks (if they aren't permitted). This also allows for quick
  994. * rejection of files that exist outside an archive's mountpoint.
  995. *
  996. * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
  997. * at a time), you should always pass zero for "allowMissing" for efficiency.
  998. *
  999. * (fname) must point to an output from sanitizePlatformIndependentPath(),
  1000. * since it will make sure that path names are in the right format for
  1001. * passing certain checks. It will also do checks for "insecure" pathnames
  1002. * like ".." which should be done once instead of once per archive. This also
  1003. * gives us license to treat (fname) as scratch space in this function.
  1004. *
  1005. * Returns non-zero if string is safe, zero if there's a security issue.
  1006. * PHYSFS_getLastError() will specify what was wrong. (*fname) will be
  1007. * updated to point past any mount point elements so it is prepared to
  1008. * be used with the archiver directly.
  1009. */
  1010. static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
  1011. {
  1012. char *fname = *_fname;
  1013. int retval = 1;
  1014. char *start;
  1015. char *end;
  1016. if (*fname == '\0') /* quick rejection. */
  1017. return(1);
  1018. /* !!! FIXME: This codeblock sucks. */
  1019. if (h->mountPoint != NULL) /* NULL mountpoint means "/". */
  1020. {
  1021. size_t mntpntlen = strlen(h->mountPoint);
  1022. size_t len = strlen(fname);
  1023. assert(mntpntlen > 1); /* root mount points should be NULL. */
  1024. /* not under the mountpoint, so skip this archive. */
  1025. BAIL_IF_MACRO(len < mntpntlen-1, ERR_NO_SUCH_PATH, 0);
  1026. /* !!! FIXME: Case insensitive? */
  1027. retval = strncmp(h->mountPoint, fname, mntpntlen-1);
  1028. BAIL_IF_MACRO(retval != 0, ERR_NO_SUCH_PATH, 0);
  1029. if (len > mntpntlen-1) /* corner case... */
  1030. BAIL_IF_MACRO(fname[mntpntlen-1] != '/', ERR_NO_SUCH_PATH, 0);
  1031. fname += mntpntlen-1; /* move to start of actual archive path. */
  1032. if (*fname == '/')
  1033. fname++;
  1034. *_fname = fname; /* skip mountpoint for later use. */
  1035. retval = 1; /* may be reset, below. */
  1036. } /* if */
  1037. start = fname;
  1038. if (!allowSymLinks)
  1039. {
  1040. while (1)
  1041. {
  1042. int rc = 0;
  1043. end = strchr(start, '/');
  1044. if (end != NULL) *end = '\0';
  1045. rc = h->funcs->isSymLink(h->opaque, fname, &retval);
  1046. if (end != NULL) *end = '/';
  1047. BAIL_IF_MACRO(rc, ERR_SYMLINK_DISALLOWED, 0); /* insecure. */
  1048. /* break out early if path element is missing. */
  1049. if (!retval)
  1050. {
  1051. /*
  1052. * We need to clear it if it's the last element of the path,
  1053. * since this might be a non-existant file we're opening
  1054. * for writing...
  1055. */
  1056. if ((end == NULL) || (allowMissing))
  1057. retval = 1;
  1058. break;
  1059. } /* if */
  1060. if (end == NULL)
  1061. break;
  1062. start = end + 1;
  1063. } /* while */
  1064. } /* if */
  1065. return(retval);
  1066. } /* verifyPath */
  1067. static int doMkdir(const char *_dname, char *dname)
  1068. {
  1069. DirHandle *h;
  1070. char *start;
  1071. char *end;
  1072. int retval = 0;
  1073. int exists = 1; /* force existance check on first path element. */
  1074. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_dname, dname), NULL, 0);
  1075. __PHYSFS_platformGrabMutex(stateLock);
  1076. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1077. h = writeDir;
  1078. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &dname, 1), NULL, stateLock, 0);
  1079. start = dname;
  1080. while (1)
  1081. {
  1082. end = strchr(start, '/');
  1083. if (end != NULL)
  1084. *end = '\0';
  1085. /* only check for existance if all parent dirs existed, too... */
  1086. if (exists)
  1087. retval = h->funcs->isDirectory(h->opaque, dname, &exists);
  1088. if (!exists)
  1089. retval = h->funcs->mkdir(h->opaque, dname);
  1090. if (!retval)
  1091. break;
  1092. if (end == NULL)
  1093. break;
  1094. *end = '/';
  1095. start = end + 1;
  1096. } /* while */
  1097. __PHYSFS_platformReleaseMutex(stateLock);
  1098. return(retval);
  1099. } /* doMkdir */
  1100. int PHYSFS_mkdir(const char *_dname)
  1101. {
  1102. int retval = 0;
  1103. char *dname;
  1104. size_t len;
  1105. BAIL_IF_MACRO(_dname == NULL, ERR_INVALID_ARGUMENT, 0);
  1106. len = strlen(_dname) + 1;
  1107. dname = (char *) __PHYSFS_smallAlloc(len);
  1108. BAIL_IF_MACRO(dname == NULL, ERR_OUT_OF_MEMORY, 0);
  1109. retval = doMkdir(_dname, dname);
  1110. __PHYSFS_smallFree(dname);
  1111. return(retval);
  1112. } /* PHYSFS_mkdir */
  1113. static int doDelete(const char *_fname, char *fname)
  1114. {
  1115. int retval;
  1116. DirHandle *h;
  1117. BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
  1118. __PHYSFS_platformGrabMutex(stateLock);
  1119. BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
  1120. h = writeDir;
  1121. BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, 0);
  1122. retval = h->funcs->remove(h->opaque, fname);
  1123. __PHYSFS_platformReleaseMutex(stateLock);
  1124. return(retval);
  1125. } /* doDelete */
  1126. int PHYSFS_delete(const char *_fname)
  1127. {
  1128. int retval;
  1129. char *fname;
  1130. size_t len;
  1131. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1132. len = strlen(_fname) + 1;
  1133. fname = (char *) __PHYSFS_smallAlloc(len);
  1134. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1135. retval = doDelete(_fname, fname);
  1136. __PHYSFS_smallFree(fname);
  1137. return(retval);
  1138. } /* PHYSFS_delete */
  1139. const char *PHYSFS_getRealDir(const char *_fname)
  1140. {
  1141. const char *retval = NULL;
  1142. char *fname = NULL;
  1143. size_t len;
  1144. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, NULL);
  1145. len = strlen(_fname) + 1;
  1146. fname = __PHYSFS_smallAlloc(len);
  1147. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, NULL);
  1148. if (sanitizePlatformIndependentPath(_fname, fname))
  1149. {
  1150. DirHandle *i;
  1151. __PHYSFS_platformGrabMutex(stateLock);
  1152. for (i = searchPath; ((i != NULL) && (retval == NULL)); i = i->next)
  1153. {
  1154. char *arcfname = fname;
  1155. if (partOfMountPoint(i, arcfname))
  1156. retval = i->dirName;
  1157. else if (verifyPath(i, &arcfname, 0))
  1158. {
  1159. if (i->funcs->exists(i->opaque, arcfname))
  1160. retval = i->dirName;
  1161. } /* if */
  1162. } /* for */
  1163. __PHYSFS_platformReleaseMutex(stateLock);
  1164. } /* if */
  1165. __PHYSFS_smallFree(fname);
  1166. return(retval);
  1167. } /* PHYSFS_getRealDir */
  1168. static int locateInStringList(const char *str,
  1169. char **list,
  1170. PHYSFS_uint32 *pos)
  1171. {
  1172. PHYSFS_uint32 len = *pos;
  1173. PHYSFS_uint32 half_len;
  1174. PHYSFS_uint32 lo = 0;
  1175. PHYSFS_uint32 middle;
  1176. int cmp;
  1177. while (len > 0)
  1178. {
  1179. half_len = len >> 1;
  1180. middle = lo + half_len;
  1181. cmp = strcmp(list[middle], str);
  1182. if (cmp == 0) /* it's in the list already. */
  1183. return(1);
  1184. else if (cmp > 0)
  1185. len = half_len;
  1186. else
  1187. {
  1188. lo = middle + 1;
  1189. len -= half_len + 1;
  1190. } /* else */
  1191. } /* while */
  1192. *pos = lo;
  1193. return(0);
  1194. } /* locateInStringList */
  1195. static void enumFilesCallback(void *data, const char *origdir, const char *str)
  1196. {
  1197. PHYSFS_uint32 pos;
  1198. void *ptr;
  1199. char *newstr;
  1200. EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
  1201. /*
  1202. * See if file is in the list already, and if not, insert it in there
  1203. * alphabetically...
  1204. */
  1205. pos = pecd->size;
  1206. if (locateInStringList(str, pecd->list, &pos))
  1207. return; /* already in the list. */
  1208. ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
  1209. newstr = (char *) allocator.Malloc(strlen(str) + 1);
  1210. if (ptr != NULL)
  1211. pecd->list = (char **) ptr;
  1212. if ((ptr == NULL) || (newstr == NULL))
  1213. return; /* better luck next time. */
  1214. strcpy(newstr, str);
  1215. if (pos != pecd->size)
  1216. {
  1217. memmove(&pecd->list[pos+1], &pecd->list[pos],
  1218. sizeof (char *) * ((pecd->size) - pos));
  1219. } /* if */
  1220. pecd->list[pos] = newstr;
  1221. pecd->size++;
  1222. } /* enumFilesCallback */
  1223. char **PHYSFS_enumerateFiles(const char *path)
  1224. {
  1225. EnumStringListCallbackData ecd;
  1226. memset(&ecd, '\0', sizeof (ecd));
  1227. ecd.list = (char **) allocator.Malloc(sizeof (char *));
  1228. BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
  1229. PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
  1230. ecd.list[ecd.size] = NULL;
  1231. return(ecd.list);
  1232. } /* PHYSFS_enumerateFiles */
  1233. /*
  1234. * Broke out to seperate function so we can use stack allocation gratuitously.
  1235. */
  1236. static void enumerateFromMountPoint(DirHandle *i, const char *arcfname,
  1237. PHYSFS_EnumFilesCallback callback,
  1238. const char *_fname, void *data)
  1239. {
  1240. const size_t len = strlen(arcfname);
  1241. char *ptr = NULL;
  1242. char *end = NULL;
  1243. const size_t slen = strlen(i->mountPoint) + 1;
  1244. char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
  1245. if (mountPoint == NULL)
  1246. return; /* oh well. */
  1247. strcpy(mountPoint, i->mountPoint);
  1248. ptr = mountPoint + ((len) ? len + 1 : 0);
  1249. end = strchr(ptr, '/');
  1250. assert(end); /* should always find a terminating '/'. */
  1251. *end = '\0';
  1252. callback(data, _fname, ptr);
  1253. __PHYSFS_smallFree(mountPoint);
  1254. } /* enumerateFromMountPoint */
  1255. /* !!! FIXME: this should report error conditions. */
  1256. void PHYSFS_enumerateFilesCallback(const char *_fname,
  1257. PHYSFS_EnumFilesCallback callback,
  1258. void *data)
  1259. {
  1260. size_t len;
  1261. char *fname;
  1262. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
  1263. BAIL_IF_MACRO(callback == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
  1264. len = strlen(_fname) + 1;
  1265. fname = (char *) __PHYSFS_smallAlloc(len);
  1266. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, ) /*0*/;
  1267. if (sanitizePlatformIndependentPath(_fname, fname))
  1268. {
  1269. DirHandle *i;
  1270. int noSyms;
  1271. __PHYSFS_platformGrabMutex(stateLock);
  1272. noSyms = !allowSymLinks;
  1273. for (i = searchPath; i != NULL; i = i->next)
  1274. {
  1275. char *arcfname = fname;
  1276. if (partOfMountPoint(i, arcfname))
  1277. enumerateFromMountPoint(i, arcfname, callback, _fname, data);
  1278. else if (verifyPath(i, &arcfname, 0))
  1279. {
  1280. i->funcs->enumerateFiles(i->opaque, arcfname, noSyms,
  1281. callback, _fname, data);
  1282. } /* else if */
  1283. } /* for */
  1284. __PHYSFS_platformReleaseMutex(stateLock);
  1285. } /* if */
  1286. __PHYSFS_smallFree(fname);
  1287. } /* PHYSFS_enumerateFilesCallback */
  1288. int PHYSFS_exists(const char *fname)
  1289. {
  1290. return(PHYSFS_getRealDir(fname) != NULL);
  1291. } /* PHYSFS_exists */
  1292. PHYSFS_sint64 PHYSFS_getLastModTime(const char *_fname)
  1293. {
  1294. PHYSFS_sint64 retval = -1;
  1295. char *fname;
  1296. size_t len;
  1297. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, -1);
  1298. len = strlen(_fname) + 1;
  1299. fname = (char *) __PHYSFS_smallAlloc(len);
  1300. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, -1);
  1301. if (sanitizePlatformIndependentPath(_fname, fname))
  1302. {
  1303. if (*fname == '\0') /* eh...punt if it's the root dir. */
  1304. retval = 1; /* !!! FIXME: Maybe this should be an error? */
  1305. else
  1306. {
  1307. DirHandle *i;
  1308. int exists = 0;
  1309. __PHYSFS_platformGrabMutex(stateLock);
  1310. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  1311. {
  1312. char *arcfname = fname;
  1313. exists = partOfMountPoint(i, arcfname);
  1314. if (exists)
  1315. retval = 1; /* !!! FIXME: What's the right value? */
  1316. else if (verifyPath(i, &arcfname, 0))
  1317. {
  1318. retval = i->funcs->getLastModTime(i->opaque, arcfname,
  1319. &exists);
  1320. } /* else if */
  1321. } /* for */
  1322. __PHYSFS_platformReleaseMutex(stateLock);
  1323. } /* else */
  1324. } /* if */
  1325. __PHYSFS_smallFree(fname);
  1326. return(retval);
  1327. } /* PHYSFS_getLastModTime */
  1328. int PHYSFS_isDirectory(const char *_fname)
  1329. {
  1330. int retval = 0;
  1331. size_t len;
  1332. char *fname;
  1333. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1334. len = strlen(_fname) + 1;
  1335. fname = (char *) __PHYSFS_smallAlloc(len);
  1336. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1337. if (!sanitizePlatformIndependentPath(_fname, fname))
  1338. retval = 0;
  1339. else if (*fname == '\0')
  1340. retval = 1; /* Root is always a dir. :) */
  1341. else
  1342. {
  1343. DirHandle *i;
  1344. int exists = 0;
  1345. __PHYSFS_platformGrabMutex(stateLock);
  1346. for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
  1347. {
  1348. char *arcfname = fname;
  1349. if ((exists = partOfMountPoint(i, arcfname)) != 0)
  1350. retval = 1;
  1351. else if (verifyPath(i, &arcfname, 0))
  1352. retval = i->funcs->isDirectory(i->opaque, arcfname, &exists);
  1353. } /* for */
  1354. __PHYSFS_platformReleaseMutex(stateLock);
  1355. } /* else */
  1356. __PHYSFS_smallFree(fname);
  1357. return(retval);
  1358. } /* PHYSFS_isDirectory */
  1359. int PHYSFS_isSymbolicLink(const char *_fname)
  1360. {
  1361. int retval = 0;
  1362. size_t len;
  1363. char *fname;
  1364. BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
  1365. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1366. len = strlen(_fname) + 1;
  1367. fname = (char *) __PHYSFS_smallAlloc(len);
  1368. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1369. if (!sanitizePlatformIndependentPath(_fname, fname))
  1370. retval = 0;
  1371. else if (*fname == '\0')
  1372. retval = 1; /* Root is never a symlink. */
  1373. else
  1374. {
  1375. DirHandle *i;
  1376. int fileExists = 0;
  1377. __PHYSFS_platformGrabMutex(stateLock);
  1378. for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
  1379. {
  1380. char *arcfname = fname;
  1381. if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
  1382. retval = 0; /* virtual dir...not a symlink. */
  1383. else if (verifyPath(i, &arcfname, 0))
  1384. retval = i->funcs->isSymLink(i->opaque, arcfname, &fileExists);
  1385. } /* for */
  1386. __PHYSFS_platformReleaseMutex(stateLock);
  1387. } /* else */
  1388. __PHYSFS_smallFree(fname);
  1389. return(retval);
  1390. } /* PHYSFS_isSymbolicLink */
  1391. static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
  1392. {
  1393. FileHandle *fh = NULL;
  1394. size_t len;
  1395. char *fname;
  1396. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1397. len = strlen(_fname) + 1;
  1398. fname = (char *) __PHYSFS_smallAlloc(len);
  1399. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1400. if (sanitizePlatformIndependentPath(_fname, fname))
  1401. {
  1402. void *opaque = NULL;
  1403. DirHandle *h = NULL;
  1404. const PHYSFS_Archiver *f;
  1405. __PHYSFS_platformGrabMutex(stateLock);
  1406. GOTO_IF_MACRO(!writeDir, ERR_NO_WRITE_DIR, doOpenWriteEnd);
  1407. h = writeDir;
  1408. GOTO_IF_MACRO(!verifyPath(h, &fname, 0), NULL, doOpenWriteEnd);
  1409. f = h->funcs;
  1410. if (appending)
  1411. opaque = f->openAppend(h->opaque, fname);
  1412. else
  1413. opaque = f->openWrite(h->opaque, fname);
  1414. GOTO_IF_MACRO(opaque == NULL, NULL, doOpenWriteEnd);
  1415. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1416. if (fh == NULL)
  1417. {
  1418. f->fileClose(opaque);
  1419. GOTO_MACRO(ERR_OUT_OF_MEMORY, doOpenWriteEnd);
  1420. } /* if */
  1421. else
  1422. {
  1423. memset(fh, '\0', sizeof (FileHandle));
  1424. fh->opaque = opaque;
  1425. fh->dirHandle = h;
  1426. fh->funcs = h->funcs;
  1427. fh->next = openWriteList;
  1428. openWriteList = fh;
  1429. } /* else */
  1430. doOpenWriteEnd:
  1431. __PHYSFS_platformReleaseMutex(stateLock);
  1432. } /* if */
  1433. __PHYSFS_smallFree(fname);
  1434. return((PHYSFS_File *) fh);
  1435. } /* doOpenWrite */
  1436. PHYSFS_File *PHYSFS_openWrite(const char *filename)
  1437. {
  1438. return(doOpenWrite(filename, 0));
  1439. } /* PHYSFS_openWrite */
  1440. PHYSFS_File *PHYSFS_openAppend(const char *filename)
  1441. {
  1442. return(doOpenWrite(filename, 1));
  1443. } /* PHYSFS_openAppend */
  1444. PHYSFS_File *PHYSFS_openRead(const char *_fname)
  1445. {
  1446. FileHandle *fh = NULL;
  1447. char *fname;
  1448. size_t len;
  1449. BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
  1450. len = strlen(_fname) + 1;
  1451. fname = (char *) __PHYSFS_smallAlloc(len);
  1452. BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
  1453. if (sanitizePlatformIndependentPath(_fname, fname))
  1454. {
  1455. int fileExists = 0;
  1456. DirHandle *i = NULL;
  1457. fvoid *opaque = NULL;
  1458. __PHYSFS_platformGrabMutex(stateLock);
  1459. GOTO_IF_MACRO(!searchPath, ERR_NO_SUCH_PATH, openReadEnd);
  1460. /* !!! FIXME: Why aren't we using a for loop here? */
  1461. i = searchPath;
  1462. do
  1463. {
  1464. char *arcfname = fname;
  1465. if (verifyPath(i, &arcfname, 0))
  1466. {
  1467. opaque = i->funcs->openRead(i->opaque, arcfname, &fileExists);
  1468. if (opaque)
  1469. break;
  1470. } /* if */
  1471. i = i->next;
  1472. } while ((i != NULL) && (!fileExists));
  1473. /* !!! FIXME: may not set an error if openRead didn't fail. */
  1474. GOTO_IF_MACRO(opaque == NULL, NULL, openReadEnd);
  1475. fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
  1476. if (fh == NULL)
  1477. {
  1478. i->funcs->fileClose(opaque);
  1479. GOTO_MACRO(ERR_OUT_OF_MEMORY, openReadEnd);
  1480. } /* if */
  1481. memset(fh, '\0', sizeof (FileHandle));
  1482. fh->opaque = opaque;
  1483. fh->forReading = 1;
  1484. fh->dirHandle = i;
  1485. fh->funcs = i->funcs;
  1486. fh->next = openReadList;
  1487. openReadList = fh;
  1488. openReadEnd:
  1489. __PHYSFS_platformReleaseMutex(stateLock);
  1490. } /* if */
  1491. __PHYSFS_smallFree(fname);
  1492. return((PHYSFS_File *) fh);
  1493. } /* PHYSFS_openRead */
  1494. static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
  1495. {
  1496. FileHandle *prev = NULL;
  1497. FileHandle *i;
  1498. int rc = 1;
  1499. for (i = *list; i != NULL; i = i->next)
  1500. {
  1501. if (i == handle) /* handle is in this list? */
  1502. {
  1503. PHYSFS_uint8 *tmp = handle->buffer;
  1504. rc = PHYSFS_flush((PHYSFS_File *) handle);
  1505. if (rc)
  1506. rc = handle->funcs->fileClose(handle->opaque);
  1507. if (!rc)
  1508. return(-1);
  1509. if (tmp != NULL) /* free any associated buffer. */
  1510. allocator.Free(tmp);
  1511. if (prev == NULL)
  1512. *list = handle->next;
  1513. else
  1514. prev->next = handle->next;
  1515. allocator.Free(handle);
  1516. return(1);
  1517. } /* if */
  1518. prev = i;
  1519. } /* for */
  1520. return(0);
  1521. } /* closeHandleInOpenList */
  1522. int PHYSFS_close(PHYSFS_File *_handle)
  1523. {
  1524. FileHandle *handle = (FileHandle *) _handle;
  1525. int rc;
  1526. __PHYSFS_platformGrabMutex(stateLock);
  1527. /* -1 == close failure. 0 == not found. 1 == success. */
  1528. rc = closeHandleInOpenList(&openReadList, handle);
  1529. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1530. if (!rc)
  1531. {
  1532. rc = closeHandleInOpenList(&openWriteList, handle);
  1533. BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
  1534. } /* if */
  1535. __PHYSFS_platformReleaseMutex(stateLock);
  1536. BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
  1537. return(1);
  1538. } /* PHYSFS_close */
  1539. static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
  1540. PHYSFS_uint32 objSize,
  1541. PHYSFS_uint32 objCount)
  1542. {
  1543. PHYSFS_sint64 retval = 0;
  1544. PHYSFS_uint32 remainder = 0;
  1545. while (objCount > 0)
  1546. {
  1547. PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
  1548. PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
  1549. PHYSFS_uint32 copied;
  1550. if (buffered == 0) /* need to refill buffer? */
  1551. {
  1552. PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
  1553. 1, fh->bufsize);
  1554. if (rc <= 0)
  1555. {
  1556. fh->bufpos -= remainder;
  1557. return(((rc == -1) && (retval == 0)) ? -1 : retval);
  1558. } /* if */
  1559. buffered = fh->buffill = (PHYSFS_uint32) rc;
  1560. fh->bufpos = 0;
  1561. } /* if */
  1562. if (buffered > mustread)
  1563. buffered = (PHYSFS_uint32) mustread;
  1564. memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
  1565. buffer = ((PHYSFS_uint8 *) buffer) + buffered;
  1566. fh->bufpos += buffered;
  1567. buffered += remainder; /* take remainder into account. */
  1568. copied = (buffered / objSize);
  1569. remainder = (buffered % objSize);
  1570. retval += copied;
  1571. objCount -= copied;
  1572. } /* while */
  1573. return(retval);
  1574. } /* doBufferedRead */
  1575. PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
  1576. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1577. {
  1578. FileHandle *fh = (FileHandle *) handle;
  1579. BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
  1580. if (fh->buffer != NULL)
  1581. return(doBufferedRead(fh, buffer, objSize, objCount));
  1582. return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
  1583. } /* PHYSFS_read */
  1584. static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
  1585. PHYSFS_uint32 objSize,
  1586. PHYSFS_uint32 objCount)
  1587. {
  1588. FileHandle *fh = (FileHandle *) handle;
  1589. /* whole thing fits in the buffer? */
  1590. if (fh->buffill + (objSize * objCount) < fh->bufsize)
  1591. {
  1592. memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
  1593. fh->buffill += (objSize * objCount);
  1594. return(objCount);
  1595. } /* if */
  1596. /* would overflow buffer. Flush and then write the new objects, too. */
  1597. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
  1598. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1599. } /* doBufferedWrite */
  1600. PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
  1601. PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
  1602. {
  1603. FileHandle *fh = (FileHandle *) handle;
  1604. BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
  1605. if (fh->buffer != NULL)
  1606. return(doBufferedWrite(handle, buffer, objSize, objCount));
  1607. return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
  1608. } /* PHYSFS_write */
  1609. int PHYSFS_eof(PHYSFS_File *handle)
  1610. {
  1611. FileHandle *fh = (FileHandle *) handle;
  1612. if (!fh->forReading) /* never EOF on files opened for write/append. */
  1613. return(0);
  1614. /* eof if buffer is empty and archiver says so. */
  1615. return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
  1616. } /* PHYSFS_eof */
  1617. PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
  1618. {
  1619. FileHandle *fh = (FileHandle *) handle;
  1620. PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
  1621. PHYSFS_sint64 retval = fh->forReading ?
  1622. (pos - fh->buffill) + fh->bufpos :
  1623. (pos + fh->buffill);
  1624. return(retval);
  1625. } /* PHYSFS_tell */
  1626. int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
  1627. {
  1628. FileHandle *fh = (FileHandle *) handle;
  1629. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1630. if (fh->buffer && fh->forReading)
  1631. {
  1632. /* avoid throwing away our precious buffer if seeking within it. */
  1633. PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
  1634. if ( /* seeking within the already-buffered range? */
  1635. ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
  1636. || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
  1637. {
  1638. fh->bufpos += (PHYSFS_uint32) offset;
  1639. return(1); /* successful seek */
  1640. } /* if */
  1641. } /* if */
  1642. /* we have to fall back to a 'raw' seek. */
  1643. fh->buffill = fh->bufpos = 0;
  1644. return(fh->funcs->seek(fh->opaque, pos));
  1645. } /* PHYSFS_seek */
  1646. PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
  1647. {
  1648. FileHandle *fh = (FileHandle *) handle;
  1649. return(fh->funcs->fileLength(fh->opaque));
  1650. } /* PHYSFS_filelength */
  1651. int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
  1652. {
  1653. FileHandle *fh = (FileHandle *) handle;
  1654. PHYSFS_uint32 bufsize;
  1655. /* !!! FIXME: Unlocalized string. */
  1656. BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
  1657. bufsize = (PHYSFS_uint32) _bufsize;
  1658. BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
  1659. /*
  1660. * For reads, we need to move the file pointer to where it would be
  1661. * if we weren't buffering, so that the next read will get the
  1662. * right chunk of stuff from the file. PHYSFS_flush() handles writes.
  1663. */
  1664. if ((fh->forReading) && (fh->buffill != fh->bufpos))
  1665. {
  1666. PHYSFS_uint64 pos;
  1667. PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
  1668. BAIL_IF_MACRO(curpos == -1, NULL, 0);
  1669. pos = ((curpos - fh->buffill) + fh->bufpos);
  1670. BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
  1671. } /* if */
  1672. if (bufsize == 0) /* delete existing buffer. */
  1673. {
  1674. if (fh->buffer != NULL)
  1675. {
  1676. allocator.Free(fh->buffer);
  1677. fh->buffer = NULL;
  1678. } /* if */
  1679. } /* if */
  1680. else
  1681. {
  1682. PHYSFS_uint8 *newbuf;
  1683. newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
  1684. BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
  1685. fh->buffer = newbuf;
  1686. } /* else */
  1687. fh->bufsize = bufsize;
  1688. fh->buffill = fh->bufpos = 0;
  1689. return(1);
  1690. } /* PHYSFS_setBuffer */
  1691. int PHYSFS_flush(PHYSFS_File *handle)
  1692. {
  1693. FileHandle *fh = (FileHandle *) handle;
  1694. PHYSFS_sint64 rc;
  1695. if ((fh->forReading) || (fh->bufpos == fh->buffill))
  1696. return(1); /* open for read or buffer empty are successful no-ops. */
  1697. /* dump buffer to disk. */
  1698. rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
  1699. fh->buffill - fh->bufpos, 1);
  1700. BAIL_IF_MACRO(rc <= 0, NULL, 0);
  1701. fh->bufpos = fh->buffill = 0;
  1702. return(1);
  1703. } /* PHYSFS_flush */
  1704. int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
  1705. {
  1706. BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
  1707. externalAllocator = (a != NULL);
  1708. if (externalAllocator)
  1709. memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
  1710. return(1);
  1711. } /* PHYSFS_setAllocator */
  1712. static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
  1713. {
  1714. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1715. #undef malloc
  1716. return(malloc((size_t) s));
  1717. } /* mallocAllocatorMalloc */
  1718. static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
  1719. {
  1720. BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
  1721. #undef realloc
  1722. return(realloc(ptr, (size_t) s));
  1723. } /* mallocAllocatorRealloc */
  1724. static void mallocAllocatorFree(void *ptr)
  1725. {
  1726. #undef free
  1727. free(ptr);
  1728. } /* mallocAllocatorFree */
  1729. static void setDefaultAllocator(void)
  1730. {
  1731. assert(!externalAllocator);
  1732. if (!__PHYSFS_platformSetDefaultAllocator(&allocator))
  1733. {
  1734. allocator.Init = NULL;
  1735. allocator.Deinit = NULL;
  1736. allocator.Malloc = mallocAllocatorMalloc;
  1737. allocator.Realloc = mallocAllocatorRealloc;
  1738. allocator.Free = mallocAllocatorFree;
  1739. } /* if */
  1740. } /* setDefaultAllocator */
  1741. void *__PHYSFS_initSmallAlloc(void *ptr, PHYSFS_uint64 len)
  1742. {
  1743. const char useHeap = ((ptr == NULL) ? 1 : 0);
  1744. if (useHeap) /* too large for stack allocation or alloca() failed. */
  1745. ptr = allocator.Malloc(len+1);
  1746. if (ptr != NULL)
  1747. {
  1748. char *retval = (char *) ptr;
  1749. /*printf("%s alloc'd (%d) bytes at (%p).\n",
  1750. useHeap ? "heap" : "stack", (int) len, ptr);*/
  1751. *retval = useHeap;
  1752. return(retval+1);
  1753. } /* if */
  1754. return(NULL); /* allocation failed. */
  1755. } /* __PHYSFS_initSmallAlloc */
  1756. void __PHYSFS_smallFree(void *ptr)
  1757. {
  1758. if (ptr != NULL)
  1759. {
  1760. char *block = ((char *) ptr) - 1;
  1761. const char useHeap = *block;
  1762. if (useHeap)
  1763. allocator.Free(block);
  1764. /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
  1765. } /* if */
  1766. } /* __PHYSFS_smallFree */
  1767. /* end of physfs.c ... */