home *** CD-ROM | disk | FTP | other *** search
/ Tools / WinSN5.0Ver.iso / NETSCAP.50 / WIN1998.ZIP / ns / modules / zlib / src / gzio.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-04-08  |  16.5 KB  |  538 lines

  1. /* gzio.c -- IO on .gz files
  2.  * Copyright (C) 1995-1996 Jean-loup Gailly.
  3.  * For conditions of distribution and use, see copyright notice in zlib.h
  4.  */
  5. /* This file was modified since it was taken from the zlib distribution */
  6.  
  7. /* $Id: gzio.c,v 3.1 1998/03/28 03:36:11 ltabb Exp $ */
  8.  
  9. #include <stdio.h>
  10.  
  11. #include "zutil.h"
  12.  
  13. struct internal_state {int dummy;}; /* for buggy compilers */
  14.  
  15. #define Z_BUFSIZE 4096
  16.  
  17. #define ALLOC(size) malloc(size)
  18. #define TRYFREE(p) {if (p) free(p);}
  19.  
  20. static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
  21.  
  22. /* gzip flag byte */
  23. #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
  24. #define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
  25. #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
  26. #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
  27. #define COMMENT      0x10 /* bit 4 set: file comment present */
  28. #define RESERVED     0xE0 /* bits 5..7: reserved */
  29.  
  30. typedef struct gz_stream {
  31.     z_stream stream;
  32.     int      z_err;   /* error code for last stream operation */
  33.     int      z_eof;   /* set if end of input file */
  34.     FILE     *file;   /* .gz file */
  35.     Byte     *inbuf;  /* input buffer */
  36.     Byte     *outbuf; /* output buffer */
  37.     uLong    crc;     /* crc32 of uncompressed data */
  38.     char     *msg;    /* error message */
  39.     char     *path;   /* path name for debugging only */
  40.     int      transparent; /* 1 if input file is not a .gz file */
  41.     char     mode;    /* 'w' or 'r' */
  42. } gz_stream;
  43.  
  44.  
  45. local gzFile gz_open      OF((const char *path, const char *mode, int  fd));
  46. local int    get_byte     OF((gz_stream *s));
  47. local void   check_header OF((gz_stream *s));
  48. local int    destroy      OF((gz_stream *s));
  49. local void   putLong      OF((FILE *file, uLong x));
  50. local uLong  getLong      OF((gz_stream *s));
  51.  
  52. /* ===========================================================================
  53.      Opens a gzip (.gz) file for reading or writing. The mode parameter
  54.    is as in fopen ("rb" or "wb"). The file is given either by file descriptor
  55.    or path name (if fd == -1).
  56.      gz_open return NULL if the file could not be opened or if there was
  57.    insufficient memory to allocate the (de)compression state; errno
  58.    can be checked to distinguish the two cases (if errno is zero, the
  59.    zlib error is Z_MEM_ERROR).
  60. */
  61. local gzFile gz_open (path, mode, fd)
  62.     const char *path;
  63.     const char *mode;
  64.     int  fd;
  65. {
  66.     int err;
  67.     int level = Z_DEFAULT_COMPRESSION; /* compression level */
  68.     char *p = (char*)mode;
  69.     gz_stream *s;
  70.     char fmode[80]; /* copy of mode, without the compression level */
  71.     char *m = fmode;
  72.  
  73.     if (!path || !mode) return Z_NULL;
  74.  
  75.     s = (gz_stream *)ALLOC(sizeof(gz_stream));
  76.     if (!s) return Z_NULL;
  77.  
  78.     s->stream.zalloc = (alloc_func)0;
  79.     s->stream.zfree = (free_func)0;
  80.     s->stream.opaque = (voidpf)0;
  81.     s->stream.next_in = s->inbuf = Z_NULL;
  82.     s->stream.next_out = s->outbuf = Z_NULL;
  83.     s->stream.avail_in = s->stream.avail_out = 0;
  84.     s->file = NULL;
  85.     s->z_err = Z_OK;
  86.     s->z_eof = 0;
  87.     s->crc = crc32(0L, Z_NULL, 0);
  88.     s->msg = NULL;
  89.     s->transparent = 0;
  90.  
  91.     s->path = (char*)ALLOC(strlen(path)+1);
  92.     if (s->path == NULL) {
  93.         return destroy(s), (gzFile)Z_NULL;
  94.     }
  95.     strcpy(s->path, path); /* do this early for debugging */
  96.  
  97.     s->mode = '\0';
  98.     do {
  99.         if (*p == 'r') s->mode = 'r';
  100.         if (*p == 'w' || *p == 'a') s->mode = 'w';
  101.         if (*p >= '0' && *p <= '9') {
  102.         level = *p - '0';
  103.     } else {
  104.         *m++ = *p; /* copy the mode */
  105.     }
  106.     } while (*p++ && m != fmode + sizeof(fmode));
  107.     if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
  108.     
  109.     if (s->mode == 'w') {
  110.         err = deflateInit2(&(s->stream), level,
  111.                            Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, 0);
  112.         /* windowBits is passed < 0 to suppress zlib header */
  113.  
  114.         s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
  115.  
  116.         if (err != Z_OK || s->outbuf == Z_NULL) {
  117.             return destroy(s), (gzFile)Z_NULL;
  118.         }
  119.     } else {
  120.         err = inflateInit2(&(s->stream), -MAX_WBITS);
  121.         s->stream.next_in  = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
  122.  
  123.         if (err != Z_OK || s->inbuf == Z_NULL) {
  124.             return destroy(s), (gzFile)Z_NULL;
  125.         }
  126.     }
  127.     s->stream.avail_out = Z_BUFSIZE;
  128.  
  129.     errno = 0;
  130.     s->file = fd < 0 ? FOPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
  131.  
  132.     if (s->file == NULL) {
  133.         return destroy(s), (gzFile)Z_NULL;
  134.     }
  135.     if (s->mode == 'w') {
  136.         /* Write a very simple .gz header:
  137.          */
  138.         fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
  139.              Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
  140.     } else {
  141.     check_header(s); /* skip the .gz header */
  142.     }
  143.     return (gzFile)s;
  144. }
  145.  
  146. /* ===========================================================================
  147.      Opens a gzip (.gz) file for reading or writing.
  148. */
  149. #ifdef NETSCAPE
  150. PR_PUBLIC_API(extern gzFile) gzopen  (const char *path, const char *mode)
  151. #else
  152. extern gzFile EXPORT gzopen  OF((const char *path, const char *mode))
  153. #endif
  154. {
  155.     return gz_open (path, mode, -1);
  156. }
  157.  
  158. /* ===========================================================================
  159.      Associate a gzFile with the file descriptor fd. fd is not dup'ed here
  160.    to mimic the behavio(u)r of fdopen.
  161. */
  162. #ifdef NETSCAPE
  163. PR_PUBLIC_API(extern gzFile) gzdopen  (int fd, const char *mode)
  164. #else
  165. extern gzFile EXPORT gzdopen  OF((int fd, const char *mode))
  166. #endif
  167. {
  168.     char name[20];
  169.  
  170.     if (fd < 0) return (gzFile)Z_NULL;
  171.     sprintf(name, "<fd:%d>", fd); /* for debugging */
  172.  
  173.     return gz_open (name, mode, fd);
  174. }
  175.  
  176. /* ===========================================================================
  177.      Read a byte from a gz_stream; update next_in and avail_in. Return EOF
  178.    for end of file.
  179.    IN assertion: the stream s has been sucessfully opened for reading.
  180. */
  181. local int get_byte(s)
  182.     gz_stream *s;
  183. {
  184.     if (s->z_eof) return EOF;
  185.     if (s->stream.avail_in == 0) {
  186.     errno = 0;
  187.     s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
  188.     if (s->stream.avail_in == 0) {
  189.         s->z_eof = 1;
  190.         if (ferror(s->file)) s->z_err = Z_ERRNO;
  191.         return EOF;
  192.     }
  193.     s->stream.next_in = s->inbuf;
  194.     }
  195.     s->stream.avail_in--;
  196.     return *(s->stream.next_in)++;
  197. }
  198.  
  199. /* ===========================================================================
  200.       Check the gzip header of a gz_stream opened for reading. Set the stream
  201.     mode to transparent if the gzip magic header is not present; set s->err
  202.     to Z_DATA_ERROR if the magic header is present but the rest of the header
  203.     is incorrect.
  204.     IN assertion: the stream s has already been created sucessfully;
  205.        s->stream.avail_in is zero for the first time, but may be non-zero
  206.        for concatenated .gz files.
  207. */
  208. local void check_header(s)
  209.     gz_stream *s;
  210. {
  211.     int method; /* method byte */
  212.     int flags;  /* flags byte */
  213.     uInt len;
  214.     int c;
  215.  
  216.     /* Check the gzip magic header */
  217.     for (len = 0; len < 2; len++) {
  218.     c = get_byte(s);
  219.     if (c != gz_magic[len]) {
  220.         s->transparent = 1;
  221.         if (c != EOF) s->stream.avail_in++, s->stream.next_in--;
  222.         s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END;
  223.         return;
  224.     }
  225.     }
  226.     method = get_byte(s);
  227.     flags = get_byte(s);
  228.     if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
  229.     s->z_err = Z_DATA_ERROR;
  230.     return;
  231.     }
  232.  
  233.     /* Discard time, xflags and OS code: */
  234.     for (len = 0; len < 6; len++) (void)get_byte(s);
  235.  
  236.     if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
  237.     len  =  (uInt)get_byte(s);
  238.     len += ((uInt)get_byte(s))<<8;
  239.     /* len is garbage if EOF but the loop below will quit anyway */
  240.     while (len-- != 0 && get_byte(s) != EOF) ;
  241.     }
  242.     if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
  243.     while ((c = get_byte(s)) != 0 && c != EOF) ;
  244.     }
  245.     if ((flags & COMMENT) != 0) {   /* skip the .gz file comment */
  246.     while ((c = get_byte(s)) != 0 && c != EOF) ;
  247.     }
  248.     if ((flags & HEAD_CRC) != 0) {  /* skip the header crc */
  249.     for (len = 0; len < 2; len++) (void)get_byte(s);
  250.     }
  251.     s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
  252. }
  253.  
  254.  /* ===========================================================================
  255.  * Cleanup then free the given gz_stream. Return a zlib error code.
  256.    Try freeing in the reverse order of allocations.
  257.  */
  258. local int destroy (s)
  259.     gz_stream *s;
  260. {
  261.     int err = Z_OK;
  262.  
  263.     if (!s) return Z_STREAM_ERROR;
  264.  
  265.     TRYFREE(s->msg);
  266.  
  267.     if (s->stream.state != NULL) {
  268.        if (s->mode == 'w') {
  269.            err = deflateEnd(&(s->stream));
  270.        } else if (s->mode == 'r') {
  271.            err = inflateEnd(&(s->stream));
  272.        }
  273.     }
  274.     if (s->file != NULL && fclose(s->file)) {
  275.         err = Z_ERRNO;
  276.     }
  277.     if (s->z_err < 0) err = s->z_err;
  278.  
  279.     TRYFREE(s->inbuf);
  280.     TRYFREE(s->outbuf);
  281.     TRYFREE(s->path);
  282.     TRYFREE(s);
  283.     return err;
  284. }
  285.  
  286. /* ===========================================================================
  287.      Reads the given number of uncompressed bytes from the compressed file.
  288.    gzread returns the number of bytes actually read (0 for end of file).
  289. */
  290. #ifdef NETSCAPE
  291. PR_PUBLIC_API(extern int)    gzread  (gzFile file, voidp buf, unsigned len)
  292. #else
  293. extern int EXPORT    gzread  OF((gzFile file, voidp buf, unsigned len))
  294. #endif
  295. {
  296.     gz_stream *s = (gz_stream*)file;
  297.     Bytef *start = buf; /* starting point for crc computation */
  298.     Byte  *next_out; /* == stream.next_out but not forced far (for MSDOS) */
  299.  
  300.     if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
  301.  
  302.     if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
  303.     if (s->z_err == Z_STREAM_END) return 0;  /* EOF */
  304.  
  305.     s->stream.next_out = next_out = buf;
  306.     s->stream.avail_out = len;
  307.  
  308.     while (s->stream.avail_out != 0) {
  309.  
  310.     if (s->transparent) {
  311.         /* Copy first the lookahead bytes: */
  312.         uInt n = s->stream.avail_in;
  313.         if (n > s->stream.avail_out) n = s->stream.avail_out;
  314.         if (n > 0) {
  315.         zmemcpy(s->stream.next_out, s->stream.next_in, n);
  316.         next_out += n;
  317.         s->stream.next_out = next_out;
  318.         s->stream.next_in   += n;
  319.         s->stream.avail_out -= n;
  320.         s->stream.avail_in  -= n;
  321.         }
  322.         if (s->stream.avail_out > 0) {
  323.         s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out,
  324.                          s->file);
  325.         }
  326.         return (int)(len - s->stream.avail_out);
  327.     }
  328.         if (s->stream.avail_in == 0 && !s->z_eof) {
  329.  
  330.             errno = 0;
  331.             s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
  332.             if (s->stream.avail_in == 0) {
  333.                 s->z_eof = 1;
  334.         if (ferror(s->file)) {
  335.             s->z_err = Z_ERRNO;
  336.             break;
  337.         }
  338.             }
  339.             s->stream.next_in = s->inbuf;
  340.         }
  341.         s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
  342.  
  343.     if (s->z_err == Z_STREAM_END) {
  344.         /* Check CRC and original size */
  345.         s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
  346.         start = s->stream.next_out;
  347.  
  348.         if (getLong(s) != s->crc || getLong(s) != s->stream.total_out) {
  349.         s->z_err = Z_DATA_ERROR;
  350.         } else {
  351.         /* Check for concatenated .gz files: */
  352.         check_header(s);
  353.         if (s->z_err == Z_OK) {
  354.             inflateReset(&(s->stream));
  355.             s->crc = crc32(0L, Z_NULL, 0);
  356.         }
  357.         }
  358.     }
  359.     if (s->z_err != Z_OK || s->z_eof) break;
  360.     }
  361.     s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
  362.  
  363.     return (int)(len - s->stream.avail_out);
  364. }
  365.  
  366. /* ===========================================================================
  367.      Writes the given number of uncompressed bytes into the compressed file.
  368.    gzwrite returns the number of bytes actually written (0 in case of error).
  369. */
  370. #ifdef NETSCAPE
  371. PR_PUBLIC_API(extern int)    gzwrite (gzFile file, const voidp buf, unsigned len)
  372. #else
  373. extern int EXPORT    gzwrite OF((gzFile file, const voidp buf, unsigned len))
  374. #endif
  375. {
  376.     gz_stream *s = (gz_stream*)file;
  377.  
  378.     if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  379.  
  380.     s->stream.next_in = buf;
  381.     s->stream.avail_in = len;
  382.  
  383.     while (s->stream.avail_in != 0) {
  384.  
  385.         if (s->stream.avail_out == 0) {
  386.  
  387.             s->stream.next_out = s->outbuf;
  388.             if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
  389.                 s->z_err = Z_ERRNO;
  390.                 break;
  391.             }
  392.             s->stream.avail_out = Z_BUFSIZE;
  393.         }
  394.         s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
  395.         if (s->z_err != Z_OK) break;
  396.     }
  397.     s->crc = crc32(s->crc, buf, len);
  398.  
  399.     return (int)(len - s->stream.avail_in);
  400. }
  401.  
  402. /* ===========================================================================
  403.      Flushes all pending output into the compressed file. The parameter
  404.    flush is as in the deflate() function.
  405.      gzflush should be called only when strictly necessary because it can
  406.    degrade compression.
  407. */
  408. #ifdef NETSCAPE
  409. PR_PUBLIC_API(extern int)    gzflush (gzFile file, int flush)
  410. #else
  411. extern int EXPORT    gzflush OF((gzFile file, int flush))
  412. #endif
  413. {
  414.     uInt len;
  415.     int done = 0;
  416.     gz_stream *s = (gz_stream*)file;
  417.  
  418.     if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
  419.  
  420.     s->stream.avail_in = 0; /* should be zero already anyway */
  421.  
  422.     for (;;) {
  423.         len = Z_BUFSIZE - s->stream.avail_out;
  424.  
  425.         if (len != 0) {
  426.             if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
  427.                 s->z_err = Z_ERRNO;
  428.                 return Z_ERRNO;
  429.             }
  430.             s->stream.next_out = s->outbuf;
  431.             s->stream.avail_out = Z_BUFSIZE;
  432.         }
  433.         if (done) break;
  434.         s->z_err = deflate(&(s->stream), flush);
  435.  
  436.         /* deflate has finished flushing only when it hasn't used up
  437.          * all the available space in the output buffer: 
  438.          */
  439.         done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
  440.  
  441.         if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
  442.     }
  443.     fflush(s->file);
  444.     return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
  445. }
  446.  
  447. /* ===========================================================================
  448.    Outputs a long in LSB order to the given file
  449. */
  450. local void putLong (file, x)
  451.     FILE *file;
  452.     uLong x;
  453. {
  454.     int n;
  455.     for (n = 0; n < 4; n++) {
  456.         fputc((int)(x & 0xff), file);
  457.         x >>= 8;
  458.     }
  459. }
  460.  
  461. /* ===========================================================================
  462.    Reads a long in LSB order from the given gz_stream. Sets 
  463. */
  464. local uLong getLong (s)
  465.     gz_stream *s;
  466. {
  467.     uLong x = (uLong)get_byte(s);
  468.     int c;
  469.  
  470.     x += ((uLong)get_byte(s))<<8;
  471.     x += ((uLong)get_byte(s))<<16;
  472.     c = get_byte(s);
  473.     if (c == EOF) s->z_err = Z_DATA_ERROR;
  474.     x += ((uLong)c)<<24;
  475.     return x;
  476. }
  477.  
  478. /* ===========================================================================
  479.      Flushes all pending output if necessary, closes the compressed file
  480.    and deallocates all the (de)compression state.
  481. */
  482. #ifdef NETSCAPE
  483. PR_PUBLIC_API(extern int)    gzclose (gzFile file)
  484. #else
  485. extern int EXPORT    gzclose OF((gzFile file))
  486. #endif
  487. {
  488.     int err;
  489.     gz_stream *s = (gz_stream*)file;
  490.  
  491.     if (s == NULL) return Z_STREAM_ERROR;
  492.  
  493.     if (s->mode == 'w') {
  494.         err = gzflush (file, Z_FINISH);
  495.         if (err != Z_OK) return destroy(file);
  496.  
  497.         putLong (s->file, s->crc);
  498.         putLong (s->file, s->stream.total_in);
  499.  
  500.     }
  501.     return destroy(file);
  502. }
  503.  
  504. /* ===========================================================================
  505.      Returns the error message for the last error which occured on the
  506.    given compressed file. errnum is set to zlib error number. If an
  507.    error occured in the file system and not in the compression library,
  508.    errnum is set to Z_ERRNO and the application may consult errno
  509.    to get the exact error code.
  510. */
  511. #ifdef NETSCAPE
  512. PR_PUBLIC_API(extern const char *) gzerror (gzFile file, int *errnum)
  513. #else
  514. extern const char * EXPORT gzerror OF((gzFile file, int *errnum))
  515. #endif
  516. {
  517.     char *m;
  518.     gz_stream *s = (gz_stream*)file;
  519.  
  520.     if (s == NULL) {
  521.         *errnum = Z_STREAM_ERROR;
  522.         return (const char*)ERR_MSG(Z_STREAM_ERROR);
  523.     }
  524.     *errnum = s->z_err;
  525.     if (*errnum == Z_OK) return (const char*)"";
  526.  
  527.     m =  (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
  528.  
  529.     if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
  530.  
  531.     TRYFREE(s->msg);
  532.     s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
  533.     strcpy(s->msg, s->path);
  534.     strcat(s->msg, ": ");
  535.     strcat(s->msg, m);
  536.     return (const char*)s->msg;
  537. }
  538.