kusano fc6ab3
/*
kusano fc6ab3
 * puff.c
kusano fc6ab3
 * Copyright (C) 2002-2013 Mark Adler
kusano fc6ab3
 * For conditions of distribution and use, see copyright notice in puff.h
kusano fc6ab3
 * version 2.3, 21 Jan 2013
kusano fc6ab3
 *
kusano fc6ab3
 * puff.c is a simple inflate written to be an unambiguous way to specify the
kusano fc6ab3
 * deflate format.  It is not written for speed but rather simplicity.  As a
kusano fc6ab3
 * side benefit, this code might actually be useful when small code is more
kusano fc6ab3
 * important than speed, such as bootstrap applications.  For typical deflate
kusano fc6ab3
 * data, zlib's inflate() is about four times as fast as puff().  zlib's
kusano fc6ab3
 * inflate compiles to around 20K on my machine, whereas puff.c compiles to
kusano fc6ab3
 * around 4K on my machine (a PowerPC using GNU cc).  If the faster decode()
kusano fc6ab3
 * function here is used, then puff() is only twice as slow as zlib's
kusano fc6ab3
 * inflate().
kusano fc6ab3
 *
kusano fc6ab3
 * All dynamically allocated memory comes from the stack.  The stack required
kusano fc6ab3
 * is less than 2K bytes.  This code is compatible with 16-bit int's and
kusano fc6ab3
 * assumes that long's are at least 32 bits.  puff.c uses the short data type,
kusano fc6ab3
 * assumed to be 16 bits, for arrays in order to to conserve memory.  The code
kusano fc6ab3
 * works whether integers are stored big endian or little endian.
kusano fc6ab3
 *
kusano fc6ab3
 * In the comments below are "Format notes" that describe the inflate process
kusano fc6ab3
 * and document some of the less obvious aspects of the format.  This source
kusano fc6ab3
 * code is meant to supplement RFC 1951, which formally describes the deflate
kusano fc6ab3
 * format:
kusano fc6ab3
 *
kusano fc6ab3
 *    http://www.zlib.org/rfc-deflate.html
kusano fc6ab3
 */
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Change history:
kusano fc6ab3
 *
kusano fc6ab3
 * 1.0  10 Feb 2002     - First version
kusano fc6ab3
 * 1.1  17 Feb 2002     - Clarifications of some comments and notes
kusano fc6ab3
 *                      - Update puff() dest and source pointers on negative
kusano fc6ab3
 *                        errors to facilitate debugging deflators
kusano fc6ab3
 *                      - Remove longest from struct huffman -- not needed
kusano fc6ab3
 *                      - Simplify offs[] index in construct()
kusano fc6ab3
 *                      - Add input size and checking, using longjmp() to
kusano fc6ab3
 *                        maintain easy readability
kusano fc6ab3
 *                      - Use short data type for large arrays
kusano fc6ab3
 *                      - Use pointers instead of long to specify source and
kusano fc6ab3
 *                        destination sizes to avoid arbitrary 4 GB limits
kusano fc6ab3
 * 1.2  17 Mar 2002     - Add faster version of decode(), doubles speed (!),
kusano fc6ab3
 *                        but leave simple version for readabilty
kusano fc6ab3
 *                      - Make sure invalid distances detected if pointers
kusano fc6ab3
 *                        are 16 bits
kusano fc6ab3
 *                      - Fix fixed codes table error
kusano fc6ab3
 *                      - Provide a scanning mode for determining size of
kusano fc6ab3
 *                        uncompressed data
kusano fc6ab3
 * 1.3  20 Mar 2002     - Go back to lengths for puff() parameters [Gailly]
kusano fc6ab3
 *                      - Add a puff.h file for the interface
kusano fc6ab3
 *                      - Add braces in puff() for else do [Gailly]
kusano fc6ab3
 *                      - Use indexes instead of pointers for readability
kusano fc6ab3
 * 1.4  31 Mar 2002     - Simplify construct() code set check
kusano fc6ab3
 *                      - Fix some comments
kusano fc6ab3
 *                      - Add FIXLCODES #define
kusano fc6ab3
 * 1.5   6 Apr 2002     - Minor comment fixes
kusano fc6ab3
 * 1.6   7 Aug 2002     - Minor format changes
kusano fc6ab3
 * 1.7   3 Mar 2003     - Added test code for distribution
kusano fc6ab3
 *                      - Added zlib-like license
kusano fc6ab3
 * 1.8   9 Jan 2004     - Added some comments on no distance codes case
kusano fc6ab3
 * 1.9  21 Feb 2008     - Fix bug on 16-bit integer architectures [Pohland]
kusano fc6ab3
 *                      - Catch missing end-of-block symbol error
kusano fc6ab3
 * 2.0  25 Jul 2008     - Add #define to permit distance too far back
kusano fc6ab3
 *                      - Add option in TEST code for puff to write the data
kusano fc6ab3
 *                      - Add option in TEST code to skip input bytes
kusano fc6ab3
 *                      - Allow TEST code to read from piped stdin
kusano fc6ab3
 * 2.1   4 Apr 2010     - Avoid variable initialization for happier compilers
kusano fc6ab3
 *                      - Avoid unsigned comparisons for even happier compilers
kusano fc6ab3
 * 2.2  25 Apr 2010     - Fix bug in variable initializations [Oberhumer]
kusano fc6ab3
 *                      - Add const where appropriate [Oberhumer]
kusano fc6ab3
 *                      - Split if's and ?'s for coverage testing
kusano fc6ab3
 *                      - Break out test code to separate file
kusano fc6ab3
 *                      - Move NIL to puff.h
kusano fc6ab3
 *                      - Allow incomplete code only if single code length is 1
kusano fc6ab3
 *                      - Add full code coverage test to Makefile
kusano fc6ab3
 * 2.3  21 Jan 2013     - Check for invalid code length codes in dynamic blocks
kusano fc6ab3
 */
kusano fc6ab3
kusano fc6ab3
#include <setjmp.h>             /* for setjmp(), longjmp(), and jmp_buf */</setjmp.h>
kusano fc6ab3
#include "puff.h"               /* prototype for puff() */
kusano fc6ab3
kusano fc6ab3
#define local static            /* for local function definitions */
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Maximums for allocations and loops.  It is not useful to change these --
kusano fc6ab3
 * they are fixed by the deflate format.
kusano fc6ab3
 */
kusano fc6ab3
#define MAXBITS 15              /* maximum bits in a code */
kusano fc6ab3
#define MAXLCODES 286           /* maximum number of literal/length codes */
kusano fc6ab3
#define MAXDCODES 30            /* maximum number of distance codes */
kusano fc6ab3
#define MAXCODES (MAXLCODES+MAXDCODES)  /* maximum codes lengths to read */
kusano fc6ab3
#define FIXLCODES 288           /* number of fixed literal/length codes */
kusano fc6ab3
kusano fc6ab3
/* input and output state */
kusano fc6ab3
struct state {
kusano fc6ab3
    /* output state */
kusano fc6ab3
    unsigned char *out;         /* output buffer */
kusano fc6ab3
    unsigned long outlen;       /* available space at out */
kusano fc6ab3
    unsigned long outcnt;       /* bytes written to out so far */
kusano fc6ab3
kusano fc6ab3
    /* input state */
kusano fc6ab3
    const unsigned char *in;    /* input buffer */
kusano fc6ab3
    unsigned long inlen;        /* available input at in */
kusano fc6ab3
    unsigned long incnt;        /* bytes read so far */
kusano fc6ab3
    int bitbuf;                 /* bit buffer */
kusano fc6ab3
    int bitcnt;                 /* number of bits in bit buffer */
kusano fc6ab3
kusano fc6ab3
    /* input limit error return state for bits() and decode() */
kusano fc6ab3
    jmp_buf env;
kusano fc6ab3
};
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Return need bits from the input stream.  This always leaves less than
kusano fc6ab3
 * eight bits in the buffer.  bits() works properly for need == 0.
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - Bits are stored in bytes from the least significant bit to the most
kusano fc6ab3
 *   significant bit.  Therefore bits are dropped from the bottom of the bit
kusano fc6ab3
 *   buffer, using shift right, and new bytes are appended to the top of the
kusano fc6ab3
 *   bit buffer, using shift left.
kusano fc6ab3
 */
kusano fc6ab3
local int bits(struct state *s, int need)
kusano fc6ab3
{
kusano fc6ab3
    long val;           /* bit accumulator (can use up to 20 bits) */
kusano fc6ab3
kusano fc6ab3
    /* load at least need bits into val */
kusano fc6ab3
    val = s->bitbuf;
kusano fc6ab3
    while (s->bitcnt < need) {
kusano fc6ab3
        if (s->incnt == s->inlen)
kusano fc6ab3
            longjmp(s->env, 1);         /* out of input */
kusano fc6ab3
        val |= (long)(s->in[s->incnt++]) << s->bitcnt;  /* load eight bits */
kusano fc6ab3
        s->bitcnt += 8;
kusano fc6ab3
    }
kusano fc6ab3
kusano fc6ab3
    /* drop need bits and update buffer, always zero to seven bits left */
kusano fc6ab3
    s->bitbuf = (int)(val >> need);
kusano fc6ab3
    s->bitcnt -= need;
kusano fc6ab3
kusano fc6ab3
    /* return need bits, zeroing the bits above that */
kusano fc6ab3
    return (int)(val & ((1L << need) - 1));
kusano fc6ab3
}
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Process a stored block.
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - After the two-bit stored block type (00), the stored block length and
kusano fc6ab3
 *   stored bytes are byte-aligned for fast copying.  Therefore any leftover
kusano fc6ab3
 *   bits in the byte that has the last bit of the type, as many as seven, are
kusano fc6ab3
 *   discarded.  The value of the discarded bits are not defined and should not
kusano fc6ab3
 *   be checked against any expectation.
kusano fc6ab3
 *
kusano fc6ab3
 * - The second inverted copy of the stored block length does not have to be
kusano fc6ab3
 *   checked, but it's probably a good idea to do so anyway.
kusano fc6ab3
 *
kusano fc6ab3
 * - A stored block can have zero length.  This is sometimes used to byte-align
kusano fc6ab3
 *   subsets of the compressed data for random access or partial recovery.
kusano fc6ab3
 */
kusano fc6ab3
local int stored(struct state *s)
kusano fc6ab3
{
kusano fc6ab3
    unsigned len;       /* length of stored block */
kusano fc6ab3
kusano fc6ab3
    /* discard leftover bits from current byte (assumes s->bitcnt < 8) */
kusano fc6ab3
    s->bitbuf = 0;
kusano fc6ab3
    s->bitcnt = 0;
kusano fc6ab3
kusano fc6ab3
    /* get length and check against its one's complement */
kusano fc6ab3
    if (s->incnt + 4 > s->inlen)
kusano fc6ab3
        return 2;                               /* not enough input */
kusano fc6ab3
    len = s->in[s->incnt++];
kusano fc6ab3
    len |= s->in[s->incnt++] << 8;
kusano fc6ab3
    if (s->in[s->incnt++] != (~len & 0xff) ||
kusano fc6ab3
        s->in[s->incnt++] != ((~len >> 8) & 0xff))
kusano fc6ab3
        return -2;                              /* didn't match complement! */
kusano fc6ab3
kusano fc6ab3
    /* copy len bytes from in to out */
kusano fc6ab3
    if (s->incnt + len > s->inlen)
kusano fc6ab3
        return 2;                               /* not enough input */
kusano fc6ab3
    if (s->out != NIL) {
kusano fc6ab3
        if (s->outcnt + len > s->outlen)
kusano fc6ab3
            return 1;                           /* not enough output space */
kusano fc6ab3
        while (len--)
kusano fc6ab3
            s->out[s->outcnt++] = s->in[s->incnt++];
kusano fc6ab3
    }
kusano fc6ab3
    else {                                      /* just scanning */
kusano fc6ab3
        s->outcnt += len;
kusano fc6ab3
        s->incnt += len;
kusano fc6ab3
    }
kusano fc6ab3
kusano fc6ab3
    /* done with a valid stored block */
kusano fc6ab3
    return 0;
kusano fc6ab3
}
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Huffman code decoding tables.  count[1..MAXBITS] is the number of symbols of
kusano fc6ab3
 * each length, which for a canonical code are stepped through in order.
kusano fc6ab3
 * symbol[] are the symbol values in canonical order, where the number of
kusano fc6ab3
 * entries is the sum of the counts in count[].  The decoding process can be
kusano fc6ab3
 * seen in the function decode() below.
kusano fc6ab3
 */
kusano fc6ab3
struct huffman {
kusano fc6ab3
    short *count;       /* number of symbols of each length */
kusano fc6ab3
    short *symbol;      /* canonically ordered symbols */
kusano fc6ab3
};
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Decode a code from the stream s using huffman table h.  Return the symbol or
kusano fc6ab3
 * a negative value if there is an error.  If all of the lengths are zero, i.e.
kusano fc6ab3
 * an empty code, or if the code is incomplete and an invalid code is received,
kusano fc6ab3
 * then -10 is returned after reading MAXBITS bits.
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - The codes as stored in the compressed data are bit-reversed relative to
kusano fc6ab3
 *   a simple integer ordering of codes of the same lengths.  Hence below the
kusano fc6ab3
 *   bits are pulled from the compressed data one at a time and used to
kusano fc6ab3
 *   build the code value reversed from what is in the stream in order to
kusano fc6ab3
 *   permit simple integer comparisons for decoding.  A table-based decoding
kusano fc6ab3
 *   scheme (as used in zlib) does not need to do this reversal.
kusano fc6ab3
 *
kusano fc6ab3
 * - The first code for the shortest length is all zeros.  Subsequent codes of
kusano fc6ab3
 *   the same length are simply integer increments of the previous code.  When
kusano fc6ab3
 *   moving up a length, a zero bit is appended to the code.  For a complete
kusano fc6ab3
 *   code, the last code of the longest length will be all ones.
kusano fc6ab3
 *
kusano fc6ab3
 * - Incomplete codes are handled by this decoder, since they are permitted
kusano fc6ab3
 *   in the deflate format.  See the format notes for fixed() and dynamic().
kusano fc6ab3
 */
kusano fc6ab3
#ifdef SLOW
kusano fc6ab3
local int decode(struct state *s, const struct huffman *h)
kusano fc6ab3
{
kusano fc6ab3
    int len;            /* current number of bits in code */
kusano fc6ab3
    int code;           /* len bits being decoded */
kusano fc6ab3
    int first;          /* first code of length len */
kusano fc6ab3
    int count;          /* number of codes of length len */
kusano fc6ab3
    int index;          /* index of first code of length len in symbol table */
kusano fc6ab3
kusano fc6ab3
    code = first = index = 0;
kusano fc6ab3
    for (len = 1; len <= MAXBITS; len++) {
kusano fc6ab3
        code |= bits(s, 1);             /* get next bit */
kusano fc6ab3
        count = h->count[len];
kusano fc6ab3
        if (code - count < first)       /* if length len, return symbol */
kusano fc6ab3
            return h->symbol[index + (code - first)];
kusano fc6ab3
        index += count;                 /* else update for next length */
kusano fc6ab3
        first += count;
kusano fc6ab3
        first <<= 1;
kusano fc6ab3
        code <<= 1;
kusano fc6ab3
    }
kusano fc6ab3
    return -10;                         /* ran out of codes */
kusano fc6ab3
}
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * A faster version of decode() for real applications of this code.   It's not
kusano fc6ab3
 * as readable, but it makes puff() twice as fast.  And it only makes the code
kusano fc6ab3
 * a few percent larger.
kusano fc6ab3
 */
kusano fc6ab3
#else /* !SLOW */
kusano fc6ab3
local int decode(struct state *s, const struct huffman *h)
kusano fc6ab3
{
kusano fc6ab3
    int len;            /* current number of bits in code */
kusano fc6ab3
    int code;           /* len bits being decoded */
kusano fc6ab3
    int first;          /* first code of length len */
kusano fc6ab3
    int count;          /* number of codes of length len */
kusano fc6ab3
    int index;          /* index of first code of length len in symbol table */
kusano fc6ab3
    int bitbuf;         /* bits from stream */
kusano fc6ab3
    int left;           /* bits left in next or left to process */
kusano fc6ab3
    short *next;        /* next number of codes */
kusano fc6ab3
kusano fc6ab3
    bitbuf = s->bitbuf;
kusano fc6ab3
    left = s->bitcnt;
kusano fc6ab3
    code = first = index = 0;
kusano fc6ab3
    len = 1;
kusano fc6ab3
    next = h->count + 1;
kusano fc6ab3
    while (1) {
kusano fc6ab3
        while (left--) {
kusano fc6ab3
            code |= bitbuf & 1;
kusano fc6ab3
            bitbuf >>= 1;
kusano fc6ab3
            count = *next++;
kusano fc6ab3
            if (code - count < first) { /* if length len, return symbol */
kusano fc6ab3
                s->bitbuf = bitbuf;
kusano fc6ab3
                s->bitcnt = (s->bitcnt - len) & 7;
kusano fc6ab3
                return h->symbol[index + (code - first)];
kusano fc6ab3
            }
kusano fc6ab3
            index += count;             /* else update for next length */
kusano fc6ab3
            first += count;
kusano fc6ab3
            first <<= 1;
kusano fc6ab3
            code <<= 1;
kusano fc6ab3
            len++;
kusano fc6ab3
        }
kusano fc6ab3
        left = (MAXBITS+1) - len;
kusano fc6ab3
        if (left == 0)
kusano fc6ab3
            break;
kusano fc6ab3
        if (s->incnt == s->inlen)
kusano fc6ab3
            longjmp(s->env, 1);         /* out of input */
kusano fc6ab3
        bitbuf = s->in[s->incnt++];
kusano fc6ab3
        if (left > 8)
kusano fc6ab3
            left = 8;
kusano fc6ab3
    }
kusano fc6ab3
    return -10;                         /* ran out of codes */
kusano fc6ab3
}
kusano fc6ab3
#endif /* SLOW */
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Given the list of code lengths length[0..n-1] representing a canonical
kusano fc6ab3
 * Huffman code for n symbols, construct the tables required to decode those
kusano fc6ab3
 * codes.  Those tables are the number of codes of each length, and the symbols
kusano fc6ab3
 * sorted by length, retaining their original order within each length.  The
kusano fc6ab3
 * return value is zero for a complete code set, negative for an over-
kusano fc6ab3
 * subscribed code set, and positive for an incomplete code set.  The tables
kusano fc6ab3
 * can be used if the return value is zero or positive, but they cannot be used
kusano fc6ab3
 * if the return value is negative.  If the return value is zero, it is not
kusano fc6ab3
 * possible for decode() using that table to return an error--any stream of
kusano fc6ab3
 * enough bits will resolve to a symbol.  If the return value is positive, then
kusano fc6ab3
 * it is possible for decode() using that table to return an error for received
kusano fc6ab3
 * codes past the end of the incomplete lengths.
kusano fc6ab3
 *
kusano fc6ab3
 * Not used by decode(), but used for error checking, h->count[0] is the number
kusano fc6ab3
 * of the n symbols not in the code.  So n - h->count[0] is the number of
kusano fc6ab3
 * codes.  This is useful for checking for incomplete codes that have more than
kusano fc6ab3
 * one symbol, which is an error in a dynamic block.
kusano fc6ab3
 *
kusano fc6ab3
 * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS
kusano fc6ab3
 * This is assured by the construction of the length arrays in dynamic() and
kusano fc6ab3
 * fixed() and is not verified by construct().
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - Permitted and expected examples of incomplete codes are one of the fixed
kusano fc6ab3
 *   codes and any code with a single symbol which in deflate is coded as one
kusano fc6ab3
 *   bit instead of zero bits.  See the format notes for fixed() and dynamic().
kusano fc6ab3
 *
kusano fc6ab3
 * - Within a given code length, the symbols are kept in ascending order for
kusano fc6ab3
 *   the code bits definition.
kusano fc6ab3
 */
kusano fc6ab3
local int construct(struct huffman *h, const short *length, int n)
kusano fc6ab3
{
kusano fc6ab3
    int symbol;         /* current symbol when stepping through length[] */
kusano fc6ab3
    int len;            /* current length when stepping through h->count[] */
kusano fc6ab3
    int left;           /* number of possible codes left of current length */
kusano fc6ab3
    short offs[MAXBITS+1];      /* offsets in symbol table for each length */
kusano fc6ab3
kusano fc6ab3
    /* count number of codes of each length */
kusano fc6ab3
    for (len = 0; len <= MAXBITS; len++)
kusano fc6ab3
        h->count[len] = 0;
kusano fc6ab3
    for (symbol = 0; symbol < n; symbol++)
kusano fc6ab3
        (h->count[length[symbol]])++;   /* assumes lengths are within bounds */
kusano fc6ab3
    if (h->count[0] == n)               /* no codes! */
kusano fc6ab3
        return 0;                       /* complete, but decode() will fail */
kusano fc6ab3
kusano fc6ab3
    /* check for an over-subscribed or incomplete set of lengths */
kusano fc6ab3
    left = 1;                           /* one possible code of zero length */
kusano fc6ab3
    for (len = 1; len <= MAXBITS; len++) {
kusano fc6ab3
        left <<= 1;                     /* one more bit, double codes left */
kusano fc6ab3
        left -= h->count[len];          /* deduct count from possible codes */
kusano fc6ab3
        if (left < 0)
kusano fc6ab3
            return left;                /* over-subscribed--return negative */
kusano fc6ab3
    }                                   /* left > 0 means incomplete */
kusano fc6ab3
kusano fc6ab3
    /* generate offsets into symbol table for each length for sorting */
kusano fc6ab3
    offs[1] = 0;
kusano fc6ab3
    for (len = 1; len < MAXBITS; len++)
kusano fc6ab3
        offs[len + 1] = offs[len] + h->count[len];
kusano fc6ab3
kusano fc6ab3
    /*
kusano fc6ab3
     * put symbols in table sorted by length, by symbol order within each
kusano fc6ab3
     * length
kusano fc6ab3
     */
kusano fc6ab3
    for (symbol = 0; symbol < n; symbol++)
kusano fc6ab3
        if (length[symbol] != 0)
kusano fc6ab3
            h->symbol[offs[length[symbol]]++] = symbol;
kusano fc6ab3
kusano fc6ab3
    /* return zero for complete set, positive for incomplete set */
kusano fc6ab3
    return left;
kusano fc6ab3
}
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Decode literal/length and distance codes until an end-of-block code.
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - Compressed data that is after the block type if fixed or after the code
kusano fc6ab3
 *   description if dynamic is a combination of literals and length/distance
kusano fc6ab3
 *   pairs terminated by and end-of-block code.  Literals are simply Huffman
kusano fc6ab3
 *   coded bytes.  A length/distance pair is a coded length followed by a
kusano fc6ab3
 *   coded distance to represent a string that occurs earlier in the
kusano fc6ab3
 *   uncompressed data that occurs again at the current location.
kusano fc6ab3
 *
kusano fc6ab3
 * - Literals, lengths, and the end-of-block code are combined into a single
kusano fc6ab3
 *   code of up to 286 symbols.  They are 256 literals (0..255), 29 length
kusano fc6ab3
 *   symbols (257..285), and the end-of-block symbol (256).
kusano fc6ab3
 *
kusano fc6ab3
 * - There are 256 possible lengths (3..258), and so 29 symbols are not enough
kusano fc6ab3
 *   to represent all of those.  Lengths 3..10 and 258 are in fact represented
kusano fc6ab3
 *   by just a length symbol.  Lengths 11..257 are represented as a symbol and
kusano fc6ab3
 *   some number of extra bits that are added as an integer to the base length
kusano fc6ab3
 *   of the length symbol.  The number of extra bits is determined by the base
kusano fc6ab3
 *   length symbol.  These are in the static arrays below, lens[] for the base
kusano fc6ab3
 *   lengths and lext[] for the corresponding number of extra bits.
kusano fc6ab3
 *
kusano fc6ab3
 * - The reason that 258 gets its own symbol is that the longest length is used
kusano fc6ab3
 *   often in highly redundant files.  Note that 258 can also be coded as the
kusano fc6ab3
 *   base value 227 plus the maximum extra value of 31.  While a good deflate
kusano fc6ab3
 *   should never do this, it is not an error, and should be decoded properly.
kusano fc6ab3
 *
kusano fc6ab3
 * - If a length is decoded, including its extra bits if any, then it is
kusano fc6ab3
 *   followed a distance code.  There are up to 30 distance symbols.  Again
kusano fc6ab3
 *   there are many more possible distances (1..32768), so extra bits are added
kusano fc6ab3
 *   to a base value represented by the symbol.  The distances 1..4 get their
kusano fc6ab3
 *   own symbol, but the rest require extra bits.  The base distances and
kusano fc6ab3
 *   corresponding number of extra bits are below in the static arrays dist[]
kusano fc6ab3
 *   and dext[].
kusano fc6ab3
 *
kusano fc6ab3
 * - Literal bytes are simply written to the output.  A length/distance pair is
kusano fc6ab3
 *   an instruction to copy previously uncompressed bytes to the output.  The
kusano fc6ab3
 *   copy is from distance bytes back in the output stream, copying for length
kusano fc6ab3
 *   bytes.
kusano fc6ab3
 *
kusano fc6ab3
 * - Distances pointing before the beginning of the output data are not
kusano fc6ab3
 *   permitted.
kusano fc6ab3
 *
kusano fc6ab3
 * - Overlapped copies, where the length is greater than the distance, are
kusano fc6ab3
 *   allowed and common.  For example, a distance of one and a length of 258
kusano fc6ab3
 *   simply copies the last byte 258 times.  A distance of four and a length of
kusano fc6ab3
 *   twelve copies the last four bytes three times.  A simple forward copy
kusano fc6ab3
 *   ignoring whether the length is greater than the distance or not implements
kusano fc6ab3
 *   this correctly.  You should not use memcpy() since its behavior is not
kusano fc6ab3
 *   defined for overlapped arrays.  You should not use memmove() or bcopy()
kusano fc6ab3
 *   since though their behavior -is- defined for overlapping arrays, it is
kusano fc6ab3
 *   defined to do the wrong thing in this case.
kusano fc6ab3
 */
kusano fc6ab3
local int codes(struct state *s,
kusano fc6ab3
                const struct huffman *lencode,
kusano fc6ab3
                const struct huffman *distcode)
kusano fc6ab3
{
kusano fc6ab3
    int symbol;         /* decoded symbol */
kusano fc6ab3
    int len;            /* length for copy */
kusano fc6ab3
    unsigned dist;      /* distance for copy */
kusano fc6ab3
    static const short lens[29] = { /* Size base for length codes 257..285 */
kusano fc6ab3
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
kusano fc6ab3
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
kusano fc6ab3
    static const short lext[29] = { /* Extra bits for length codes 257..285 */
kusano fc6ab3
        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
kusano fc6ab3
        3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
kusano fc6ab3
    static const short dists[30] = { /* Offset base for distance codes 0..29 */
kusano fc6ab3
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
kusano fc6ab3
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
kusano fc6ab3
        8193, 12289, 16385, 24577};
kusano fc6ab3
    static const short dext[30] = { /* Extra bits for distance codes 0..29 */
kusano fc6ab3
        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
kusano fc6ab3
        7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
kusano fc6ab3
        12, 12, 13, 13};
kusano fc6ab3
kusano fc6ab3
    /* decode literals and length/distance pairs */
kusano fc6ab3
    do {
kusano fc6ab3
        symbol = decode(s, lencode);
kusano fc6ab3
        if (symbol < 0)
kusano fc6ab3
            return symbol;              /* invalid symbol */
kusano fc6ab3
        if (symbol < 256) {             /* literal: symbol is the byte */
kusano fc6ab3
            /* write out the literal */
kusano fc6ab3
            if (s->out != NIL) {
kusano fc6ab3
                if (s->outcnt == s->outlen)
kusano fc6ab3
                    return 1;
kusano fc6ab3
                s->out[s->outcnt] = symbol;
kusano fc6ab3
            }
kusano fc6ab3
            s->outcnt++;
kusano fc6ab3
        }
kusano fc6ab3
        else if (symbol > 256) {        /* length */
kusano fc6ab3
            /* get and compute length */
kusano fc6ab3
            symbol -= 257;
kusano fc6ab3
            if (symbol >= 29)
kusano fc6ab3
                return -10;             /* invalid fixed code */
kusano fc6ab3
            len = lens[symbol] + bits(s, lext[symbol]);
kusano fc6ab3
kusano fc6ab3
            /* get and check distance */
kusano fc6ab3
            symbol = decode(s, distcode);
kusano fc6ab3
            if (symbol < 0)
kusano fc6ab3
                return symbol;          /* invalid symbol */
kusano fc6ab3
            dist = dists[symbol] + bits(s, dext[symbol]);
kusano fc6ab3
#ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
kusano fc6ab3
            if (dist > s->outcnt)
kusano fc6ab3
                return -11;     /* distance too far back */
kusano fc6ab3
#endif
kusano fc6ab3
kusano fc6ab3
            /* copy length bytes from distance bytes back */
kusano fc6ab3
            if (s->out != NIL) {
kusano fc6ab3
                if (s->outcnt + len > s->outlen)
kusano fc6ab3
                    return 1;
kusano fc6ab3
                while (len--) {
kusano fc6ab3
                    s->out[s->outcnt] =
kusano fc6ab3
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
kusano fc6ab3
                        dist > s->outcnt ?
kusano fc6ab3
                            0 :
kusano fc6ab3
#endif
kusano fc6ab3
                            s->out[s->outcnt - dist];
kusano fc6ab3
                    s->outcnt++;
kusano fc6ab3
                }
kusano fc6ab3
            }
kusano fc6ab3
            else
kusano fc6ab3
                s->outcnt += len;
kusano fc6ab3
        }
kusano fc6ab3
    } while (symbol != 256);            /* end of block symbol */
kusano fc6ab3
kusano fc6ab3
    /* done with a valid fixed or dynamic block */
kusano fc6ab3
    return 0;
kusano fc6ab3
}
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Process a fixed codes block.
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - This block type can be useful for compressing small amounts of data for
kusano fc6ab3
 *   which the size of the code descriptions in a dynamic block exceeds the
kusano fc6ab3
 *   benefit of custom codes for that block.  For fixed codes, no bits are
kusano fc6ab3
 *   spent on code descriptions.  Instead the code lengths for literal/length
kusano fc6ab3
 *   codes and distance codes are fixed.  The specific lengths for each symbol
kusano fc6ab3
 *   can be seen in the "for" loops below.
kusano fc6ab3
 *
kusano fc6ab3
 * - The literal/length code is complete, but has two symbols that are invalid
kusano fc6ab3
 *   and should result in an error if received.  This cannot be implemented
kusano fc6ab3
 *   simply as an incomplete code since those two symbols are in the "middle"
kusano fc6ab3
 *   of the code.  They are eight bits long and the longest literal/length\
kusano fc6ab3
 *   code is nine bits.  Therefore the code must be constructed with those
kusano fc6ab3
 *   symbols, and the invalid symbols must be detected after decoding.
kusano fc6ab3
 *
kusano fc6ab3
 * - The fixed distance codes also have two invalid symbols that should result
kusano fc6ab3
 *   in an error if received.  Since all of the distance codes are the same
kusano fc6ab3
 *   length, this can be implemented as an incomplete code.  Then the invalid
kusano fc6ab3
 *   codes are detected while decoding.
kusano fc6ab3
 */
kusano fc6ab3
local int fixed(struct state *s)
kusano fc6ab3
{
kusano fc6ab3
    static int virgin = 1;
kusano fc6ab3
    static short lencnt[MAXBITS+1], lensym[FIXLCODES];
kusano fc6ab3
    static short distcnt[MAXBITS+1], distsym[MAXDCODES];
kusano fc6ab3
    static struct huffman lencode, distcode;
kusano fc6ab3
kusano fc6ab3
    /* build fixed huffman tables if first call (may not be thread safe) */
kusano fc6ab3
    if (virgin) {
kusano fc6ab3
        int symbol;
kusano fc6ab3
        short lengths[FIXLCODES];
kusano fc6ab3
kusano fc6ab3
        /* construct lencode and distcode */
kusano fc6ab3
        lencode.count = lencnt;
kusano fc6ab3
        lencode.symbol = lensym;
kusano fc6ab3
        distcode.count = distcnt;
kusano fc6ab3
        distcode.symbol = distsym;
kusano fc6ab3
kusano fc6ab3
        /* literal/length table */
kusano fc6ab3
        for (symbol = 0; symbol < 144; symbol++)
kusano fc6ab3
            lengths[symbol] = 8;
kusano fc6ab3
        for (; symbol < 256; symbol++)
kusano fc6ab3
            lengths[symbol] = 9;
kusano fc6ab3
        for (; symbol < 280; symbol++)
kusano fc6ab3
            lengths[symbol] = 7;
kusano fc6ab3
        for (; symbol < FIXLCODES; symbol++)
kusano fc6ab3
            lengths[symbol] = 8;
kusano fc6ab3
        construct(&lencode, lengths, FIXLCODES);
kusano fc6ab3
kusano fc6ab3
        /* distance table */
kusano fc6ab3
        for (symbol = 0; symbol < MAXDCODES; symbol++)
kusano fc6ab3
            lengths[symbol] = 5;
kusano fc6ab3
        construct(&distcode, lengths, MAXDCODES);
kusano fc6ab3
kusano fc6ab3
        /* do this just once */
kusano fc6ab3
        virgin = 0;
kusano fc6ab3
    }
kusano fc6ab3
kusano fc6ab3
    /* decode data until end-of-block code */
kusano fc6ab3
    return codes(s, &lencode, &distcode);
kusano fc6ab3
}
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Process a dynamic codes block.
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - A dynamic block starts with a description of the literal/length and
kusano fc6ab3
 *   distance codes for that block.  New dynamic blocks allow the compressor to
kusano fc6ab3
 *   rapidly adapt to changing data with new codes optimized for that data.
kusano fc6ab3
 *
kusano fc6ab3
 * - The codes used by the deflate format are "canonical", which means that
kusano fc6ab3
 *   the actual bits of the codes are generated in an unambiguous way simply
kusano fc6ab3
 *   from the number of bits in each code.  Therefore the code descriptions
kusano fc6ab3
 *   are simply a list of code lengths for each symbol.
kusano fc6ab3
 *
kusano fc6ab3
 * - The code lengths are stored in order for the symbols, so lengths are
kusano fc6ab3
 *   provided for each of the literal/length symbols, and for each of the
kusano fc6ab3
 *   distance symbols.
kusano fc6ab3
 *
kusano fc6ab3
 * - If a symbol is not used in the block, this is represented by a zero as
kusano fc6ab3
 *   as the code length.  This does not mean a zero-length code, but rather
kusano fc6ab3
 *   that no code should be created for this symbol.  There is no way in the
kusano fc6ab3
 *   deflate format to represent a zero-length code.
kusano fc6ab3
 *
kusano fc6ab3
 * - The maximum number of bits in a code is 15, so the possible lengths for
kusano fc6ab3
 *   any code are 1..15.
kusano fc6ab3
 *
kusano fc6ab3
 * - The fact that a length of zero is not permitted for a code has an
kusano fc6ab3
 *   interesting consequence.  Normally if only one symbol is used for a given
kusano fc6ab3
 *   code, then in fact that code could be represented with zero bits.  However
kusano fc6ab3
 *   in deflate, that code has to be at least one bit.  So for example, if
kusano fc6ab3
 *   only a single distance base symbol appears in a block, then it will be
kusano fc6ab3
 *   represented by a single code of length one, in particular one 0 bit.  This
kusano fc6ab3
 *   is an incomplete code, since if a 1 bit is received, it has no meaning,
kusano fc6ab3
 *   and should result in an error.  So incomplete distance codes of one symbol
kusano fc6ab3
 *   should be permitted, and the receipt of invalid codes should be handled.
kusano fc6ab3
 *
kusano fc6ab3
 * - It is also possible to have a single literal/length code, but that code
kusano fc6ab3
 *   must be the end-of-block code, since every dynamic block has one.  This
kusano fc6ab3
 *   is not the most efficient way to create an empty block (an empty fixed
kusano fc6ab3
 *   block is fewer bits), but it is allowed by the format.  So incomplete
kusano fc6ab3
 *   literal/length codes of one symbol should also be permitted.
kusano fc6ab3
 *
kusano fc6ab3
 * - If there are only literal codes and no lengths, then there are no distance
kusano fc6ab3
 *   codes.  This is represented by one distance code with zero bits.
kusano fc6ab3
 *
kusano fc6ab3
 * - The list of up to 286 length/literal lengths and up to 30 distance lengths
kusano fc6ab3
 *   are themselves compressed using Huffman codes and run-length encoding.  In
kusano fc6ab3
 *   the list of code lengths, a 0 symbol means no code, a 1..15 symbol means
kusano fc6ab3
 *   that length, and the symbols 16, 17, and 18 are run-length instructions.
kusano fc6ab3
 *   Each of 16, 17, and 18 are follwed by extra bits to define the length of
kusano fc6ab3
 *   the run.  16 copies the last length 3 to 6 times.  17 represents 3 to 10
kusano fc6ab3
 *   zero lengths, and 18 represents 11 to 138 zero lengths.  Unused symbols
kusano fc6ab3
 *   are common, hence the special coding for zero lengths.
kusano fc6ab3
 *
kusano fc6ab3
 * - The symbols for 0..18 are Huffman coded, and so that code must be
kusano fc6ab3
 *   described first.  This is simply a sequence of up to 19 three-bit values
kusano fc6ab3
 *   representing no code (0) or the code length for that symbol (1..7).
kusano fc6ab3
 *
kusano fc6ab3
 * - A dynamic block starts with three fixed-size counts from which is computed
kusano fc6ab3
 *   the number of literal/length code lengths, the number of distance code
kusano fc6ab3
 *   lengths, and the number of code length code lengths (ok, you come up with
kusano fc6ab3
 *   a better name!) in the code descriptions.  For the literal/length and
kusano fc6ab3
 *   distance codes, lengths after those provided are considered zero, i.e. no
kusano fc6ab3
 *   code.  The code length code lengths are received in a permuted order (see
kusano fc6ab3
 *   the order[] array below) to make a short code length code length list more
kusano fc6ab3
 *   likely.  As it turns out, very short and very long codes are less likely
kusano fc6ab3
 *   to be seen in a dynamic code description, hence what may appear initially
kusano fc6ab3
 *   to be a peculiar ordering.
kusano fc6ab3
 *
kusano fc6ab3
 * - Given the number of literal/length code lengths (nlen) and distance code
kusano fc6ab3
 *   lengths (ndist), then they are treated as one long list of nlen + ndist
kusano fc6ab3
 *   code lengths.  Therefore run-length coding can and often does cross the
kusano fc6ab3
 *   boundary between the two sets of lengths.
kusano fc6ab3
 *
kusano fc6ab3
 * - So to summarize, the code description at the start of a dynamic block is
kusano fc6ab3
 *   three counts for the number of code lengths for the literal/length codes,
kusano fc6ab3
 *   the distance codes, and the code length codes.  This is followed by the
kusano fc6ab3
 *   code length code lengths, three bits each.  This is used to construct the
kusano fc6ab3
 *   code length code which is used to read the remainder of the lengths.  Then
kusano fc6ab3
 *   the literal/length code lengths and distance lengths are read as a single
kusano fc6ab3
 *   set of lengths using the code length codes.  Codes are constructed from
kusano fc6ab3
 *   the resulting two sets of lengths, and then finally you can start
kusano fc6ab3
 *   decoding actual compressed data in the block.
kusano fc6ab3
 *
kusano fc6ab3
 * - For reference, a "typical" size for the code description in a dynamic
kusano fc6ab3
 *   block is around 80 bytes.
kusano fc6ab3
 */
kusano fc6ab3
local int dynamic(struct state *s)
kusano fc6ab3
{
kusano fc6ab3
    int nlen, ndist, ncode;             /* number of lengths in descriptor */
kusano fc6ab3
    int index;                          /* index of lengths[] */
kusano fc6ab3
    int err;                            /* construct() return value */
kusano fc6ab3
    short lengths[MAXCODES];            /* descriptor code lengths */
kusano fc6ab3
    short lencnt[MAXBITS+1], lensym[MAXLCODES];         /* lencode memory */
kusano fc6ab3
    short distcnt[MAXBITS+1], distsym[MAXDCODES];       /* distcode memory */
kusano fc6ab3
    struct huffman lencode, distcode;   /* length and distance codes */
kusano fc6ab3
    static const short order[19] =      /* permutation of code length codes */
kusano fc6ab3
        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
kusano fc6ab3
kusano fc6ab3
    /* construct lencode and distcode */
kusano fc6ab3
    lencode.count = lencnt;
kusano fc6ab3
    lencode.symbol = lensym;
kusano fc6ab3
    distcode.count = distcnt;
kusano fc6ab3
    distcode.symbol = distsym;
kusano fc6ab3
kusano fc6ab3
    /* get number of lengths in each table, check lengths */
kusano fc6ab3
    nlen = bits(s, 5) + 257;
kusano fc6ab3
    ndist = bits(s, 5) + 1;
kusano fc6ab3
    ncode = bits(s, 4) + 4;
kusano fc6ab3
    if (nlen > MAXLCODES || ndist > MAXDCODES)
kusano fc6ab3
        return -3;                      /* bad counts */
kusano fc6ab3
kusano fc6ab3
    /* read code length code lengths (really), missing lengths are zero */
kusano fc6ab3
    for (index = 0; index < ncode; index++)
kusano fc6ab3
        lengths[order[index]] = bits(s, 3);
kusano fc6ab3
    for (; index < 19; index++)
kusano fc6ab3
        lengths[order[index]] = 0;
kusano fc6ab3
kusano fc6ab3
    /* build huffman table for code lengths codes (use lencode temporarily) */
kusano fc6ab3
    err = construct(&lencode, lengths, 19);
kusano fc6ab3
    if (err != 0)               /* require complete code set here */
kusano fc6ab3
        return -4;
kusano fc6ab3
kusano fc6ab3
    /* read length/literal and distance code length tables */
kusano fc6ab3
    index = 0;
kusano fc6ab3
    while (index < nlen + ndist) {
kusano fc6ab3
        int symbol;             /* decoded value */
kusano fc6ab3
        int len;                /* last length to repeat */
kusano fc6ab3
kusano fc6ab3
        symbol = decode(s, &lencode);
kusano fc6ab3
        if (symbol < 0)
kusano fc6ab3
            return symbol;          /* invalid symbol */
kusano fc6ab3
        if (symbol < 16)                /* length in 0..15 */
kusano fc6ab3
            lengths[index++] = symbol;
kusano fc6ab3
        else {                          /* repeat instruction */
kusano fc6ab3
            len = 0;                    /* assume repeating zeros */
kusano fc6ab3
            if (symbol == 16) {         /* repeat last length 3..6 times */
kusano fc6ab3
                if (index == 0)
kusano fc6ab3
                    return -5;          /* no last length! */
kusano fc6ab3
                len = lengths[index - 1];       /* last length */
kusano fc6ab3
                symbol = 3 + bits(s, 2);
kusano fc6ab3
            }
kusano fc6ab3
            else if (symbol == 17)      /* repeat zero 3..10 times */
kusano fc6ab3
                symbol = 3 + bits(s, 3);
kusano fc6ab3
            else                        /* == 18, repeat zero 11..138 times */
kusano fc6ab3
                symbol = 11 + bits(s, 7);
kusano fc6ab3
            if (index + symbol > nlen + ndist)
kusano fc6ab3
                return -6;              /* too many lengths! */
kusano fc6ab3
            while (symbol--)            /* repeat last or zero symbol times */
kusano fc6ab3
                lengths[index++] = len;
kusano fc6ab3
        }
kusano fc6ab3
    }
kusano fc6ab3
kusano fc6ab3
    /* check for end-of-block code -- there better be one! */
kusano fc6ab3
    if (lengths[256] == 0)
kusano fc6ab3
        return -9;
kusano fc6ab3
kusano fc6ab3
    /* build huffman table for literal/length codes */
kusano fc6ab3
    err = construct(&lencode, lengths, nlen);
kusano fc6ab3
    if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1]))
kusano fc6ab3
        return -7;      /* incomplete code ok only for single length 1 code */
kusano fc6ab3
kusano fc6ab3
    /* build huffman table for distance codes */
kusano fc6ab3
    err = construct(&distcode, lengths + nlen, ndist);
kusano fc6ab3
    if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1]))
kusano fc6ab3
        return -8;      /* incomplete code ok only for single length 1 code */
kusano fc6ab3
kusano fc6ab3
    /* decode data until end-of-block code */
kusano fc6ab3
    return codes(s, &lencode, &distcode);
kusano fc6ab3
}
kusano fc6ab3
kusano fc6ab3
/*
kusano fc6ab3
 * Inflate source to dest.  On return, destlen and sourcelen are updated to the
kusano fc6ab3
 * size of the uncompressed data and the size of the deflate data respectively.
kusano fc6ab3
 * On success, the return value of puff() is zero.  If there is an error in the
kusano fc6ab3
 * source data, i.e. it is not in the deflate format, then a negative value is
kusano fc6ab3
 * returned.  If there is not enough input available or there is not enough
kusano fc6ab3
 * output space, then a positive error is returned.  In that case, destlen and
kusano fc6ab3
 * sourcelen are not updated to facilitate retrying from the beginning with the
kusano fc6ab3
 * provision of more input data or more output space.  In the case of invalid
kusano fc6ab3
 * inflate data (a negative error), the dest and source pointers are updated to
kusano fc6ab3
 * facilitate the debugging of deflators.
kusano fc6ab3
 *
kusano fc6ab3
 * puff() also has a mode to determine the size of the uncompressed output with
kusano fc6ab3
 * no output written.  For this dest must be (unsigned char *)0.  In this case,
kusano fc6ab3
 * the input value of *destlen is ignored, and on return *destlen is set to the
kusano fc6ab3
 * size of the uncompressed output.
kusano fc6ab3
 *
kusano fc6ab3
 * The return codes are:
kusano fc6ab3
 *
kusano fc6ab3
 *   2:  available inflate data did not terminate
kusano fc6ab3
 *   1:  output space exhausted before completing inflate
kusano fc6ab3
 *   0:  successful inflate
kusano fc6ab3
 *  -1:  invalid block type (type == 3)
kusano fc6ab3
 *  -2:  stored block length did not match one's complement
kusano fc6ab3
 *  -3:  dynamic block code description: too many length or distance codes
kusano fc6ab3
 *  -4:  dynamic block code description: code lengths codes incomplete
kusano fc6ab3
 *  -5:  dynamic block code description: repeat lengths with no first length
kusano fc6ab3
 *  -6:  dynamic block code description: repeat more than specified lengths
kusano fc6ab3
 *  -7:  dynamic block code description: invalid literal/length code lengths
kusano fc6ab3
 *  -8:  dynamic block code description: invalid distance code lengths
kusano fc6ab3
 *  -9:  dynamic block code description: missing end-of-block code
kusano fc6ab3
 * -10:  invalid literal/length or distance code in fixed or dynamic block
kusano fc6ab3
 * -11:  distance is too far back in fixed or dynamic block
kusano fc6ab3
 *
kusano fc6ab3
 * Format notes:
kusano fc6ab3
 *
kusano fc6ab3
 * - Three bits are read for each block to determine the kind of block and
kusano fc6ab3
 *   whether or not it is the last block.  Then the block is decoded and the
kusano fc6ab3
 *   process repeated if it was not the last block.
kusano fc6ab3
 *
kusano fc6ab3
 * - The leftover bits in the last byte of the deflate data after the last
kusano fc6ab3
 *   block (if it was a fixed or dynamic block) are undefined and have no
kusano fc6ab3
 *   expected values to check.
kusano fc6ab3
 */
kusano fc6ab3
int puff(unsigned char *dest,           /* pointer to destination pointer */
kusano fc6ab3
         unsigned long *destlen,        /* amount of output space */
kusano fc6ab3
         const unsigned char *source,   /* pointer to source data pointer */
kusano fc6ab3
         unsigned long *sourcelen)      /* amount of input available */
kusano fc6ab3
{
kusano fc6ab3
    struct state s;             /* input/output state */
kusano fc6ab3
    int last, type;             /* block information */
kusano fc6ab3
    int err;                    /* return value */
kusano fc6ab3
kusano fc6ab3
    /* initialize output state */
kusano fc6ab3
    s.out = dest;
kusano fc6ab3
    s.outlen = *destlen;                /* ignored if dest is NIL */
kusano fc6ab3
    s.outcnt = 0;
kusano fc6ab3
kusano fc6ab3
    /* initialize input state */
kusano fc6ab3
    s.in = source;
kusano fc6ab3
    s.inlen = *sourcelen;
kusano fc6ab3
    s.incnt = 0;
kusano fc6ab3
    s.bitbuf = 0;
kusano fc6ab3
    s.bitcnt = 0;
kusano fc6ab3
kusano fc6ab3
    /* return if bits() or decode() tries to read past available input */
kusano fc6ab3
    if (setjmp(s.env) != 0)             /* if came back here via longjmp() */
kusano fc6ab3
        err = 2;                        /* then skip do-loop, return error */
kusano fc6ab3
    else {
kusano fc6ab3
        /* process blocks until last block or error */
kusano fc6ab3
        do {
kusano fc6ab3
            last = bits(&s, 1);         /* one if last block */
kusano fc6ab3
            type = bits(&s, 2);         /* block type 0..3 */
kusano fc6ab3
            err = type == 0 ?
kusano fc6ab3
                    stored(&s) :
kusano fc6ab3
                    (type == 1 ?
kusano fc6ab3
                        fixed(&s) :
kusano fc6ab3
                        (type == 2 ?
kusano fc6ab3
                            dynamic(&s) :
kusano fc6ab3
                            -1));       /* type == 3, invalid */
kusano fc6ab3
            if (err != 0)
kusano fc6ab3
                break;                  /* return with error */
kusano fc6ab3
        } while (!last);
kusano fc6ab3
    }
kusano fc6ab3
kusano fc6ab3
    /* update the lengths and return */
kusano fc6ab3
    if (err <= 0) {
kusano fc6ab3
        *destlen = s.outcnt;
kusano fc6ab3
        *sourcelen = s.incnt;
kusano fc6ab3
    }
kusano fc6ab3
    return err;
kusano fc6ab3
}