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