Upload 2.0.2
[physicsfs] / physfs.c
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
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include "physfs.h"
15
16 #define __PHYSICSFS_INTERNAL__
17 #include "physfs_internal.h"
18
19
20 typedef struct __PHYSFS_DIRHANDLE__
21 {
22     void *opaque;  /* Instance data unique to the archiver. */
23     char *dirName;  /* Path to archive in platform-dependent notation. */
24     char *mountPoint; /* Mountpoint in virtual file tree. */
25     const PHYSFS_Archiver *funcs;  /* Ptr to archiver info for this handle. */
26     struct __PHYSFS_DIRHANDLE__ *next;  /* linked list stuff. */
27 } DirHandle;
28
29
30 typedef struct __PHYSFS_FILEHANDLE__
31 {
32     void *opaque;  /* Instance data unique to the archiver for this file. */
33     PHYSFS_uint8 forReading; /* Non-zero if reading, zero if write/append */
34     const DirHandle *dirHandle;  /* Archiver instance that created this */
35     const PHYSFS_Archiver *funcs;  /* Ptr to archiver info for this handle. */
36     PHYSFS_uint8 *buffer;  /* Buffer, if set (NULL otherwise). Don't touch! */
37     PHYSFS_uint32 bufsize;  /* Bufsize, if set (0 otherwise). Don't touch! */
38     PHYSFS_uint32 buffill;  /* Buffer fill size. Don't touch! */
39     PHYSFS_uint32 bufpos;  /* Buffer position. Don't touch! */
40     struct __PHYSFS_FILEHANDLE__ *next;  /* linked list stuff. */
41 } FileHandle;
42
43
44 typedef struct __PHYSFS_ERRMSGTYPE__
45 {
46     PHYSFS_uint64 tid;
47     int errorAvailable;
48     char errorString[80];
49     struct __PHYSFS_ERRMSGTYPE__ *next;
50 } ErrMsg;
51
52
53 /* The various i/o drivers...some of these may not be compiled in. */
54 extern const PHYSFS_ArchiveInfo    __PHYSFS_ArchiveInfo_ZIP;
55 extern const PHYSFS_Archiver       __PHYSFS_Archiver_ZIP;
56 extern const PHYSFS_ArchiveInfo    __PHYSFS_ArchiveInfo_LZMA;
57 extern const PHYSFS_Archiver       __PHYSFS_Archiver_LZMA;
58 extern const PHYSFS_ArchiveInfo    __PHYSFS_ArchiveInfo_GRP;
59 extern const PHYSFS_Archiver       __PHYSFS_Archiver_GRP;
60 extern const PHYSFS_ArchiveInfo    __PHYSFS_ArchiveInfo_QPAK;
61 extern const PHYSFS_Archiver       __PHYSFS_Archiver_QPAK;
62 extern const PHYSFS_ArchiveInfo    __PHYSFS_ArchiveInfo_HOG;
63 extern const PHYSFS_Archiver       __PHYSFS_Archiver_HOG;
64 extern const PHYSFS_ArchiveInfo    __PHYSFS_ArchiveInfo_MVL;
65 extern const PHYSFS_Archiver       __PHYSFS_Archiver_MVL;
66 extern const PHYSFS_ArchiveInfo    __PHYSFS_ArchiveInfo_WAD;
67 extern const PHYSFS_Archiver       __PHYSFS_Archiver_WAD;
68 extern const PHYSFS_Archiver       __PHYSFS_Archiver_DIR;
69
70
71 static const PHYSFS_ArchiveInfo *supported_types[] =
72 {
73 #if (defined PHYSFS_SUPPORTS_ZIP)
74     &__PHYSFS_ArchiveInfo_ZIP,
75 #endif
76 #if (defined PHYSFS_SUPPORTS_7Z)
77     &__PHYSFS_ArchiveInfo_LZMA,
78 #endif
79 #if (defined PHYSFS_SUPPORTS_GRP)
80     &__PHYSFS_ArchiveInfo_GRP,
81 #endif
82 #if (defined PHYSFS_SUPPORTS_QPAK)
83     &__PHYSFS_ArchiveInfo_QPAK,
84 #endif
85 #if (defined PHYSFS_SUPPORTS_HOG)
86     &__PHYSFS_ArchiveInfo_HOG,
87 #endif
88 #if (defined PHYSFS_SUPPORTS_MVL)
89     &__PHYSFS_ArchiveInfo_MVL,
90 #endif
91 #if (defined PHYSFS_SUPPORTS_WAD)
92     &__PHYSFS_ArchiveInfo_WAD,
93 #endif
94     NULL
95 };
96
97 static const PHYSFS_Archiver *archivers[] =
98 {
99     &__PHYSFS_Archiver_DIR,
100 #if (defined PHYSFS_SUPPORTS_ZIP)
101     &__PHYSFS_Archiver_ZIP,
102 #endif
103 #if (defined PHYSFS_SUPPORTS_7Z)
104     &__PHYSFS_Archiver_LZMA,
105 #endif
106 #if (defined PHYSFS_SUPPORTS_GRP)
107     &__PHYSFS_Archiver_GRP,
108 #endif
109 #if (defined PHYSFS_SUPPORTS_QPAK)
110     &__PHYSFS_Archiver_QPAK,
111 #endif
112 #if (defined PHYSFS_SUPPORTS_HOG)
113     &__PHYSFS_Archiver_HOG,
114 #endif
115 #if (defined PHYSFS_SUPPORTS_MVL)
116     &__PHYSFS_Archiver_MVL,
117 #endif
118 #if (defined PHYSFS_SUPPORTS_WAD)
119     &__PHYSFS_Archiver_WAD,
120 #endif
121     NULL
122 };
123
124
125
126 /* General PhysicsFS state ... */
127 static int initialized = 0;
128 static ErrMsg *errorMessages = NULL;
129 static DirHandle *searchPath = NULL;
130 static DirHandle *writeDir = NULL;
131 static FileHandle *openWriteList = NULL;
132 static FileHandle *openReadList = NULL;
133 static char *baseDir = NULL;
134 static char *userDir = NULL;
135 static int allowSymLinks = 0;
136
137 /* mutexes ... */
138 static void *errorLock = NULL;     /* protects error message list.        */
139 static void *stateLock = NULL;     /* protects other PhysFS static state. */
140
141 /* allocator ... */
142 static int externalAllocator = 0;
143 PHYSFS_Allocator allocator;
144
145
146 /* functions ... */
147
148 typedef struct
149 {
150     char **list;
151     PHYSFS_uint32 size;
152     const char *errorstr;
153 } EnumStringListCallbackData;
154
155 static void enumStringListCallback(void *data, const char *str)
156 {
157     void *ptr;
158     char *newstr;
159     EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
160
161     if (pecd->errorstr)
162         return;
163
164     ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
165     newstr = (char *) allocator.Malloc(strlen(str) + 1);
166     if (ptr != NULL)
167         pecd->list = (char **) ptr;
168
169     if ((ptr == NULL) || (newstr == NULL))
170     {
171         pecd->errorstr = ERR_OUT_OF_MEMORY;
172         pecd->list[pecd->size] = NULL;
173         PHYSFS_freeList(pecd->list);
174         return;
175     } /* if */
176
177     strcpy(newstr, str);
178     pecd->list[pecd->size] = newstr;
179     pecd->size++;
180 } /* enumStringListCallback */
181
182
183 static char **doEnumStringList(void (*func)(PHYSFS_StringCallback, void *))
184 {
185     EnumStringListCallbackData ecd;
186     memset(&ecd, '\0', sizeof (ecd));
187     ecd.list = (char **) allocator.Malloc(sizeof (char *));
188     BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
189     func(enumStringListCallback, &ecd);
190     BAIL_IF_MACRO(ecd.errorstr != NULL, ecd.errorstr, NULL);
191     ecd.list[ecd.size] = NULL;
192     return(ecd.list);
193 } /* doEnumStringList */
194
195
196 static void __PHYSFS_bubble_sort(void *a, PHYSFS_uint32 lo, PHYSFS_uint32 hi,
197                          int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
198                          void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
199 {
200     PHYSFS_uint32 i;
201     int sorted;
202
203     do
204     {
205         sorted = 1;
206         for (i = lo; i < hi; i++)
207         {
208             if (cmpfn(a, i, i + 1) > 0)
209             {
210                 swapfn(a, i, i + 1);
211                 sorted = 0;
212             } /* if */
213         } /* for */
214     } while (!sorted);
215 } /* __PHYSFS_bubble_sort */
216
217
218 static void __PHYSFS_quick_sort(void *a, PHYSFS_uint32 lo, PHYSFS_uint32 hi,
219                          int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
220                          void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
221 {
222     PHYSFS_uint32 i;
223     PHYSFS_uint32 j;
224     PHYSFS_uint32 v;
225
226     if ((hi - lo) <= PHYSFS_QUICKSORT_THRESHOLD)
227         __PHYSFS_bubble_sort(a, lo, hi, cmpfn, swapfn);
228     else
229     {
230         i = (hi + lo) / 2;
231
232         if (cmpfn(a, lo, i) > 0) swapfn(a, lo, i);
233         if (cmpfn(a, lo, hi) > 0) swapfn(a, lo, hi);
234         if (cmpfn(a, i, hi) > 0) swapfn(a, i, hi);
235
236         j = hi - 1;
237         swapfn(a, i, j);
238         i = lo;
239         v = j;
240         while (1)
241         {
242             while(cmpfn(a, ++i, v) < 0) { /* do nothing */ }
243             while(cmpfn(a, --j, v) > 0) { /* do nothing */ }
244             if (j < i)
245                 break;
246             swapfn(a, i, j);
247         } /* while */
248         if (i != (hi-1))
249             swapfn(a, i, hi-1);
250         __PHYSFS_quick_sort(a, lo, j, cmpfn, swapfn);
251         __PHYSFS_quick_sort(a, i+1, hi, cmpfn, swapfn);
252     } /* else */
253 } /* __PHYSFS_quick_sort */
254
255
256 void __PHYSFS_sort(void *entries, PHYSFS_uint32 max,
257                    int (*cmpfn)(void *, PHYSFS_uint32, PHYSFS_uint32),
258                    void (*swapfn)(void *, PHYSFS_uint32, PHYSFS_uint32))
259 {
260     /*
261      * Quicksort w/ Bubblesort fallback algorithm inspired by code from here:
262      *   http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
263      */
264     __PHYSFS_quick_sort(entries, 0, max - 1, cmpfn, swapfn);
265 } /* __PHYSFS_sort */
266
267
268 static ErrMsg *findErrorForCurrentThread(void)
269 {
270     ErrMsg *i;
271     PHYSFS_uint64 tid;
272
273     if (errorLock != NULL)
274         __PHYSFS_platformGrabMutex(errorLock);
275
276     if (errorMessages != NULL)
277     {
278         tid = __PHYSFS_platformGetThreadID();
279
280         for (i = errorMessages; i != NULL; i = i->next)
281         {
282             if (i->tid == tid)
283             {
284                 if (errorLock != NULL)
285                     __PHYSFS_platformReleaseMutex(errorLock);
286                 return(i);
287             } /* if */
288         } /* for */
289     } /* if */
290
291     if (errorLock != NULL)
292         __PHYSFS_platformReleaseMutex(errorLock);
293
294     return(NULL);   /* no error available. */
295 } /* findErrorForCurrentThread */
296
297
298 void __PHYSFS_setError(const char *str)
299 {
300     ErrMsg *err;
301
302     if (str == NULL)
303         return;
304
305     err = findErrorForCurrentThread();
306
307     if (err == NULL)
308     {
309         err = (ErrMsg *) allocator.Malloc(sizeof (ErrMsg));
310         if (err == NULL)
311             return;   /* uhh...? */
312
313         memset((void *) err, '\0', sizeof (ErrMsg));
314         err->tid = __PHYSFS_platformGetThreadID();
315
316         if (errorLock != NULL)
317             __PHYSFS_platformGrabMutex(errorLock);
318
319         err->next = errorMessages;
320         errorMessages = err;
321
322         if (errorLock != NULL)
323             __PHYSFS_platformReleaseMutex(errorLock);
324     } /* if */
325
326     err->errorAvailable = 1;
327     strncpy(err->errorString, str, sizeof (err->errorString));
328     err->errorString[sizeof (err->errorString) - 1] = '\0';
329 } /* __PHYSFS_setError */
330
331
332 const char *PHYSFS_getLastError(void)
333 {
334     ErrMsg *err = findErrorForCurrentThread();
335
336     if ((err == NULL) || (!err->errorAvailable))
337         return(NULL);
338
339     err->errorAvailable = 0;
340     return(err->errorString);
341 } /* PHYSFS_getLastError */
342
343
344 /* MAKE SURE that errorLock is held before calling this! */
345 static void freeErrorMessages(void)
346 {
347     ErrMsg *i;
348     ErrMsg *next;
349
350     for (i = errorMessages; i != NULL; i = next)
351     {
352         next = i->next;
353         allocator.Free(i);
354     } /* for */
355
356     errorMessages = NULL;
357 } /* freeErrorMessages */
358
359
360 void PHYSFS_getLinkedVersion(PHYSFS_Version *ver)
361 {
362     if (ver != NULL)
363     {
364         ver->major = PHYSFS_VER_MAJOR;
365         ver->minor = PHYSFS_VER_MINOR;
366         ver->patch = PHYSFS_VER_PATCH;
367     } /* if */
368 } /* PHYSFS_getLinkedVersion */
369
370
371 static const char *find_filename_extension(const char *fname)
372 {
373     const char *retval = strchr(fname, '.');
374     const char *p = retval;
375
376     while (p != NULL)
377     {
378         p = strchr(p + 1, '.');
379         if (p != NULL)
380             retval = p;
381     } /* while */
382
383     if (retval != NULL)
384         retval++;  /* skip '.' */
385
386     return(retval);
387 } /* find_filename_extension */
388
389
390 static DirHandle *tryOpenDir(const PHYSFS_Archiver *funcs,
391                              const char *d, int forWriting)
392 {
393     DirHandle *retval = NULL;
394     if (funcs->isArchive(d, forWriting))
395     {
396         void *opaque = funcs->openArchive(d, forWriting);
397         if (opaque != NULL)
398         {
399             retval = (DirHandle *) allocator.Malloc(sizeof (DirHandle));
400             if (retval == NULL)
401                 funcs->dirClose(opaque);
402             else
403             {
404                 memset(retval, '\0', sizeof (DirHandle));
405                 retval->mountPoint = NULL;
406                 retval->funcs = funcs;
407                 retval->opaque = opaque;
408             } /* else */
409         } /* if */
410     } /* if */
411
412     return(retval);
413 } /* tryOpenDir */
414
415
416 static DirHandle *openDirectory(const char *d, int forWriting)
417 {
418     DirHandle *retval = NULL;
419     const PHYSFS_Archiver **i;
420     const char *ext;
421
422     BAIL_IF_MACRO(!__PHYSFS_platformExists(d), ERR_NO_SUCH_FILE, NULL);
423
424     ext = find_filename_extension(d);
425     if (ext != NULL)
426     {
427         /* Look for archivers with matching file extensions first... */
428         for (i = archivers; (*i != NULL) && (retval == NULL); i++)
429         {
430             if (__PHYSFS_stricmpASCII(ext, (*i)->info->extension) == 0)
431                 retval = tryOpenDir(*i, d, forWriting);
432         } /* for */
433
434         /* failing an exact file extension match, try all the others... */
435         for (i = archivers; (*i != NULL) && (retval == NULL); i++)
436         {
437             if (__PHYSFS_stricmpASCII(ext, (*i)->info->extension) != 0)
438                 retval = tryOpenDir(*i, d, forWriting);
439         } /* for */
440     } /* if */
441
442     else  /* no extension? Try them all. */
443     {
444         for (i = archivers; (*i != NULL) && (retval == NULL); i++)
445             retval = tryOpenDir(*i, d, forWriting);
446     } /* else */
447
448     BAIL_IF_MACRO(retval == NULL, ERR_UNSUPPORTED_ARCHIVE, NULL);
449     return(retval);
450 } /* openDirectory */
451
452
453 /*
454  * Make a platform-independent path string sane. Doesn't actually check the
455  *  file hierarchy, it just cleans up the string.
456  *  (dst) must be a buffer at least as big as (src), as this is where the
457  *  cleaned up string is deposited.
458  * If there are illegal bits in the path (".." entries, etc) then we
459  *  return zero and (dst) is undefined. Non-zero if the path was sanitized.
460  */
461 static int sanitizePlatformIndependentPath(const char *src, char *dst)
462 {
463     char *prev;
464     char ch;
465
466     while (*src == '/')  /* skip initial '/' chars... */
467         src++;
468
469     prev = dst;
470     do
471     {
472         ch = *(src++);
473
474         if ((ch == ':') || (ch == '\\'))  /* illegal chars in a physfs path. */
475             BAIL_MACRO(ERR_INSECURE_FNAME, 0);
476
477         if (ch == '/')   /* path separator. */
478         {
479             *dst = '\0';  /* "." and ".." are illegal pathnames. */
480             if ((strcmp(prev, ".") == 0) || (strcmp(prev, "..") == 0))
481                 BAIL_MACRO(ERR_INSECURE_FNAME, 0);
482
483             while (*src == '/')   /* chop out doubles... */
484                 src++;
485
486             if (*src == '\0') /* ends with a pathsep? */
487                 break;  /* we're done, don't add final pathsep to dst. */
488
489             prev = dst + 1;
490         } /* if */
491
492         *(dst++) = ch;
493     } while (ch != '\0');
494
495     return(1);
496 } /* sanitizePlatformIndependentPath */
497
498
499 /*
500  * Figure out if (fname) is part of (h)'s mountpoint. (fname) must be an
501  *  output from sanitizePlatformIndependentPath(), so that it is in a known
502  *  state.
503  *
504  * This only finds legitimate segments of a mountpoint. If the mountpoint is
505  *  "/a/b/c" and (fname) is "/a/b/c", "/", or "/a/b/c/d", then the results are
506  *  all zero. "/a/b" will succeed, though.
507  */
508 static int partOfMountPoint(DirHandle *h, char *fname)
509 {
510     /* !!! FIXME: This code feels gross. */
511     int rc;
512     size_t len, mntpntlen;
513
514     if (h->mountPoint == NULL)
515         return(0);
516     else if (*fname == '\0')
517         return(1);
518
519     len = strlen(fname);
520     mntpntlen = strlen(h->mountPoint);
521     if (len > mntpntlen)  /* can't be a subset of mountpoint. */
522         return(0);
523
524     /* if true, must be not a match or a complete match, but not a subset. */
525     if ((len + 1) == mntpntlen)
526         return(0);
527
528     rc = strncmp(fname, h->mountPoint, len); /* !!! FIXME: case insensitive? */
529     if (rc != 0)
530         return(0);  /* not a match. */
531
532     /* make sure /a/b matches /a/b/ and not /a/bc ... */
533     return(h->mountPoint[len] == '/');
534 } /* partOfMountPoint */
535
536
537 static DirHandle *createDirHandle(const char *newDir,
538                                   const char *mountPoint,
539                                   int forWriting)
540 {
541     DirHandle *dirHandle = NULL;
542     char *tmpmntpnt = NULL;
543
544     GOTO_IF_MACRO(!newDir, ERR_INVALID_ARGUMENT, badDirHandle);
545     if (mountPoint != NULL)
546     {
547         const size_t len = strlen(mountPoint) + 1;
548         tmpmntpnt = (char *) __PHYSFS_smallAlloc(len);
549         GOTO_IF_MACRO(!tmpmntpnt, ERR_OUT_OF_MEMORY, badDirHandle);
550         if (!sanitizePlatformIndependentPath(mountPoint, tmpmntpnt))
551             goto badDirHandle;
552         mountPoint = tmpmntpnt;  /* sanitized version. */
553     } /* if */
554
555     dirHandle = openDirectory(newDir, forWriting);
556     GOTO_IF_MACRO(!dirHandle, NULL, badDirHandle);
557
558     dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
559     GOTO_IF_MACRO(!dirHandle->dirName, ERR_OUT_OF_MEMORY, badDirHandle);
560     strcpy(dirHandle->dirName, newDir);
561
562     if ((mountPoint != NULL) && (*mountPoint != '\0'))
563     {
564         dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
565         GOTO_IF_MACRO(!dirHandle->mountPoint, ERR_OUT_OF_MEMORY, badDirHandle);
566         strcpy(dirHandle->mountPoint, mountPoint);
567         strcat(dirHandle->mountPoint, "/");
568     } /* if */
569
570     __PHYSFS_smallFree(tmpmntpnt);
571     return(dirHandle);
572
573 badDirHandle:
574     if (dirHandle != NULL)
575     {
576         dirHandle->funcs->dirClose(dirHandle->opaque);
577         allocator.Free(dirHandle->dirName);
578         allocator.Free(dirHandle->mountPoint);
579         allocator.Free(dirHandle);
580     } /* if */
581
582     __PHYSFS_smallFree(tmpmntpnt);
583     return(NULL);
584 } /* createDirHandle */
585
586
587 /* MAKE SURE you've got the stateLock held before calling this! */
588 static int freeDirHandle(DirHandle *dh, FileHandle *openList)
589 {
590     FileHandle *i;
591
592     if (dh == NULL)
593         return(1);
594
595     for (i = openList; i != NULL; i = i->next)
596         BAIL_IF_MACRO(i->dirHandle == dh, ERR_FILES_STILL_OPEN, 0);
597
598     dh->funcs->dirClose(dh->opaque);
599     allocator.Free(dh->dirName);
600     allocator.Free(dh->mountPoint);
601     allocator.Free(dh);
602     return(1);
603 } /* freeDirHandle */
604
605
606 static char *calculateUserDir(void)
607 {
608     char *retval = __PHYSFS_platformGetUserDir();
609     if (retval != NULL)
610     {
611         /* make sure it really exists and is normalized. */
612         char *ptr = __PHYSFS_platformRealPath(retval);
613         allocator.Free(retval);
614         retval = ptr;
615     } /* if */
616
617     if (retval == NULL)
618     {
619         const char *dirsep = PHYSFS_getDirSeparator();
620         const char *uname = __PHYSFS_platformGetUserName();
621         const char *str = (uname != NULL) ? uname : "default";
622
623         retval = (char *) allocator.Malloc(strlen(baseDir) + strlen(str) +
624                                            strlen(dirsep) + 6);
625
626         if (retval == NULL)
627             __PHYSFS_setError(ERR_OUT_OF_MEMORY);
628         else
629             sprintf(retval, "%susers%s%s", baseDir, dirsep, str);
630
631         allocator.Free((void *) uname);
632     } /* else */
633
634     return(retval);
635 } /* calculateUserDir */
636
637
638 static int appendDirSep(char **dir)
639 {
640     const char *dirsep = PHYSFS_getDirSeparator();
641     char *ptr;
642
643     if (strcmp((*dir + strlen(*dir)) - strlen(dirsep), dirsep) == 0)
644         return(1);
645
646     ptr = (char *) allocator.Realloc(*dir, strlen(*dir) + strlen(dirsep) + 1);
647     if (!ptr)
648     {
649         allocator.Free(*dir);
650         return(0);
651     } /* if */
652
653     strcat(ptr, dirsep);
654     *dir = ptr;
655     return(1);
656 } /* appendDirSep */
657
658
659 static char *calculateBaseDir(const char *argv0)
660 {
661     char *retval = NULL;
662     const char *dirsep = NULL;
663     char *ptr = NULL;
664
665     /* Give the platform layer first shot at this. */
666     retval = __PHYSFS_platformCalcBaseDir(argv0);
667     if (retval != NULL)
668         return(retval);
669
670     /* We need argv0 to go on. */
671     BAIL_IF_MACRO(argv0 == NULL, ERR_ARGV0_IS_NULL, NULL);
672
673     dirsep = PHYSFS_getDirSeparator();
674     if (strlen(dirsep) == 1)  /* fast path. */
675         ptr = strrchr(argv0, *dirsep);
676     else
677     {
678         ptr = strstr(argv0, dirsep);
679         if (ptr != NULL)
680         {
681             char *p = ptr;
682             while (p != NULL)
683             {
684                 ptr = p;
685                 p = strstr(p + 1, dirsep);
686             } /* while */
687         } /* if */
688     } /* else */
689
690     if (ptr != NULL)
691     {
692         size_t size = (size_t) (ptr - argv0);
693         retval = (char *) allocator.Malloc(size + 1);
694         BAIL_IF_MACRO(retval == NULL, ERR_OUT_OF_MEMORY, NULL);
695         memcpy(retval, argv0, size);
696         retval[size] = '\0';
697         return(retval);
698     } /* if */
699
700     /* argv0 wasn't helpful. */
701     BAIL_MACRO(ERR_INVALID_ARGUMENT, NULL);
702     return(NULL);
703 } /* calculateBaseDir */
704
705
706 static int initializeMutexes(void)
707 {
708     errorLock = __PHYSFS_platformCreateMutex();
709     if (errorLock == NULL)
710         goto initializeMutexes_failed;
711
712     stateLock = __PHYSFS_platformCreateMutex();
713     if (stateLock == NULL)
714         goto initializeMutexes_failed;
715
716     return(1);  /* success. */
717
718 initializeMutexes_failed:
719     if (errorLock != NULL)
720         __PHYSFS_platformDestroyMutex(errorLock);
721
722     if (stateLock != NULL)
723         __PHYSFS_platformDestroyMutex(stateLock);
724
725     errorLock = stateLock = NULL;
726     return(0);  /* failed. */
727 } /* initializeMutexes */
728
729
730 static void setDefaultAllocator(void);
731
732 int PHYSFS_init(const char *argv0)
733 {
734     char *ptr;
735
736     BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
737
738     if (!externalAllocator)
739         setDefaultAllocator();
740
741     if (allocator.Init != NULL)
742         BAIL_IF_MACRO(!allocator.Init(), NULL, 0);
743
744     BAIL_IF_MACRO(!__PHYSFS_platformInit(), NULL, 0);
745
746     BAIL_IF_MACRO(!initializeMutexes(), NULL, 0);
747
748     baseDir = calculateBaseDir(argv0);
749     BAIL_IF_MACRO(baseDir == NULL, NULL, 0);
750
751     /* !!! FIXME: only call this if we got this from argv0 (unreliable). */
752     ptr = __PHYSFS_platformRealPath(baseDir);
753     allocator.Free(baseDir);
754     BAIL_IF_MACRO(ptr == NULL, NULL, 0);
755     baseDir = ptr;
756
757     BAIL_IF_MACRO(!appendDirSep(&baseDir), NULL, 0);
758
759     userDir = calculateUserDir();
760     if ((userDir == NULL) || (!appendDirSep(&userDir)))
761     {
762         allocator.Free(baseDir);
763         baseDir = NULL;
764         return(0);
765     } /* if */
766
767     initialized = 1;
768
769     /* This makes sure that the error subsystem is initialized. */
770     __PHYSFS_setError(PHYSFS_getLastError());
771
772     return(1);
773 } /* PHYSFS_init */
774
775
776 /* MAKE SURE you hold stateLock before calling this! */
777 static int closeFileHandleList(FileHandle **list)
778 {
779     FileHandle *i;
780     FileHandle *next = NULL;
781
782     for (i = *list; i != NULL; i = next)
783     {
784         next = i->next;
785         if (!i->funcs->fileClose(i->opaque))
786         {
787             *list = i;
788             return(0);
789         } /* if */
790
791         allocator.Free(i);
792     } /* for */
793
794     *list = NULL;
795     return(1);
796 } /* closeFileHandleList */
797
798
799 /* MAKE SURE you hold the stateLock before calling this! */
800 static void freeSearchPath(void)
801 {
802     DirHandle *i;
803     DirHandle *next = NULL;
804
805     closeFileHandleList(&openReadList);
806
807     if (searchPath != NULL)
808     {
809         for (i = searchPath; i != NULL; i = next)
810         {
811             next = i->next;
812             freeDirHandle(i, openReadList);
813         } /* for */
814         searchPath = NULL;
815     } /* if */
816 } /* freeSearchPath */
817
818
819 int PHYSFS_deinit(void)
820 {
821     BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
822     BAIL_IF_MACRO(!__PHYSFS_platformDeinit(), NULL, 0);
823
824     closeFileHandleList(&openWriteList);
825     BAIL_IF_MACRO(!PHYSFS_setWriteDir(NULL), ERR_FILES_STILL_OPEN, 0);
826
827     freeSearchPath();
828     freeErrorMessages();
829
830     if (baseDir != NULL)
831     {
832         allocator.Free(baseDir);
833         baseDir = NULL;
834     } /* if */
835
836     if (userDir != NULL)
837     {
838         allocator.Free(userDir);
839         userDir = NULL;
840     } /* if */
841
842     allowSymLinks = 0;
843     initialized = 0;
844
845     __PHYSFS_platformDestroyMutex(errorLock);
846     __PHYSFS_platformDestroyMutex(stateLock);
847
848     if (allocator.Deinit != NULL)
849         allocator.Deinit();
850
851     errorLock = stateLock = NULL;
852     return(1);
853 } /* PHYSFS_deinit */
854
855
856 int PHYSFS_isInit(void)
857 {
858     return(initialized);
859 } /* PHYSFS_isInit */
860
861
862 const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
863 {
864     return(supported_types);
865 } /* PHYSFS_supportedArchiveTypes */
866
867
868 void PHYSFS_freeList(void *list)
869 {
870     void **i;
871     for (i = (void **) list; *i != NULL; i++)
872         allocator.Free(*i);
873
874     allocator.Free(list);
875 } /* PHYSFS_freeList */
876
877
878 const char *PHYSFS_getDirSeparator(void)
879 {
880     return(__PHYSFS_platformDirSeparator);
881 } /* PHYSFS_getDirSeparator */
882
883
884 char **PHYSFS_getCdRomDirs(void)
885 {
886     return(doEnumStringList(__PHYSFS_platformDetectAvailableCDs));
887 } /* PHYSFS_getCdRomDirs */
888
889
890 void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
891 {
892     __PHYSFS_platformDetectAvailableCDs(callback, data);
893 } /* PHYSFS_getCdRomDirsCallback */
894
895
896 const char *PHYSFS_getBaseDir(void)
897 {
898     return(baseDir);   /* this is calculated in PHYSFS_init()... */
899 } /* PHYSFS_getBaseDir */
900
901
902 const char *PHYSFS_getUserDir(void)
903 {
904     return(userDir);   /* this is calculated in PHYSFS_init()... */
905 } /* PHYSFS_getUserDir */
906
907
908 const char *PHYSFS_getWriteDir(void)
909 {
910     const char *retval = NULL;
911
912     __PHYSFS_platformGrabMutex(stateLock);
913     if (writeDir != NULL)
914         retval = writeDir->dirName;
915     __PHYSFS_platformReleaseMutex(stateLock);
916
917     return(retval);
918 } /* PHYSFS_getWriteDir */
919
920
921 int PHYSFS_setWriteDir(const char *newDir)
922 {
923     int retval = 1;
924
925     __PHYSFS_platformGrabMutex(stateLock);
926
927     if (writeDir != NULL)
928     {
929         BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), NULL,
930                             stateLock, 0);
931         writeDir = NULL;
932     } /* if */
933
934     if (newDir != NULL)
935     {
936         writeDir = createDirHandle(newDir, NULL, 1);
937         retval = (writeDir != NULL);
938     } /* if */
939
940     __PHYSFS_platformReleaseMutex(stateLock);
941
942     return(retval);
943 } /* PHYSFS_setWriteDir */
944
945
946 int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
947 {
948     DirHandle *dh;
949     DirHandle *prev = NULL;
950     DirHandle *i;
951
952     BAIL_IF_MACRO(newDir == NULL, ERR_INVALID_ARGUMENT, 0);
953
954     if (mountPoint == NULL)
955         mountPoint = "/";
956
957     __PHYSFS_platformGrabMutex(stateLock);
958
959     for (i = searchPath; i != NULL; i = i->next)
960     {
961         /* already in search path? */
962         BAIL_IF_MACRO_MUTEX(strcmp(newDir, i->dirName)==0, NULL, stateLock, 1);
963         prev = i;
964     } /* for */
965
966     dh = createDirHandle(newDir, mountPoint, 0);
967     BAIL_IF_MACRO_MUTEX(dh == NULL, NULL, stateLock, 0);
968
969     if (appendToPath)
970     {
971         if (prev == NULL)
972             searchPath = dh;
973         else
974             prev->next = dh;
975     } /* if */
976     else
977     {
978         dh->next = searchPath;
979         searchPath = dh;
980     } /* else */
981
982     __PHYSFS_platformReleaseMutex(stateLock);
983     return(1);
984 } /* PHYSFS_mount */
985
986
987 int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
988 {
989     return(PHYSFS_mount(newDir, NULL, appendToPath));
990 } /* PHYSFS_addToSearchPath */
991
992
993 int PHYSFS_removeFromSearchPath(const char *oldDir)
994 {
995     DirHandle *i;
996     DirHandle *prev = NULL;
997     DirHandle *next = NULL;
998
999     BAIL_IF_MACRO(oldDir == NULL, ERR_INVALID_ARGUMENT, 0);
1000
1001     __PHYSFS_platformGrabMutex(stateLock);
1002     for (i = searchPath; i != NULL; i = i->next)
1003     {
1004         if (strcmp(i->dirName, oldDir) == 0)
1005         {
1006             next = i->next;
1007             BAIL_IF_MACRO_MUTEX(!freeDirHandle(i, openReadList), NULL,
1008                                 stateLock, 0);
1009
1010             if (prev == NULL)
1011                 searchPath = next;
1012             else
1013                 prev->next = next;
1014
1015             BAIL_MACRO_MUTEX(NULL, stateLock, 1);
1016         } /* if */
1017         prev = i;
1018     } /* for */
1019
1020     BAIL_MACRO_MUTEX(ERR_NOT_IN_SEARCH_PATH, stateLock, 0);
1021 } /* PHYSFS_removeFromSearchPath */
1022
1023
1024 char **PHYSFS_getSearchPath(void)
1025 {
1026     return(doEnumStringList(PHYSFS_getSearchPathCallback));
1027 } /* PHYSFS_getSearchPath */
1028
1029
1030 const char *PHYSFS_getMountPoint(const char *dir)
1031 {
1032     DirHandle *i;
1033     __PHYSFS_platformGrabMutex(stateLock);
1034     for (i = searchPath; i != NULL; i = i->next)
1035     {
1036         if (strcmp(i->dirName, dir) == 0)
1037         {
1038             const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
1039             __PHYSFS_platformReleaseMutex(stateLock);
1040             return(retval);
1041         } /* if */
1042     } /* for */
1043     __PHYSFS_platformReleaseMutex(stateLock);
1044
1045     BAIL_MACRO(ERR_NOT_IN_SEARCH_PATH, NULL);
1046 } /* PHYSFS_getMountPoint */
1047
1048
1049 void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
1050 {
1051     DirHandle *i;
1052
1053     __PHYSFS_platformGrabMutex(stateLock);
1054
1055     for (i = searchPath; i != NULL; i = i->next)
1056         callback(data, i->dirName);
1057
1058     __PHYSFS_platformReleaseMutex(stateLock);
1059 } /* PHYSFS_getSearchPathCallback */
1060
1061
1062 /* Split out to avoid stack allocation in a loop. */
1063 static void setSaneCfgAddPath(const char *i, const size_t l, const char *dirsep,
1064                               int archivesFirst)
1065 {
1066     const char *d = PHYSFS_getRealDir(i);
1067     const size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
1068     char *str = (char *) __PHYSFS_smallAlloc(allocsize);
1069     if (str != NULL)
1070     {
1071         sprintf(str, "%s%s%s", d, dirsep, i);
1072         PHYSFS_addToSearchPath(str, archivesFirst == 0);
1073         __PHYSFS_smallFree(str);
1074     } /* if */
1075 } /* setSaneCfgAddPath */
1076
1077
1078 int PHYSFS_setSaneConfig(const char *organization, const char *appName,
1079                          const char *archiveExt, int includeCdRoms,
1080                          int archivesFirst)
1081 {
1082     const char *basedir = PHYSFS_getBaseDir();
1083     const char *userdir = PHYSFS_getUserDir();
1084     const char *dirsep = PHYSFS_getDirSeparator();
1085     PHYSFS_uint64 len = 0;
1086     char *str = NULL;
1087
1088     BAIL_IF_MACRO(!initialized, ERR_NOT_INITIALIZED, 0);
1089
1090     /* set write dir... */
1091     len = (strlen(userdir) + (strlen(organization) * 2) +
1092             (strlen(appName) * 2) + (strlen(dirsep) * 3) + 2);
1093
1094     str = (char *) __PHYSFS_smallAlloc(len);
1095
1096     BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, 0);
1097     sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
1098
1099     if (!PHYSFS_setWriteDir(str))
1100     {
1101         int no_write = 0;
1102         sprintf(str, ".%s/%s", organization, appName);
1103         if ( (PHYSFS_setWriteDir(userdir)) &&
1104              (PHYSFS_mkdir(str)) )
1105         {
1106             sprintf(str, "%s.%s%s%s", userdir, organization, dirsep, appName);
1107             if (!PHYSFS_setWriteDir(str))
1108                 no_write = 1;
1109         } /* if */
1110         else
1111         {
1112             no_write = 1;
1113         } /* else */
1114
1115         if (no_write)
1116         {
1117             PHYSFS_setWriteDir(NULL);   /* just in case. */
1118             __PHYSFS_smallFree(str);
1119             BAIL_MACRO(ERR_CANT_SET_WRITE_DIR, 0);
1120         } /* if */
1121     } /* if */
1122
1123     /* Put write dir first in search path... */
1124     PHYSFS_addToSearchPath(str, 0);
1125     __PHYSFS_smallFree(str);
1126
1127         /* Put base path on search path... */
1128     PHYSFS_addToSearchPath(basedir, 1);
1129
1130         /* handle CD-ROMs... */
1131     if (includeCdRoms)
1132     {
1133         char **cds = PHYSFS_getCdRomDirs();
1134         char **i;
1135         for (i = cds; *i != NULL; i++)
1136             PHYSFS_addToSearchPath(*i, 1);
1137
1138         PHYSFS_freeList(cds);
1139     } /* if */
1140
1141         /* Root out archives, and add them to search path... */
1142     if (archiveExt != NULL)
1143     {
1144         char **rc = PHYSFS_enumerateFiles("/");
1145         char **i;
1146         size_t extlen = strlen(archiveExt);
1147         char *ext;
1148
1149         for (i = rc; *i != NULL; i++)
1150         {
1151             size_t l = strlen(*i);
1152             if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
1153             {
1154                 ext = (*i) + (l - extlen);
1155                 if (__PHYSFS_stricmpASCII(ext, archiveExt) == 0)
1156                     setSaneCfgAddPath(*i, l, dirsep, archivesFirst);
1157             } /* if */
1158         } /* for */
1159
1160         PHYSFS_freeList(rc);
1161     } /* if */
1162
1163     return(1);
1164 } /* PHYSFS_setSaneConfig */
1165
1166
1167 void PHYSFS_permitSymbolicLinks(int allow)
1168 {
1169     allowSymLinks = allow;
1170 } /* PHYSFS_permitSymbolicLinks */
1171
1172
1173 int PHYSFS_symbolicLinksPermitted(void)
1174 {
1175     return(allowSymLinks);
1176 } /* PHYSFS_symbolicLinksPermitted */
1177
1178
1179 /* string manipulation in C makes my ass itch. */
1180 char *__PHYSFS_convertToDependent(const char *prepend,
1181                                   const char *dirName,
1182                                   const char *append)
1183 {
1184     const char *dirsep = __PHYSFS_platformDirSeparator;
1185     size_t sepsize = strlen(dirsep);
1186     char *str;
1187     char *i1;
1188     char *i2;
1189     size_t allocSize;
1190
1191     while (*dirName == '/')  /* !!! FIXME: pass through sanitize function. */
1192         dirName++;
1193
1194     allocSize = strlen(dirName) + 1;
1195     if (prepend != NULL)
1196         allocSize += strlen(prepend) + sepsize;
1197     if (append != NULL)
1198         allocSize += strlen(append) + sepsize;
1199
1200     /* make sure there's enough space if the dir separator is bigger. */
1201     if (sepsize > 1)
1202     {
1203         str = (char *) dirName;
1204         do
1205         {
1206             str = strchr(str, '/');
1207             if (str != NULL)
1208             {
1209                 allocSize += (sepsize - 1);
1210                 str++;
1211             } /* if */
1212         } while (str != NULL);
1213     } /* if */
1214
1215     str = (char *) allocator.Malloc(allocSize);
1216     BAIL_IF_MACRO(str == NULL, ERR_OUT_OF_MEMORY, NULL);
1217
1218     if (prepend == NULL)
1219         *str = '\0';
1220     else
1221     {
1222         strcpy(str, prepend);
1223         strcat(str, dirsep);
1224     } /* else */
1225
1226     for (i1 = (char *) dirName, i2 = str + strlen(str); *i1; i1++, i2++)
1227     {
1228         if (*i1 == '/')
1229         {
1230             strcpy(i2, dirsep);
1231             i2 += sepsize;
1232         } /* if */
1233         else
1234         {
1235             *i2 = *i1;
1236         } /* else */
1237     } /* for */
1238     *i2 = '\0';
1239
1240     if (append)
1241     {
1242         strcat(str, dirsep);
1243         strcat(str, append);
1244     } /* if */
1245
1246     return(str);
1247 } /* __PHYSFS_convertToDependent */
1248
1249
1250 /*
1251  * Verify that (fname) (in platform-independent notation), in relation
1252  *  to (h) is secure. That means that each element of fname is checked
1253  *  for symlinks (if they aren't permitted). This also allows for quick
1254  *  rejection of files that exist outside an archive's mountpoint.
1255  *
1256  * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
1257  *  at a time), you should always pass zero for "allowMissing" for efficiency.
1258  *
1259  * (fname) must point to an output from sanitizePlatformIndependentPath(),
1260  *  since it will make sure that path names are in the right format for
1261  *  passing certain checks. It will also do checks for "insecure" pathnames
1262  *  like ".." which should be done once instead of once per archive. This also
1263  *  gives us license to treat (fname) as scratch space in this function.
1264  *
1265  * Returns non-zero if string is safe, zero if there's a security issue.
1266  *  PHYSFS_getLastError() will specify what was wrong. (*fname) will be
1267  *  updated to point past any mount point elements so it is prepared to
1268  *  be used with the archiver directly.
1269  */
1270 static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
1271 {
1272     char *fname = *_fname;
1273     int retval = 1;
1274     char *start;
1275     char *end;
1276
1277     if (*fname == '\0')  /* quick rejection. */
1278         return(1);
1279
1280     /* !!! FIXME: This codeblock sucks. */
1281     if (h->mountPoint != NULL)  /* NULL mountpoint means "/". */
1282     {
1283         size_t mntpntlen = strlen(h->mountPoint);
1284         size_t len = strlen(fname);
1285         assert(mntpntlen > 1); /* root mount points should be NULL. */
1286         /* not under the mountpoint, so skip this archive. */
1287         BAIL_IF_MACRO(len < mntpntlen-1, ERR_NO_SUCH_PATH, 0);
1288         /* !!! FIXME: Case insensitive? */
1289         retval = strncmp(h->mountPoint, fname, mntpntlen-1);
1290         BAIL_IF_MACRO(retval != 0, ERR_NO_SUCH_PATH, 0);
1291         if (len > mntpntlen-1)  /* corner case... */
1292             BAIL_IF_MACRO(fname[mntpntlen-1] != '/', ERR_NO_SUCH_PATH, 0);
1293         fname += mntpntlen-1;  /* move to start of actual archive path. */
1294         if (*fname == '/')
1295             fname++;
1296         *_fname = fname;  /* skip mountpoint for later use. */
1297         retval = 1;  /* may be reset, below. */
1298     } /* if */
1299
1300     start = fname;
1301     if (!allowSymLinks)
1302     {
1303         while (1)
1304         {
1305             int rc = 0;
1306             end = strchr(start, '/');
1307
1308             if (end != NULL) *end = '\0';
1309             rc = h->funcs->isSymLink(h->opaque, fname, &retval);
1310             if (end != NULL) *end = '/';
1311
1312             BAIL_IF_MACRO(rc, ERR_SYMLINK_DISALLOWED, 0);   /* insecure. */
1313
1314             /* break out early if path element is missing. */
1315             if (!retval)
1316             {
1317                 /*
1318                  * We need to clear it if it's the last element of the path,
1319                  *  since this might be a non-existant file we're opening
1320                  *  for writing...
1321                  */
1322                 if ((end == NULL) || (allowMissing))
1323                     retval = 1;
1324                 break;
1325             } /* if */
1326
1327             if (end == NULL)
1328                 break;
1329
1330             start = end + 1;
1331         } /* while */
1332     } /* if */
1333
1334     return(retval);
1335 } /* verifyPath */
1336
1337
1338 static int doMkdir(const char *_dname, char *dname)
1339 {
1340     DirHandle *h;
1341     char *start;
1342     char *end;
1343     int retval = 0;
1344     int exists = 1;  /* force existance check on first path element. */
1345
1346     BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_dname, dname), NULL, 0);
1347
1348     __PHYSFS_platformGrabMutex(stateLock);
1349     BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
1350     h = writeDir;
1351     BAIL_IF_MACRO_MUTEX(!verifyPath(h, &dname, 1), NULL, stateLock, 0);
1352
1353     start = dname;
1354     while (1)
1355     {
1356         end = strchr(start, '/');
1357         if (end != NULL)
1358             *end = '\0';
1359
1360         /* only check for existance if all parent dirs existed, too... */
1361         if (exists)
1362             retval = h->funcs->isDirectory(h->opaque, dname, &exists);
1363
1364         if (!exists)
1365             retval = h->funcs->mkdir(h->opaque, dname);
1366
1367         if (!retval)
1368             break;
1369
1370         if (end == NULL)
1371             break;
1372
1373         *end = '/';
1374         start = end + 1;
1375     } /* while */
1376
1377     __PHYSFS_platformReleaseMutex(stateLock);
1378     return(retval);
1379 } /* doMkdir */
1380
1381
1382 int PHYSFS_mkdir(const char *_dname)
1383 {
1384     int retval = 0;
1385     char *dname;
1386     size_t len;
1387
1388     BAIL_IF_MACRO(_dname == NULL, ERR_INVALID_ARGUMENT, 0);
1389     len = strlen(_dname) + 1;
1390     dname = (char *) __PHYSFS_smallAlloc(len);
1391     BAIL_IF_MACRO(dname == NULL, ERR_OUT_OF_MEMORY, 0);
1392     retval = doMkdir(_dname, dname);
1393     __PHYSFS_smallFree(dname);
1394     return(retval);
1395 } /* PHYSFS_mkdir */
1396
1397
1398 static int doDelete(const char *_fname, char *fname)
1399 {
1400     int retval;
1401     DirHandle *h;
1402     BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), NULL, 0);
1403
1404     __PHYSFS_platformGrabMutex(stateLock);
1405
1406     BAIL_IF_MACRO_MUTEX(writeDir == NULL, ERR_NO_WRITE_DIR, stateLock, 0);
1407     h = writeDir;
1408     BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), NULL, stateLock, 0);
1409     retval = h->funcs->remove(h->opaque, fname);
1410
1411     __PHYSFS_platformReleaseMutex(stateLock);
1412     return(retval);
1413 } /* doDelete */
1414
1415
1416 int PHYSFS_delete(const char *_fname)
1417 {
1418     int retval;
1419     char *fname;
1420     size_t len;
1421
1422     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
1423     len = strlen(_fname) + 1;
1424     fname = (char *) __PHYSFS_smallAlloc(len);
1425     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
1426     retval = doDelete(_fname, fname);
1427     __PHYSFS_smallFree(fname);
1428     return(retval);
1429 } /* PHYSFS_delete */
1430
1431
1432 const char *PHYSFS_getRealDir(const char *_fname)
1433 {
1434     const char *retval = NULL;
1435     char *fname = NULL;
1436     size_t len;
1437
1438     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, NULL);
1439     len = strlen(_fname) + 1;
1440     fname = __PHYSFS_smallAlloc(len);
1441     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, NULL);
1442     if (sanitizePlatformIndependentPath(_fname, fname))
1443     {
1444         DirHandle *i;
1445         __PHYSFS_platformGrabMutex(stateLock);
1446         for (i = searchPath; ((i != NULL) && (retval == NULL)); i = i->next)
1447         {
1448             char *arcfname = fname;
1449             if (partOfMountPoint(i, arcfname))
1450                 retval = i->dirName;
1451             else if (verifyPath(i, &arcfname, 0))
1452             {
1453                 if (i->funcs->exists(i->opaque, arcfname))
1454                     retval = i->dirName;
1455             } /* if */
1456         } /* for */
1457         __PHYSFS_platformReleaseMutex(stateLock);
1458     } /* if */
1459
1460     __PHYSFS_smallFree(fname);
1461     return(retval);
1462 } /* PHYSFS_getRealDir */
1463
1464
1465 static int locateInStringList(const char *str,
1466                               char **list,
1467                               PHYSFS_uint32 *pos)
1468 {
1469     PHYSFS_uint32 len = *pos;
1470     PHYSFS_uint32 half_len;
1471     PHYSFS_uint32 lo = 0;
1472     PHYSFS_uint32 middle;
1473     int cmp;
1474
1475     while (len > 0)
1476     {
1477         half_len = len >> 1;
1478         middle = lo + half_len;
1479         cmp = strcmp(list[middle], str);
1480
1481         if (cmp == 0)  /* it's in the list already. */
1482             return(1);
1483         else if (cmp > 0)
1484             len = half_len;
1485         else
1486         {
1487             lo = middle + 1;
1488             len -= half_len + 1;
1489         } /* else */
1490     } /* while */
1491
1492     *pos = lo;
1493     return(0);
1494 } /* locateInStringList */
1495
1496
1497 static void enumFilesCallback(void *data, const char *origdir, const char *str)
1498 {
1499     PHYSFS_uint32 pos;
1500     void *ptr;
1501     char *newstr;
1502     EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
1503
1504     /*
1505      * See if file is in the list already, and if not, insert it in there
1506      *  alphabetically...
1507      */
1508     pos = pecd->size;
1509     if (locateInStringList(str, pecd->list, &pos))
1510         return;  /* already in the list. */
1511
1512     ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
1513     newstr = (char *) allocator.Malloc(strlen(str) + 1);
1514     if (ptr != NULL)
1515         pecd->list = (char **) ptr;
1516
1517     if ((ptr == NULL) || (newstr == NULL))
1518         return;  /* better luck next time. */
1519
1520     strcpy(newstr, str);
1521
1522     if (pos != pecd->size)
1523     {
1524         memmove(&pecd->list[pos+1], &pecd->list[pos],
1525                  sizeof (char *) * ((pecd->size) - pos));
1526     } /* if */
1527
1528     pecd->list[pos] = newstr;
1529     pecd->size++;
1530 } /* enumFilesCallback */
1531
1532
1533 char **PHYSFS_enumerateFiles(const char *path)
1534 {
1535     EnumStringListCallbackData ecd;
1536     memset(&ecd, '\0', sizeof (ecd));
1537     ecd.list = (char **) allocator.Malloc(sizeof (char *));
1538     BAIL_IF_MACRO(ecd.list == NULL, ERR_OUT_OF_MEMORY, NULL);
1539     PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
1540     ecd.list[ecd.size] = NULL;
1541     return(ecd.list);
1542 } /* PHYSFS_enumerateFiles */
1543
1544
1545 /*
1546  * Broke out to seperate function so we can use stack allocation gratuitously.
1547  */
1548 static void enumerateFromMountPoint(DirHandle *i, const char *arcfname,
1549                                     PHYSFS_EnumFilesCallback callback,
1550                                     const char *_fname, void *data)
1551 {
1552     const size_t len = strlen(arcfname);
1553     char *ptr = NULL;
1554     char *end = NULL;
1555     const size_t slen = strlen(i->mountPoint) + 1;
1556     char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
1557
1558     if (mountPoint == NULL)
1559         return;  /* oh well. */
1560
1561     strcpy(mountPoint, i->mountPoint);
1562     ptr = mountPoint + ((len) ? len + 1 : 0);
1563     end = strchr(ptr, '/');
1564     assert(end);  /* should always find a terminating '/'. */
1565     *end = '\0';
1566     callback(data, _fname, ptr);
1567     __PHYSFS_smallFree(mountPoint);
1568 } /* enumerateFromMountPoint */
1569
1570
1571 /* !!! FIXME: this should report error conditions. */
1572 void PHYSFS_enumerateFilesCallback(const char *_fname,
1573                                    PHYSFS_EnumFilesCallback callback,
1574                                    void *data)
1575 {
1576     size_t len;
1577     char *fname;
1578
1579     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
1580     BAIL_IF_MACRO(callback == NULL, ERR_INVALID_ARGUMENT, ) /*0*/;
1581
1582     len = strlen(_fname) + 1;
1583     fname = (char *) __PHYSFS_smallAlloc(len);
1584     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, ) /*0*/;
1585
1586     if (sanitizePlatformIndependentPath(_fname, fname))
1587     {
1588         DirHandle *i;
1589         int noSyms;
1590
1591         __PHYSFS_platformGrabMutex(stateLock);
1592         noSyms = !allowSymLinks;
1593         for (i = searchPath; i != NULL; i = i->next)
1594         {
1595             char *arcfname = fname;
1596             if (partOfMountPoint(i, arcfname))
1597                 enumerateFromMountPoint(i, arcfname, callback, _fname, data);
1598
1599             else if (verifyPath(i, &arcfname, 0))
1600             {
1601                 i->funcs->enumerateFiles(i->opaque, arcfname, noSyms,
1602                                          callback, _fname, data);
1603             } /* else if */
1604         } /* for */
1605         __PHYSFS_platformReleaseMutex(stateLock);
1606     } /* if */
1607
1608     __PHYSFS_smallFree(fname);
1609 } /* PHYSFS_enumerateFilesCallback */
1610
1611
1612 int PHYSFS_exists(const char *fname)
1613 {
1614     return(PHYSFS_getRealDir(fname) != NULL);
1615 } /* PHYSFS_exists */
1616
1617
1618 PHYSFS_sint64 PHYSFS_getLastModTime(const char *_fname)
1619 {
1620     PHYSFS_sint64 retval = -1;
1621     char *fname;
1622     size_t len;
1623
1624     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, -1);
1625     len = strlen(_fname) + 1;
1626     fname = (char *) __PHYSFS_smallAlloc(len);
1627     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, -1);
1628
1629     if (sanitizePlatformIndependentPath(_fname, fname))
1630     {
1631         if (*fname == '\0')   /* eh...punt if it's the root dir. */
1632             retval = 1;  /* !!! FIXME: Maybe this should be an error? */
1633         else
1634         {
1635             DirHandle *i;
1636             int exists = 0;
1637             __PHYSFS_platformGrabMutex(stateLock);
1638             for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
1639             {
1640                 char *arcfname = fname;
1641                 exists = partOfMountPoint(i, arcfname);
1642                 if (exists)
1643                     retval = 1; /* !!! FIXME: What's the right value? */
1644                 else if (verifyPath(i, &arcfname, 0))
1645                 {
1646                     retval = i->funcs->getLastModTime(i->opaque, arcfname,
1647                                                       &exists);
1648                 } /* else if */
1649             } /* for */
1650             __PHYSFS_platformReleaseMutex(stateLock);
1651         } /* else */
1652     } /* if */
1653
1654     __PHYSFS_smallFree(fname);
1655     return(retval);
1656 } /* PHYSFS_getLastModTime */
1657
1658
1659 int PHYSFS_isDirectory(const char *_fname)
1660 {
1661     int retval = 0;
1662     size_t len;
1663     char *fname;
1664
1665     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
1666     len = strlen(_fname) + 1;
1667     fname = (char *) __PHYSFS_smallAlloc(len);
1668     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
1669
1670     if (!sanitizePlatformIndependentPath(_fname, fname))
1671         retval = 0;
1672
1673     else if (*fname == '\0')
1674         retval = 1;  /* Root is always a dir.  :) */
1675
1676     else
1677     {
1678         DirHandle *i;
1679         int exists = 0;
1680
1681         __PHYSFS_platformGrabMutex(stateLock);
1682         for (i = searchPath; ((i != NULL) && (!exists)); i = i->next)
1683         {
1684             char *arcfname = fname;
1685             if ((exists = partOfMountPoint(i, arcfname)) != 0)
1686                 retval = 1;
1687             else if (verifyPath(i, &arcfname, 0))
1688                 retval = i->funcs->isDirectory(i->opaque, arcfname, &exists);
1689         } /* for */
1690         __PHYSFS_platformReleaseMutex(stateLock);
1691     } /* else */
1692
1693     __PHYSFS_smallFree(fname);
1694     return(retval);
1695 } /* PHYSFS_isDirectory */
1696
1697
1698 int PHYSFS_isSymbolicLink(const char *_fname)
1699 {
1700     int retval = 0;
1701     size_t len;
1702     char *fname;
1703
1704     BAIL_IF_MACRO(!allowSymLinks, ERR_SYMLINK_DISALLOWED, 0);
1705
1706     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
1707     len = strlen(_fname) + 1;
1708     fname = (char *) __PHYSFS_smallAlloc(len);
1709     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
1710
1711     if (!sanitizePlatformIndependentPath(_fname, fname))
1712         retval = 0;
1713
1714     else if (*fname == '\0')
1715         retval = 1;  /* Root is never a symlink. */
1716
1717     else
1718     {
1719         DirHandle *i;
1720         int fileExists = 0;
1721
1722         __PHYSFS_platformGrabMutex(stateLock);
1723         for (i = searchPath; ((i != NULL) && (!fileExists)); i = i->next)
1724         {
1725             char *arcfname = fname;
1726             if ((fileExists = partOfMountPoint(i, arcfname)) != 0)
1727                 retval = 0;  /* virtual dir...not a symlink. */
1728             else if (verifyPath(i, &arcfname, 0))
1729                 retval = i->funcs->isSymLink(i->opaque, arcfname, &fileExists);
1730         } /* for */
1731         __PHYSFS_platformReleaseMutex(stateLock);
1732     } /* else */
1733
1734     __PHYSFS_smallFree(fname);
1735     return(retval);
1736 } /* PHYSFS_isSymbolicLink */
1737
1738
1739 static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
1740 {
1741     FileHandle *fh = NULL;
1742     size_t len;
1743     char *fname;
1744
1745     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
1746     len = strlen(_fname) + 1;
1747     fname = (char *) __PHYSFS_smallAlloc(len);
1748     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
1749
1750     if (sanitizePlatformIndependentPath(_fname, fname))
1751     {
1752         void *opaque = NULL;
1753         DirHandle *h = NULL;
1754         const PHYSFS_Archiver *f;
1755
1756         __PHYSFS_platformGrabMutex(stateLock);
1757
1758         GOTO_IF_MACRO(!writeDir, ERR_NO_WRITE_DIR, doOpenWriteEnd);
1759
1760         h = writeDir;
1761         GOTO_IF_MACRO(!verifyPath(h, &fname, 0), NULL, doOpenWriteEnd);
1762
1763         f = h->funcs;
1764         if (appending)
1765             opaque = f->openAppend(h->opaque, fname);
1766         else
1767             opaque = f->openWrite(h->opaque, fname);
1768
1769         GOTO_IF_MACRO(opaque == NULL, NULL, doOpenWriteEnd);
1770
1771         fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
1772         if (fh == NULL)
1773         {
1774             f->fileClose(opaque);
1775             GOTO_MACRO(ERR_OUT_OF_MEMORY, doOpenWriteEnd);
1776         } /* if */
1777         else
1778         {
1779             memset(fh, '\0', sizeof (FileHandle));
1780             fh->opaque = opaque;
1781             fh->dirHandle = h;
1782             fh->funcs = h->funcs;
1783             fh->next = openWriteList;
1784             openWriteList = fh;
1785         } /* else */
1786
1787         doOpenWriteEnd:
1788         __PHYSFS_platformReleaseMutex(stateLock);
1789     } /* if */
1790
1791     __PHYSFS_smallFree(fname);
1792     return((PHYSFS_File *) fh);
1793 } /* doOpenWrite */
1794
1795
1796 PHYSFS_File *PHYSFS_openWrite(const char *filename)
1797 {
1798     return(doOpenWrite(filename, 0));
1799 } /* PHYSFS_openWrite */
1800
1801
1802 PHYSFS_File *PHYSFS_openAppend(const char *filename)
1803 {
1804     return(doOpenWrite(filename, 1));
1805 } /* PHYSFS_openAppend */
1806
1807
1808 PHYSFS_File *PHYSFS_openRead(const char *_fname)
1809 {
1810     FileHandle *fh = NULL;
1811     char *fname;
1812     size_t len;
1813
1814     BAIL_IF_MACRO(_fname == NULL, ERR_INVALID_ARGUMENT, 0);
1815     len = strlen(_fname) + 1;
1816     fname = (char *) __PHYSFS_smallAlloc(len);
1817     BAIL_IF_MACRO(fname == NULL, ERR_OUT_OF_MEMORY, 0);
1818
1819     if (sanitizePlatformIndependentPath(_fname, fname))
1820     {
1821         int fileExists = 0;
1822         DirHandle *i = NULL;
1823         fvoid *opaque = NULL;
1824
1825         __PHYSFS_platformGrabMutex(stateLock);
1826
1827         GOTO_IF_MACRO(!searchPath, ERR_NO_SUCH_PATH, openReadEnd);
1828
1829         /* !!! FIXME: Why aren't we using a for loop here? */
1830         i = searchPath;
1831
1832         do
1833         {
1834             char *arcfname = fname;
1835             if (verifyPath(i, &arcfname, 0))
1836             {
1837                 opaque = i->funcs->openRead(i->opaque, arcfname, &fileExists);
1838                 if (opaque)
1839                     break;
1840             } /* if */
1841             i = i->next;
1842         } while ((i != NULL) && (!fileExists));
1843
1844         /* !!! FIXME: may not set an error if openRead didn't fail. */
1845         GOTO_IF_MACRO(opaque == NULL, NULL, openReadEnd);
1846
1847         fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
1848         if (fh == NULL)
1849         {
1850             i->funcs->fileClose(opaque);
1851             GOTO_MACRO(ERR_OUT_OF_MEMORY, openReadEnd);
1852         } /* if */
1853
1854         memset(fh, '\0', sizeof (FileHandle));
1855         fh->opaque = opaque;
1856         fh->forReading = 1;
1857         fh->dirHandle = i;
1858         fh->funcs = i->funcs;
1859         fh->next = openReadList;
1860         openReadList = fh;
1861
1862         openReadEnd:
1863         __PHYSFS_platformReleaseMutex(stateLock);
1864     } /* if */
1865
1866     __PHYSFS_smallFree(fname);
1867     return((PHYSFS_File *) fh);
1868 } /* PHYSFS_openRead */
1869
1870
1871 static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
1872 {
1873     FileHandle *prev = NULL;
1874     FileHandle *i;
1875     int rc = 1;
1876
1877     for (i = *list; i != NULL; i = i->next)
1878     {
1879         if (i == handle)  /* handle is in this list? */
1880         {
1881             PHYSFS_uint8 *tmp = handle->buffer;
1882             rc = PHYSFS_flush((PHYSFS_File *) handle);
1883             if (rc)
1884                 rc = handle->funcs->fileClose(handle->opaque);
1885             if (!rc)
1886                 return(-1);
1887
1888             if (tmp != NULL)  /* free any associated buffer. */
1889                 allocator.Free(tmp);
1890
1891             if (prev == NULL)
1892                 *list = handle->next;
1893             else
1894                 prev->next = handle->next;
1895
1896             allocator.Free(handle);
1897             return(1);
1898         } /* if */
1899         prev = i;
1900     } /* for */
1901
1902     return(0);
1903 } /* closeHandleInOpenList */
1904
1905
1906 int PHYSFS_close(PHYSFS_File *_handle)
1907 {
1908     FileHandle *handle = (FileHandle *) _handle;
1909     int rc;
1910
1911     __PHYSFS_platformGrabMutex(stateLock);
1912
1913     /* -1 == close failure. 0 == not found. 1 == success. */
1914     rc = closeHandleInOpenList(&openReadList, handle);
1915     BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
1916     if (!rc)
1917     {
1918         rc = closeHandleInOpenList(&openWriteList, handle);
1919         BAIL_IF_MACRO_MUTEX(rc == -1, NULL, stateLock, 0);
1920     } /* if */
1921
1922     __PHYSFS_platformReleaseMutex(stateLock);
1923     BAIL_IF_MACRO(!rc, ERR_NOT_A_HANDLE, 0);
1924     return(1);
1925 } /* PHYSFS_close */
1926
1927
1928 static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
1929                                     PHYSFS_uint32 objSize,
1930                                     PHYSFS_uint32 objCount)
1931 {
1932     PHYSFS_sint64 retval = 0;
1933     PHYSFS_uint32 remainder = 0;
1934
1935     while (objCount > 0)
1936     {
1937         PHYSFS_uint32 buffered = fh->buffill - fh->bufpos;
1938         PHYSFS_uint64 mustread = (objSize * objCount) - remainder;
1939         PHYSFS_uint32 copied;
1940
1941         if (buffered == 0) /* need to refill buffer? */
1942         {
1943             PHYSFS_sint64 rc = fh->funcs->read(fh->opaque, fh->buffer,
1944                                                 1, fh->bufsize);
1945             if (rc <= 0)
1946             {
1947                 fh->bufpos -= remainder;
1948                 return(((rc == -1) && (retval == 0)) ? -1 : retval);
1949             } /* if */
1950
1951             buffered = fh->buffill = (PHYSFS_uint32) rc;
1952             fh->bufpos = 0;
1953         } /* if */
1954
1955         if (buffered > mustread)
1956             buffered = (PHYSFS_uint32) mustread;
1957
1958         memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
1959         buffer = ((PHYSFS_uint8 *) buffer) + buffered;
1960         fh->bufpos += buffered;
1961         buffered += remainder;  /* take remainder into account. */
1962         copied = (buffered / objSize);
1963         remainder = (buffered % objSize);
1964         retval += copied;
1965         objCount -= copied;
1966     } /* while */
1967
1968     return(retval);
1969 } /* doBufferedRead */
1970
1971
1972 PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
1973                           PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
1974 {
1975     FileHandle *fh = (FileHandle *) handle;
1976
1977     BAIL_IF_MACRO(!fh->forReading, ERR_FILE_ALREADY_OPEN_W, -1);
1978     BAIL_IF_MACRO(objSize == 0, NULL, 0);
1979     BAIL_IF_MACRO(objCount == 0, NULL, 0);
1980     if (fh->buffer != NULL)
1981         return(doBufferedRead(fh, buffer, objSize, objCount));
1982
1983     return(fh->funcs->read(fh->opaque, buffer, objSize, objCount));
1984 } /* PHYSFS_read */
1985
1986
1987 static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
1988                                      PHYSFS_uint32 objSize,
1989                                      PHYSFS_uint32 objCount)
1990 {
1991     FileHandle *fh = (FileHandle *) handle;
1992
1993     /* whole thing fits in the buffer? */
1994     if (fh->buffill + (objSize * objCount) < fh->bufsize)
1995     {
1996         memcpy(fh->buffer + fh->buffill, buffer, objSize * objCount);
1997         fh->buffill += (objSize * objCount);
1998         return(objCount);
1999     } /* if */
2000
2001     /* would overflow buffer. Flush and then write the new objects, too. */
2002     BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, -1);
2003     return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
2004 } /* doBufferedWrite */
2005
2006
2007 PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
2008                            PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
2009 {
2010     FileHandle *fh = (FileHandle *) handle;
2011
2012     BAIL_IF_MACRO(fh->forReading, ERR_FILE_ALREADY_OPEN_R, -1);
2013     BAIL_IF_MACRO(objSize == 0, NULL, 0);
2014     BAIL_IF_MACRO(objCount == 0, NULL, 0);
2015     if (fh->buffer != NULL)
2016         return(doBufferedWrite(handle, buffer, objSize, objCount));
2017
2018     return(fh->funcs->write(fh->opaque, buffer, objSize, objCount));
2019 } /* PHYSFS_write */
2020
2021
2022 int PHYSFS_eof(PHYSFS_File *handle)
2023 {
2024     FileHandle *fh = (FileHandle *) handle;
2025
2026     if (!fh->forReading)  /* never EOF on files opened for write/append. */
2027         return(0);
2028
2029     /* eof if buffer is empty and archiver says so. */
2030     return((fh->bufpos == fh->buffill) && (fh->funcs->eof(fh->opaque)));
2031 } /* PHYSFS_eof */
2032
2033
2034 PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
2035 {
2036     FileHandle *fh = (FileHandle *) handle;
2037     PHYSFS_sint64 pos = fh->funcs->tell(fh->opaque);
2038     PHYSFS_sint64 retval = fh->forReading ?
2039                             (pos - fh->buffill) + fh->bufpos :
2040                             (pos + fh->buffill);
2041     return(retval);
2042 } /* PHYSFS_tell */
2043
2044
2045 int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
2046 {
2047     FileHandle *fh = (FileHandle *) handle;
2048     BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
2049
2050     if (fh->buffer && fh->forReading)
2051     {
2052         /* avoid throwing away our precious buffer if seeking within it. */
2053         PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
2054         if ( /* seeking within the already-buffered range? */
2055             ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
2056             || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
2057         {
2058             fh->bufpos += (PHYSFS_uint32) offset;
2059             return(1); /* successful seek */
2060         } /* if */
2061     } /* if */
2062
2063     /* we have to fall back to a 'raw' seek. */
2064     fh->buffill = fh->bufpos = 0;
2065     return(fh->funcs->seek(fh->opaque, pos));
2066 } /* PHYSFS_seek */
2067
2068
2069 PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
2070 {
2071     FileHandle *fh = (FileHandle *) handle;
2072     return(fh->funcs->fileLength(fh->opaque));
2073 } /* PHYSFS_filelength */
2074
2075
2076 int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
2077 {
2078     FileHandle *fh = (FileHandle *) handle;
2079     PHYSFS_uint32 bufsize;
2080
2081     /* !!! FIXME: Unlocalized string. */
2082     BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);
2083     bufsize = (PHYSFS_uint32) _bufsize;
2084
2085     BAIL_IF_MACRO(!PHYSFS_flush(handle), NULL, 0);
2086
2087     /*
2088      * For reads, we need to move the file pointer to where it would be
2089      *  if we weren't buffering, so that the next read will get the
2090      *  right chunk of stuff from the file. PHYSFS_flush() handles writes.
2091      */
2092     if ((fh->forReading) && (fh->buffill != fh->bufpos))
2093     {
2094         PHYSFS_uint64 pos;
2095         PHYSFS_sint64 curpos = fh->funcs->tell(fh->opaque);
2096         BAIL_IF_MACRO(curpos == -1, NULL, 0);
2097         pos = ((curpos - fh->buffill) + fh->bufpos);
2098         BAIL_IF_MACRO(!fh->funcs->seek(fh->opaque, pos), NULL, 0);
2099     } /* if */
2100
2101     if (bufsize == 0)  /* delete existing buffer. */
2102     {
2103         if (fh->buffer != NULL)
2104         {
2105             allocator.Free(fh->buffer);
2106             fh->buffer = NULL;
2107         } /* if */
2108     } /* if */
2109
2110     else
2111     {
2112         PHYSFS_uint8 *newbuf;
2113         newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
2114         BAIL_IF_MACRO(newbuf == NULL, ERR_OUT_OF_MEMORY, 0);
2115         fh->buffer = newbuf;
2116     } /* else */
2117
2118     fh->bufsize = bufsize;
2119     fh->buffill = fh->bufpos = 0;
2120     return(1);
2121 } /* PHYSFS_setBuffer */
2122
2123
2124 int PHYSFS_flush(PHYSFS_File *handle)
2125 {
2126     FileHandle *fh = (FileHandle *) handle;
2127     PHYSFS_sint64 rc;
2128
2129     if ((fh->forReading) || (fh->bufpos == fh->buffill))
2130         return(1);  /* open for read or buffer empty are successful no-ops. */
2131
2132     /* dump buffer to disk. */
2133     rc = fh->funcs->write(fh->opaque, fh->buffer + fh->bufpos,
2134                           fh->buffill - fh->bufpos, 1);
2135     BAIL_IF_MACRO(rc <= 0, NULL, 0);
2136     fh->bufpos = fh->buffill = 0;
2137     return(1);
2138 } /* PHYSFS_flush */
2139
2140
2141 int PHYSFS_setAllocator(const PHYSFS_Allocator *a)
2142 {
2143     BAIL_IF_MACRO(initialized, ERR_IS_INITIALIZED, 0);
2144     externalAllocator = (a != NULL);
2145     if (externalAllocator)
2146         memcpy(&allocator, a, sizeof (PHYSFS_Allocator));
2147
2148     return(1);
2149 } /* PHYSFS_setAllocator */
2150
2151
2152 static void *mallocAllocatorMalloc(PHYSFS_uint64 s)
2153 {
2154     BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
2155     #undef malloc
2156     return(malloc((size_t) s));
2157 } /* mallocAllocatorMalloc */
2158
2159
2160 static void *mallocAllocatorRealloc(void *ptr, PHYSFS_uint64 s)
2161 {
2162     BAIL_IF_MACRO(__PHYSFS_ui64FitsAddressSpace(s), ERR_OUT_OF_MEMORY, NULL);
2163     #undef realloc
2164     return(realloc(ptr, (size_t) s));
2165 } /* mallocAllocatorRealloc */
2166
2167
2168 static void mallocAllocatorFree(void *ptr)
2169 {
2170     #undef free
2171     free(ptr);
2172 } /* mallocAllocatorFree */
2173
2174
2175 static void setDefaultAllocator(void)
2176 {
2177     assert(!externalAllocator);
2178     if (!__PHYSFS_platformSetDefaultAllocator(&allocator))
2179     {
2180         allocator.Init = NULL;
2181         allocator.Deinit = NULL;
2182         allocator.Malloc = mallocAllocatorMalloc;
2183         allocator.Realloc = mallocAllocatorRealloc;
2184         allocator.Free = mallocAllocatorFree;
2185     } /* if */
2186 } /* setDefaultAllocator */
2187
2188
2189 void *__PHYSFS_initSmallAlloc(void *ptr, PHYSFS_uint64 len)
2190 {
2191     const char useHeap = ((ptr == NULL) ? 1 : 0);
2192     if (useHeap)  /* too large for stack allocation or alloca() failed. */
2193         ptr = allocator.Malloc(len+1);
2194
2195     if (ptr != NULL)
2196     {
2197         char *retval = (char *) ptr;
2198         /*printf("%s alloc'd (%d) bytes at (%p).\n",
2199                 useHeap ? "heap" : "stack", (int) len, ptr);*/
2200         *retval = useHeap;
2201         return(retval+1);
2202     } /* if */
2203
2204     return(NULL);  /* allocation failed. */
2205 } /* __PHYSFS_initSmallAlloc */
2206
2207
2208 void __PHYSFS_smallFree(void *ptr)
2209 {
2210     if (ptr != NULL)
2211     {
2212         char *block = ((char *) ptr) - 1;
2213         const char useHeap = *block;
2214         if (useHeap)
2215             allocator.Free(block);
2216         /*printf("%s free'd (%p).\n", useHeap ? "heap" : "stack", block);*/
2217     } /* if */
2218 } /* __PHYSFS_smallFree */
2219
2220 /* end of physfs.c ... */
2221