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