]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libz/gzio.c
This commit was generated by cvs2svn to compensate for changes in r86567,
[FreeBSD/FreeBSD.git] / lib / libz / gzio.c
1 /* gzio.c -- IO on .gz files
2  * Copyright (C) 1995-1998 Jean-loup Gailly.
3  * For conditions of distribution and use, see copyright notice in zlib.h
4  *
5  * Compile this file with -DNO_DEFLATE to avoid the compression code.
6  */
7
8 #include <sys/cdefs.h>
9 __FBSDID("$FreeBSD$");
10
11 #include <stdio.h>
12
13 #include "zutil.h"
14
15 struct internal_state {int dummy;}; /* for buggy compilers */
16
17 #ifndef Z_BUFSIZE
18 #  ifdef MAXSEG_64K
19 #    define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
20 #  else
21 #    define Z_BUFSIZE 16384
22 #  endif
23 #endif
24 #ifndef Z_PRINTF_BUFSIZE
25 #  define Z_PRINTF_BUFSIZE 4096
26 #endif
27
28 #define ALLOC(size) malloc(size)
29 #define TRYFREE(p) {if (p) free(p);}
30
31 static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
32
33 /* gzip flag byte */
34 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
35 #define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
36 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
37 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
38 #define COMMENT      0x10 /* bit 4 set: file comment present */
39 #define RESERVED     0xE0 /* bits 5..7: reserved */
40
41 typedef struct gz_stream {
42     z_stream stream;
43     int      z_err;   /* error code for last stream operation */
44     int      z_eof;   /* set if end of input file */
45     FILE     *file;   /* .gz file */
46     Byte     *inbuf;  /* input buffer */
47     Byte     *outbuf; /* output buffer */
48     uLong    crc;     /* crc32 of uncompressed data */
49     char     *msg;    /* error message */
50     char     *path;   /* path name for debugging only */
51     int      transparent; /* 1 if input file is not a .gz file */
52     char     mode;    /* 'w' or 'r' */
53     long     startpos; /* start of compressed data in file (header skipped) */
54 } gz_stream;
55
56
57 local gzFile gz_open      OF((const char *path, const char *mode, int  fd));
58 local int do_flush        OF((gzFile file, int flush));
59 local int    get_byte     OF((gz_stream *s));
60 local void   check_header OF((gz_stream *s));
61 local int    destroy      OF((gz_stream *s));
62 local void   putLong      OF((FILE *file, uLong x));
63 local uLong  getLong      OF((gz_stream *s));
64
65 /* ===========================================================================
66      Opens a gzip (.gz) file for reading or writing. The mode parameter
67    is as in fopen ("rb" or "wb"). The file is given either by file descriptor
68    or path name (if fd == -1).
69      gz_open return NULL if the file could not be opened or if there was
70    insufficient memory to allocate the (de)compression state; errno
71    can be checked to distinguish the two cases (if errno is zero, the
72    zlib error is Z_MEM_ERROR).
73 */
74 local gzFile gz_open (path, mode, fd)
75     const char *path;
76     const char *mode;
77     int  fd;
78 {
79     int err;
80     int level = Z_DEFAULT_COMPRESSION; /* compression level */
81     int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
82     char *p = (char*)mode;
83     gz_stream *s;
84     char fmode[80]; /* copy of mode, without the compression level */
85     char *m = fmode;
86
87     if (!path || !mode) return Z_NULL;
88
89     s = (gz_stream *)ALLOC(sizeof(gz_stream));
90     if (!s) return Z_NULL;
91
92     s->stream.zalloc = (alloc_func)0;
93     s->stream.zfree = (free_func)0;
94     s->stream.opaque = (voidpf)0;
95     s->stream.next_in = s->inbuf = Z_NULL;
96     s->stream.next_out = s->outbuf = Z_NULL;
97     s->stream.avail_in = s->stream.avail_out = 0;
98     s->file = NULL;
99     s->z_err = Z_OK;
100     s->z_eof = 0;
101     s->crc = crc32(0L, Z_NULL, 0);
102     s->msg = NULL;
103     s->transparent = 0;
104
105     s->path = (char*)ALLOC(strlen(path)+1);
106     if (s->path == NULL) {
107         return destroy(s), (gzFile)Z_NULL;
108     }
109     strcpy(s->path, path); /* do this early for debugging */
110
111     s->mode = '\0';
112     do {
113         if (*p == 'r') s->mode = 'r';
114         if (*p == 'w' || *p == 'a') s->mode = 'w';
115         if (*p >= '0' && *p <= '9') {
116             level = *p - '0';
117         } else if (*p == 'f') {
118           strategy = Z_FILTERED;
119         } else if (*p == 'h') {
120           strategy = Z_HUFFMAN_ONLY;
121         } else {
122             *m++ = *p; /* copy the mode */
123         }
124     } while (*p++ && m != fmode + sizeof(fmode));
125     if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
126     
127     if (s->mode == 'w') {
128 #ifdef NO_DEFLATE
129         err = Z_STREAM_ERROR;
130 #else
131         err = deflateInit2(&(s->stream), level,
132                            Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
133         /* windowBits is passed < 0 to suppress zlib header */
134
135         s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
136 #endif
137         if (err != Z_OK || s->outbuf == Z_NULL) {
138             return destroy(s), (gzFile)Z_NULL;
139         }
140     } else {
141         s->stream.next_in  = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
142
143         err = inflateInit2(&(s->stream), -MAX_WBITS);
144         /* windowBits is passed < 0 to tell that there is no zlib header.
145          * Note that in this case inflate *requires* an extra "dummy" byte
146          * after the compressed stream in order to complete decompression and
147          * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
148          * present after the compressed stream.
149          */
150         if (err != Z_OK || s->inbuf == Z_NULL) {
151             return destroy(s), (gzFile)Z_NULL;
152         }
153     }
154     s->stream.avail_out = Z_BUFSIZE;
155
156     errno = 0;
157     s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
158
159     if (s->file == NULL) {
160         return destroy(s), (gzFile)Z_NULL;
161     }
162     if (s->mode == 'w') {
163         /* Write a very simple .gz header:
164          */
165         fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
166              Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
167         s->startpos = 10L;
168         /* We use 10L instead of ftell(s->file) to because ftell causes an
169          * fflush on some systems. This version of the library doesn't use
170          * startpos anyway in write mode, so this initialization is not
171          * necessary.
172          */
173     } else {
174         check_header(s); /* skip the .gz header */
175         s->startpos = (ftell(s->file) - s->stream.avail_in);
176     }
177     
178     return (gzFile)s;
179 }
180
181 /* ===========================================================================
182      Opens a gzip (.gz) file for reading or writing.
183 */
184 gzFile ZEXPORT gzopen (path, mode)
185     const char *path;
186     const char *mode;
187 {
188     return gz_open (path, mode, -1);
189 }
190
191 /* ===========================================================================
192      Associate a gzFile with the file descriptor fd. fd is not dup'ed here
193    to mimic the behavio(u)r of fdopen.
194 */
195 gzFile ZEXPORT gzdopen (fd, mode)
196     int fd;
197     const char *mode;
198 {
199     char name[20];
200
201     if (fd < 0) return (gzFile)Z_NULL;
202     snprintf(name, sizeof(name), "<fd:%d>", fd); /* for debugging */
203
204     return gz_open (name, mode, fd);
205 }
206
207 /* ===========================================================================
208  * Update the compression level and strategy
209  */
210 int ZEXPORT gzsetparams (file, level, strategy)
211     gzFile file;
212     int level;
213     int strategy;
214 {
215     gz_stream *s = (gz_stream*)file;
216
217     if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
218
219     /* Make room to allow flushing */
220     if (s->stream.avail_out == 0) {
221
222         s->stream.next_out = s->outbuf;
223         if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
224             s->z_err = Z_ERRNO;
225         }
226         s->stream.avail_out = Z_BUFSIZE;
227     }
228
229     return deflateParams (&(s->stream), level, strategy);
230 }
231
232 /* ===========================================================================
233      Read a byte from a gz_stream; update next_in and avail_in. Return EOF
234    for end of file.
235    IN assertion: the stream s has been sucessfully opened for reading.
236 */
237 local int get_byte(s)
238     gz_stream *s;
239 {
240     if (s->z_eof) return EOF;
241     if (s->stream.avail_in == 0) {
242         errno = 0;
243         s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
244         if (s->stream.avail_in == 0) {
245             s->z_eof = 1;
246             if (ferror(s->file)) s->z_err = Z_ERRNO;
247             return EOF;
248         }
249         s->stream.next_in = s->inbuf;
250     }
251     s->stream.avail_in--;
252     return *(s->stream.next_in)++;
253 }
254
255 /* ===========================================================================
256       Check the gzip header of a gz_stream opened for reading. Set the stream
257     mode to transparent if the gzip magic header is not present; set s->err
258     to Z_DATA_ERROR if the magic header is present but the rest of the header
259     is incorrect.
260     IN assertion: the stream s has already been created sucessfully;
261        s->stream.avail_in is zero for the first time, but may be non-zero
262        for concatenated .gz files.
263 */
264 local void check_header(s)
265     gz_stream *s;
266 {
267     int method; /* method byte */
268     int flags;  /* flags byte */
269     uInt len;
270     int c;
271
272     /* Check the gzip magic header */
273     for (len = 0; len < 2; len++) {
274         c = get_byte(s);
275         if (c != gz_magic[len]) {
276             if (len != 0) s->stream.avail_in++, s->stream.next_in--;
277             if (c != EOF) {
278                 s->stream.avail_in++, s->stream.next_in--;
279                 s->transparent = 1;
280             }
281             s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END;
282             return;
283         }
284     }
285     method = get_byte(s);
286     flags = get_byte(s);
287     if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
288         s->z_err = Z_DATA_ERROR;
289         return;
290     }
291
292     /* Discard time, xflags and OS code: */
293     for (len = 0; len < 6; len++) (void)get_byte(s);
294
295     if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
296         len  =  (uInt)get_byte(s);
297         len += ((uInt)get_byte(s))<<8;
298         /* len is garbage if EOF but the loop below will quit anyway */
299         while (len-- != 0 && get_byte(s) != EOF) ;
300     }
301     if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
302         while ((c = get_byte(s)) != 0 && c != EOF) ;
303     }
304     if ((flags & COMMENT) != 0) {   /* skip the .gz file comment */
305         while ((c = get_byte(s)) != 0 && c != EOF) ;
306     }
307     if ((flags & HEAD_CRC) != 0) {  /* skip the header crc */
308         for (len = 0; len < 2; len++) (void)get_byte(s);
309     }
310     s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
311 }
312
313  /* ===========================================================================
314  * Cleanup then free the given gz_stream. Return a zlib error code.
315    Try freeing in the reverse order of allocations.
316  */
317 local int destroy (s)
318     gz_stream *s;
319 {
320     int err = Z_OK;
321
322     if (!s) return Z_STREAM_ERROR;
323
324     TRYFREE(s->msg);
325
326     if (s->stream.state != NULL) {
327         if (s->mode == 'w') {
328 #ifdef NO_DEFLATE
329             err = Z_STREAM_ERROR;
330 #else
331             err = deflateEnd(&(s->stream));
332 #endif
333         } else if (s->mode == 'r') {
334             err = inflateEnd(&(s->stream));
335         }
336     }
337     if (s->file != NULL && fclose(s->file)) {
338 #ifdef ESPIPE
339         if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
340 #endif
341             err = Z_ERRNO;
342     }
343     if (s->z_err < 0) err = s->z_err;
344
345     TRYFREE(s->inbuf);
346     TRYFREE(s->outbuf);
347     TRYFREE(s->path);
348     TRYFREE(s);
349     return err;
350 }
351
352 /* ===========================================================================
353      Reads the given number of uncompressed bytes from the compressed file.
354    gzread returns the number of bytes actually read (0 for end of file).
355 */
356 int ZEXPORT gzread (file, buf, len)
357     gzFile file;
358     voidp buf;
359     unsigned len;
360 {
361     gz_stream *s = (gz_stream*)file;
362     Bytef *start = (Bytef*)buf; /* starting point for crc computation */
363     Byte  *next_out; /* == stream.next_out but not forced far (for MSDOS) */
364
365     if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
366
367     if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
368     if (s->z_err == Z_STREAM_END) return 0;  /* EOF */
369
370     next_out = (Byte*)buf;
371     s->stream.next_out = (Bytef*)buf;
372     s->stream.avail_out = len;
373
374     while (s->stream.avail_out != 0) {
375
376         if (s->transparent) {
377             /* Copy first the lookahead bytes: */
378             uInt n = s->stream.avail_in;
379             if (n > s->stream.avail_out) n = s->stream.avail_out;
380             if (n > 0) {
381                 zmemcpy(s->stream.next_out, s->stream.next_in, n);
382                 next_out += n;
383                 s->stream.next_out = next_out;
384                 s->stream.next_in   += n;
385                 s->stream.avail_out -= n;
386                 s->stream.avail_in  -= n;
387             }
388             if (s->stream.avail_out > 0) {
389                 s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out,
390                                              s->file);
391             }
392             len -= s->stream.avail_out;
393             s->stream.total_in  += (uLong)len;
394             s->stream.total_out += (uLong)len;
395             if (len == 0) s->z_eof = 1;
396             return (int)len;
397         }
398         if (s->stream.avail_in == 0 && !s->z_eof) {
399
400             errno = 0;
401             s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
402             if (s->stream.avail_in == 0) {
403                 s->z_eof = 1;
404                 if (ferror(s->file)) {
405                     s->z_err = Z_ERRNO;
406                     break;
407                 }
408             }
409             s->stream.next_in = s->inbuf;
410         }
411         s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
412
413         if (s->z_err == Z_STREAM_END) {
414             /* Check CRC and original size */
415             s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
416             start = s->stream.next_out;
417
418             if (getLong(s) != s->crc) {
419                 s->z_err = Z_DATA_ERROR;
420             } else {
421                 (void)getLong(s);
422                 /* The uncompressed length returned by above getlong() may
423                  * be different from s->stream.total_out) in case of
424                  * concatenated .gz files. Check for such files:
425                  */
426                 check_header(s);
427                 if (s->z_err == Z_OK) {
428                     uLong total_in = s->stream.total_in;
429                     uLong total_out = s->stream.total_out;
430
431                     inflateReset(&(s->stream));
432                     s->stream.total_in = total_in;
433                     s->stream.total_out = total_out;
434                     s->crc = crc32(0L, Z_NULL, 0);
435                 }
436             }
437         }
438         if (s->z_err != Z_OK || s->z_eof) break;
439     }
440     s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
441
442     return (int)(len - s->stream.avail_out);
443 }
444
445
446 /* ===========================================================================
447       Reads one byte from the compressed file. gzgetc returns this byte
448    or -1 in case of end of file or error.
449 */
450 int ZEXPORT gzgetc(file)
451     gzFile file;
452 {
453     unsigned char c;
454
455     return gzread(file, &c, 1) == 1 ? c : -1;
456 }
457
458
459 /* ===========================================================================
460       Reads bytes from the compressed file until len-1 characters are
461    read, or a newline character is read and transferred to buf, or an
462    end-of-file condition is encountered.  The string is then terminated
463    with a null character.
464       gzgets returns buf, or Z_NULL in case of error.
465
466       The current implementation is not optimized at all.
467 */
468 char * ZEXPORT gzgets(file, buf, len)
469     gzFile file;
470     char *buf;
471     int len;
472 {
473     char *b = buf;
474     if (buf == Z_NULL || len <= 0) return Z_NULL;
475
476     while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
477     *buf = '\0';
478     return b == buf && len > 0 ? Z_NULL : b;
479 }
480
481
482 #ifndef NO_DEFLATE
483 /* ===========================================================================
484      Writes the given number of uncompressed bytes into the compressed file.
485    gzwrite returns the number of bytes actually written (0 in case of error).
486 */
487 int ZEXPORT gzwrite (file, buf, len)
488     gzFile file;
489     const voidp buf;
490     unsigned len;
491 {
492     gz_stream *s = (gz_stream*)file;
493
494     if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
495
496     s->stream.next_in = (Bytef*)buf;
497     s->stream.avail_in = len;
498
499     while (s->stream.avail_in != 0) {
500
501         if (s->stream.avail_out == 0) {
502
503             s->stream.next_out = s->outbuf;
504             if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
505                 s->z_err = Z_ERRNO;
506                 break;
507             }
508             s->stream.avail_out = Z_BUFSIZE;
509         }
510         s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
511         if (s->z_err != Z_OK) break;
512     }
513     s->crc = crc32(s->crc, (const Bytef *)buf, len);
514
515     return (int)(len - s->stream.avail_in);
516 }
517
518 /* ===========================================================================
519      Converts, formats, and writes the args to the compressed file under
520    control of the format string, as in fprintf. gzprintf returns the number of
521    uncompressed bytes actually written (0 in case of error).
522 */
523 #ifdef STDC
524 #include <stdarg.h>
525
526 int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
527 {
528     char buf[Z_PRINTF_BUFSIZE];
529     va_list va;
530     int len;
531
532     va_start(va, format);
533 #ifdef HAS_vsnprintf
534     (void)vsnprintf(buf, sizeof(buf), format, va);
535 #else
536     (void)vsprintf(buf, format, va);
537 #endif
538     va_end(va);
539     len = strlen(buf); /* some *sprintf don't return the nb of bytes written */
540     if (len <= 0) return 0;
541
542     return gzwrite(file, buf, (unsigned)len);
543 }
544 #else /* not ANSI C */
545
546 int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
547                        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
548     gzFile file;
549     const char *format;
550     int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
551         a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
552 {
553     char buf[Z_PRINTF_BUFSIZE];
554     int len;
555
556 #ifdef HAS_snprintf
557     snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
558              a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
559 #else
560     sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
561             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
562 #endif
563     len = strlen(buf); /* old sprintf doesn't return the nb of bytes written */
564     if (len <= 0) return 0;
565
566     return gzwrite(file, buf, len);
567 }
568 #endif
569
570 /* ===========================================================================
571       Writes c, converted to an unsigned char, into the compressed file.
572    gzputc returns the value that was written, or -1 in case of error.
573 */
574 int ZEXPORT gzputc(file, c)
575     gzFile file;
576     int c;
577 {
578     unsigned char cc = (unsigned char) c; /* required for big endian systems */
579
580     return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
581 }
582
583
584 /* ===========================================================================
585       Writes the given null-terminated string to the compressed file, excluding
586    the terminating null character.
587       gzputs returns the number of characters written, or -1 in case of error.
588 */
589 int ZEXPORT gzputs(file, s)
590     gzFile file;
591     const char *s;
592 {
593     return gzwrite(file, (char*)s, (unsigned)strlen(s));
594 }
595
596
597 /* ===========================================================================
598      Flushes all pending output into the compressed file. The parameter
599    flush is as in the deflate() function.
600 */
601 local int do_flush (file, flush)
602     gzFile file;
603     int flush;
604 {
605     uInt len;
606     int done = 0;
607     gz_stream *s = (gz_stream*)file;
608
609     if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
610
611     s->stream.avail_in = 0; /* should be zero already anyway */
612
613     for (;;) {
614         len = Z_BUFSIZE - s->stream.avail_out;
615
616         if (len != 0) {
617             if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
618                 s->z_err = Z_ERRNO;
619                 return Z_ERRNO;
620             }
621             s->stream.next_out = s->outbuf;
622             s->stream.avail_out = Z_BUFSIZE;
623         }
624         if (done) break;
625         s->z_err = deflate(&(s->stream), flush);
626
627         /* Ignore the second of two consecutive flushes: */
628         if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
629
630         /* deflate has finished flushing only when it hasn't used up
631          * all the available space in the output buffer: 
632          */
633         done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
634  
635         if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
636     }
637     return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
638 }
639
640 int ZEXPORT gzflush (file, flush)
641      gzFile file;
642      int flush;
643 {
644     gz_stream *s = (gz_stream*)file;
645     int err = do_flush (file, flush);
646
647     if (err) return err;
648     fflush(s->file);
649     return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
650 }
651 #endif /* NO_DEFLATE */
652
653 /* ===========================================================================
654       Sets the starting position for the next gzread or gzwrite on the given
655    compressed file. The offset represents a number of bytes in the
656       gzseek returns the resulting offset location as measured in bytes from
657    the beginning of the uncompressed stream, or -1 in case of error.
658       SEEK_END is not implemented, returns error.
659       In this version of the library, gzseek can be extremely slow.
660 */
661 z_off_t ZEXPORT gzseek (file, offset, whence)
662     gzFile file;
663     z_off_t offset;
664     int whence;
665 {
666     gz_stream *s = (gz_stream*)file;
667
668     if (s == NULL || whence == SEEK_END ||
669         s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
670         return -1L;
671     }
672     
673     if (s->mode == 'w') {
674 #ifdef NO_DEFLATE
675         return -1L;
676 #else
677         if (whence == SEEK_SET) {
678             offset -= s->stream.total_in;
679         }
680         if (offset < 0) return -1L;
681
682         /* At this point, offset is the number of zero bytes to write. */
683         if (s->inbuf == Z_NULL) {
684             s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
685             zmemzero(s->inbuf, Z_BUFSIZE);
686         }
687         while (offset > 0)  {
688             uInt size = Z_BUFSIZE;
689             if (offset < Z_BUFSIZE) size = (uInt)offset;
690
691             size = gzwrite(file, s->inbuf, size);
692             if (size == 0) return -1L;
693
694             offset -= size;
695         }
696         return (z_off_t)s->stream.total_in;
697 #endif
698     }
699     /* Rest of function is for reading only */
700
701     /* compute absolute position */
702     if (whence == SEEK_CUR) {
703         offset += s->stream.total_out;
704     }
705     if (offset < 0) return -1L;
706
707     if (s->transparent) {
708         /* map to fseek */
709         s->stream.avail_in = 0;
710         s->stream.next_in = s->inbuf;
711         if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
712
713         s->stream.total_in = s->stream.total_out = (uLong)offset;
714         return offset;
715     }
716
717     /* For a negative seek, rewind and use positive seek */
718     if ((uLong)offset >= s->stream.total_out) {
719         offset -= s->stream.total_out;
720     } else if (gzrewind(file) < 0) {
721         return -1L;
722     }
723     /* offset is now the number of bytes to skip. */
724
725     if (offset != 0 && s->outbuf == Z_NULL) {
726         s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
727     }
728     while (offset > 0)  {
729         int size = Z_BUFSIZE;
730         if (offset < Z_BUFSIZE) size = (int)offset;
731
732         size = gzread(file, s->outbuf, (uInt)size);
733         if (size <= 0) return -1L;
734         offset -= size;
735     }
736     return (z_off_t)s->stream.total_out;
737 }
738
739 /* ===========================================================================
740      Rewinds input file. 
741 */
742 int ZEXPORT gzrewind (file)
743     gzFile file;
744 {
745     gz_stream *s = (gz_stream*)file;
746     
747     if (s == NULL || s->mode != 'r') return -1;
748
749     s->z_err = Z_OK;
750     s->z_eof = 0;
751     s->stream.avail_in = 0;
752     s->stream.next_in = s->inbuf;
753     s->crc = crc32(0L, Z_NULL, 0);
754         
755     if (s->startpos == 0) { /* not a compressed file */
756         rewind(s->file);
757         return 0;
758     }
759
760     (void) inflateReset(&s->stream);
761     return fseek(s->file, s->startpos, SEEK_SET);
762 }
763
764 /* ===========================================================================
765      Returns the starting position for the next gzread or gzwrite on the
766    given compressed file. This position represents a number of bytes in the
767    uncompressed data stream.
768 */
769 z_off_t ZEXPORT gztell (file)
770     gzFile file;
771 {
772     return gzseek(file, 0L, SEEK_CUR);
773 }
774
775 /* ===========================================================================
776      Returns 1 when EOF has previously been detected reading the given
777    input stream, otherwise zero.
778 */
779 int ZEXPORT gzeof (file)
780     gzFile file;
781 {
782     gz_stream *s = (gz_stream*)file;
783     
784     return (s == NULL || s->mode != 'r') ? 0 : s->z_eof;
785 }
786
787 /* ===========================================================================
788    Outputs a long in LSB order to the given file
789 */
790 local void putLong (file, x)
791     FILE *file;
792     uLong x;
793 {
794     int n;
795     for (n = 0; n < 4; n++) {
796         fputc((int)(x & 0xff), file);
797         x >>= 8;
798     }
799 }
800
801 /* ===========================================================================
802    Reads a long in LSB order from the given gz_stream. Sets z_err in case
803    of error.
804 */
805 local uLong getLong (s)
806     gz_stream *s;
807 {
808     uLong x = (uLong)get_byte(s);
809     int c;
810
811     x += ((uLong)get_byte(s))<<8;
812     x += ((uLong)get_byte(s))<<16;
813     c = get_byte(s);
814     if (c == EOF) s->z_err = Z_DATA_ERROR;
815     x += ((uLong)c)<<24;
816     return x;
817 }
818
819 /* ===========================================================================
820      Flushes all pending output if necessary, closes the compressed file
821    and deallocates all the (de)compression state.
822 */
823 int ZEXPORT gzclose (file)
824     gzFile file;
825 {
826     int err;
827     gz_stream *s = (gz_stream*)file;
828
829     if (s == NULL) return Z_STREAM_ERROR;
830
831     if (s->mode == 'w') {
832 #ifdef NO_DEFLATE
833         return Z_STREAM_ERROR;
834 #else
835         err = do_flush (file, Z_FINISH);
836         if (err != Z_OK) return destroy((gz_stream*)file);
837
838         putLong (s->file, s->crc);
839         putLong (s->file, s->stream.total_in);
840 #endif
841     }
842     return destroy((gz_stream*)file);
843 }
844
845 /* ===========================================================================
846      Returns the error message for the last error which occured on the
847    given compressed file. errnum is set to zlib error number. If an
848    error occured in the file system and not in the compression library,
849    errnum is set to Z_ERRNO and the application may consult errno
850    to get the exact error code.
851 */
852 const char*  ZEXPORT gzerror (file, errnum)
853     gzFile file;
854     int *errnum;
855 {
856     char *m;
857     gz_stream *s = (gz_stream*)file;
858
859     if (s == NULL) {
860         *errnum = Z_STREAM_ERROR;
861         return (const char*)ERR_MSG(Z_STREAM_ERROR);
862     }
863     *errnum = s->z_err;
864     if (*errnum == Z_OK) return (const char*)"";
865
866     m =  (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
867
868     if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
869
870     TRYFREE(s->msg);
871     s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
872     strcpy(s->msg, s->path);
873     strcat(s->msg, ": ");
874     strcat(s->msg, m);
875     return (const char*)s->msg;
876 }