]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/common/unzip.c
Merge remote-tracking branch 'ttimo/master'
[xonotic/netradiant.git] / tools / quake3 / common / unzip.c
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 /*****************************************************************************
23 * name:         unzip.c
24 *
25 * desc:         IO on .zip files using portions of zlib
26 *
27 *
28 *****************************************************************************/
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include "unzip.h"
34
35 // TTimo added for safe_malloc wrapping
36 #include "cmdlib.h"
37
38 /* unzip.h -- IO for uncompress .zip files using zlib
39    Version 0.15 beta, Mar 19th, 1998,
40
41    Copyright (C) 1998 Gilles Vollant
42
43    This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
44      WinZip, InfoZip tools and compatible.
45    Encryption and multi volume ZipFile (span) are not supported.
46    Old compressions used by old PKZip 1.x are not supported
47
48    THIS IS AN ALPHA VERSION. AT THIS STAGE OF DEVELOPPEMENT, SOMES API OR STRUCTURE
49    CAN CHANGE IN FUTURE VERSION !!
50    I WAIT FEEDBACK at mail info@winimage.com
51    Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
52
53    Condition of use and distribution are the same than zlib :
54
55    This software is provided 'as-is', without any express or implied
56    warranty.  In no event will the authors be held liable for any damages
57    arising from the use of this software.
58
59    Permission is granted to anyone to use this software for any purpose,
60    including commercial applications, and to alter it and redistribute it
61    freely, subject to the following restrictions:
62
63    1. The origin of this software must not be misrepresented; you must not
64      claim that you wrote the original software. If you use this software
65      in a product, an acknowledgment in the product documentation would be
66      appreciated but is not required.
67    2. Altered source versions must be plainly marked as such, and must not be
68      misrepresented as being the original software.
69    3. This notice may not be removed or altered from any source distribution.
70
71
72  */
73 /* for more info about .ZIP format, see
74       ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
75    PkWare has also a specification at :
76       ftp://ftp.pkware.com/probdesc.zip */
77
78 /* zlib.h -- interface of the 'zlib' general purpose compression library
79    version 1.1.3, July 9th, 1998
80
81    Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
82
83    This software is provided 'as-is', without any express or implied
84    warranty.  In no event will the authors be held liable for any damages
85    arising from the use of this software.
86
87    Permission is granted to anyone to use this software for any purpose,
88    including commercial applications, and to alter it and redistribute it
89    freely, subject to the following restrictions:
90
91    1. The origin of this software must not be misrepresented; you must not
92      claim that you wrote the original software. If you use this software
93      in a product, an acknowledgment in the product documentation would be
94      appreciated but is not required.
95    2. Altered source versions must be plainly marked as such, and must not be
96      misrepresented as being the original software.
97    3. This notice may not be removed or altered from any source distribution.
98
99    Jean-loup Gailly        Mark Adler
100    jloup@gzip.org          madler@alumni.caltech.edu
101
102
103    The data format used by the zlib library is described by RFCs (Request for
104    Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
105    (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
106  */
107
108 /* zconf.h -- configuration of the zlib compression library
109  * Copyright (C) 1995-1998 Jean-loup Gailly.
110  * For conditions of distribution and use, see copyright notice in zlib.h
111  */
112
113
114 #ifndef _ZCONF_H
115 #define _ZCONF_H
116
117 /* Maximum value for memLevel in deflateInit2 */
118 #ifndef MAX_MEM_LEVEL
119 #  ifdef MAXSEG_64K
120 #    define MAX_MEM_LEVEL 8
121 #  else
122 #    define MAX_MEM_LEVEL 9
123 #  endif
124 #endif
125
126 /* Maximum value for windowBits in deflateInit2 and inflateInit2.
127  * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
128  * created by gzip. (Files created by minigzip can still be extracted by
129  * gzip.)
130  */
131 #ifndef MAX_WBITS
132 #  define MAX_WBITS   15 /* 32K LZ77 window */
133 #endif
134
135 /* The memory requirements for deflate are (in bytes):
136             (1 << (windowBits+2)) +  (1 << (memLevel+9))
137    that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
138    plus a few kilobytes for small objects. For example, if you want to reduce
139    the default memory requirements from 256K to 128K, compile with
140      make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
141    Of course this will generally degrade compression (there's no free lunch).
142
143    The memory requirements for inflate are (in bytes) 1 << windowBits
144    that is, 32K for windowBits=15 (default value) plus a few kilobytes
145    for small objects.
146  */
147
148 /* Type declarations */
149
150 #ifndef OF /* function prototypes */
151 #define OF( args )  args
152 #endif
153
154 typedef unsigned char Byte;   /* 8 bits */
155 typedef unsigned int uInt;    /* 16 bits or more */
156 typedef unsigned long uLong;  /* 32 bits or more */
157 typedef Byte    *voidp;
158
159 #ifndef SEEK_SET
160 #  define SEEK_SET        0       /* Seek from beginning of file.  */
161 #  define SEEK_CUR        1       /* Seek from current position.  */
162 #  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
163 #endif
164
165 #endif /* _ZCONF_H */
166
167 #define ZLIB_VERSION "1.1.3"
168
169 /*
170      The 'zlib' compression library provides in-memory compression and
171    decompression functions, including integrity checks of the uncompressed
172    data.  This version of the library supports only one compression method
173    (deflation) but other algorithms will be added later and will have the same
174    stream interface.
175
176      Compression can be done in a single step if the buffers are large
177    enough (for example if an input file is mmap'ed), or can be done by
178    repeated calls of the compression function.  In the latter case, the
179    application must provide more input and/or consume the output
180    (providing more output space) before each call.
181
182      The library also supports reading and writing files in gzip (.gz) format
183    with an interface similar to that of stdio.
184
185      The library does not install any signal handler. The decoder checks
186    the consistency of the compressed data, so the library should never
187    crash even in case of corrupted input.
188  */
189
190 /*
191    The application must update next_in and avail_in when avail_in has
192    dropped to zero. It must update next_out and avail_out when avail_out
193    has dropped to zero. The application must initialize zalloc, zfree and
194    opaque before calling the init function. All other fields are set by the
195    compression library and must not be updated by the application.
196
197    The opaque value provided by the application will be passed as the first
198    parameter for calls of zalloc and zfree. This can be useful for custom
199    memory management. The compression library attaches no meaning to the
200    opaque value.
201
202    zalloc must return Z_NULL if there is not enough memory for the object.
203    If zlib is used in a multi-threaded application, zalloc and zfree must be
204    thread safe.
205
206    On 16-bit systems, the functions zalloc and zfree must be able to allocate
207    exactly 65536 bytes, but will not be required to allocate more than this
208    if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
209    pointers returned by zalloc for objects of exactly 65536 bytes *must*
210    have their offset normalized to zero. The default allocation function
211    provided by this library ensures this (see zutil.c). To reduce memory
212    requirements and avoid any allocation of 64K objects, at the expense of
213    compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
214
215    The fields total_in and total_out can be used for statistics or
216    progress reports. After compression, total_in holds the total size of
217    the uncompressed data and may be saved for use in the decompressor
218    (particularly if the decompressor wants to decompress everything in
219    a single step).
220  */
221
222 /* constants */
223
224 #define Z_NO_FLUSH      0
225 #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
226 #define Z_SYNC_FLUSH    2
227 #define Z_FULL_FLUSH    3
228 #define Z_FINISH        4
229 /* Allowed flush values; see deflate() below for details */
230
231 #define Z_OK            0
232 #define Z_STREAM_END    1
233 #define Z_NEED_DICT     2
234 #define Z_ERRNO        ( -1 )
235 #define Z_STREAM_ERROR ( -2 )
236 #define Z_DATA_ERROR   ( -3 )
237 #define Z_MEM_ERROR    ( -4 )
238 #define Z_BUF_ERROR    ( -5 )
239 #define Z_VERSION_ERROR ( -6 )
240 /* Return codes for the compression/decompression functions. Negative
241  * values are errors, positive values are used for special but normal events.
242  */
243
244 #define Z_NO_COMPRESSION         0
245 #define Z_BEST_SPEED             1
246 #define Z_BEST_COMPRESSION       9
247 #define Z_DEFAULT_COMPRESSION  ( -1 )
248 /* compression levels */
249
250 #define Z_FILTERED            1
251 #define Z_HUFFMAN_ONLY        2
252 #define Z_DEFAULT_STRATEGY    0
253 /* compression strategy; see deflateInit2() below for details */
254
255 #define Z_BINARY   0
256 #define Z_ASCII    1
257 #define Z_UNKNOWN  2
258 /* Possible values of the data_type field */
259
260 #define Z_DEFLATED   8
261 /* The deflate compression method (the only one supported in this version) */
262
263 #define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
264
265 #define zlib_version zlibVersion()
266 /* for compatibility with versions < 1.0.2 */
267
268 /* basic functions */
269
270 const char * zlibVersion OF( (void) );
271 /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
272    If the first character differs, the library code actually used is
273    not compatible with the zlib.h header file used by the application.
274    This check is automatically made by deflateInit and inflateInit.
275  */
276
277 /*
278    int deflateInit OF((z_streamp strm, int level));
279
280      Initializes the internal stream state for compression. The fields
281    zalloc, zfree and opaque must be initialized before by the caller.
282    If zalloc and zfree are set to Z_NULL, deflateInit updates them to
283    use default allocation functions.
284
285      The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
286    1 gives best speed, 9 gives best compression, 0 gives no compression at
287    all (the input data is simply copied a block at a time).
288    Z_DEFAULT_COMPRESSION requests a default compromise between speed and
289    compression (currently equivalent to level 6).
290
291      deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
292    enough memory, Z_STREAM_ERROR if level is not a valid compression level,
293    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
294    with the version assumed by the caller (ZLIB_VERSION).
295    msg is set to null if there is no error message.  deflateInit does not
296    perform any compression: this will be done by deflate().
297  */
298
299
300 int deflate OF( ( z_streamp strm, int flush ) );
301 /*
302     deflate compresses as much data as possible, and stops when the input
303    buffer becomes empty or the output buffer becomes full. It may introduce some
304    output latency (reading input without producing any output) except when
305    forced to flush.
306
307     The detailed semantics are as follows. deflate performs one or both of the
308    following actions:
309
310    - Compress more input starting at next_in and update next_in and avail_in
311     accordingly. If not all input can be processed (because there is not
312     enough room in the output buffer), next_in and avail_in are updated and
313     processing will resume at this point for the next call of deflate().
314
315    - Provide more output starting at next_out and update next_out and avail_out
316     accordingly. This action is forced if the parameter flush is non zero.
317     Forcing flush frequently degrades the compression ratio, so this parameter
318     should be set only when necessary (in interactive applications).
319     Some output may be provided even if flush is not set.
320
321    Before the call of deflate(), the application should ensure that at least
322    one of the actions is possible, by providing more input and/or consuming
323    more output, and updating avail_in or avail_out accordingly; avail_out
324    should never be zero before the call. The application can consume the
325    compressed output when it wants, for example when the output buffer is full
326    (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
327    and with zero avail_out, it must be called again after making room in the
328    output buffer because there might be more output pending.
329
330     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
331    flushed to the output buffer and the output is aligned on a byte boundary, so
332    that the decompressor can get all input data available so far. (In particular
333    avail_in is zero after the call if enough output space has been provided
334    before the call.)  Flushing may degrade compression for some compression
335    algorithms and so it should be used only when necessary.
336
337     If flush is set to Z_FULL_FLUSH, all output is flushed as with
338    Z_SYNC_FLUSH, and the compression state is reset so that decompression can
339    restart from this point if previous compressed data has been damaged or if
340    random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
341    the compression.
342
343     If deflate returns with avail_out == 0, this function must be called again
344    with the same value of the flush parameter and more output space (updated
345    avail_out), until the flush is complete (deflate returns with non-zero
346    avail_out).
347
348     If the parameter flush is set to Z_FINISH, pending input is processed,
349    pending output is flushed and deflate returns with Z_STREAM_END if there
350    was enough output space; if deflate returns with Z_OK, this function must be
351    called again with Z_FINISH and more output space (updated avail_out) but no
352    more input data, until it returns with Z_STREAM_END or an error. After
353    deflate has returned Z_STREAM_END, the only possible operations on the
354    stream are deflateReset or deflateEnd.
355
356     Z_FINISH can be used immediately after deflateInit if all the compression
357    is to be done in a single step. In this case, avail_out must be at least
358    0.1% larger than avail_in plus 12 bytes.  If deflate does not return
359    Z_STREAM_END, then it must be called again as described above.
360
361     deflate() sets strm->adler to the adler32 checksum of all input read
362    so (that is, total_in bytes).
363
364     deflate() may update data_type if it can make a good guess about
365    the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
366    binary. This field is only for information purposes and does not affect
367    the compression algorithm in any manner.
368
369     deflate() returns Z_OK if some progress has been made (more input
370    processed or more output produced), Z_STREAM_END if all input has been
371    consumed and all output has been produced (only when flush is set to
372    Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
373    if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
374    (for example avail_in or avail_out was zero).
375  */
376
377
378 int deflateEnd OF( (z_streamp strm) );
379 /*
380      All dynamically allocated data structures for this stream are freed.
381    This function discards any unprocessed input and does not flush any
382    pending output.
383
384      deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
385    stream state was inconsistent, Z_DATA_ERROR if the stream was freed
386    prematurely (some input or output was discarded). In the error case,
387    msg may be set but then points to a static string (which must not be
388    deallocated).
389  */
390
391
392 /*
393    int inflateInit OF((z_streamp strm));
394
395      Initializes the internal stream state for decompression. The fields
396    next_in, avail_in, zalloc, zfree and opaque must be initialized before by
397    the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
398    value depends on the compression method), inflateInit determines the
399    compression method from the zlib header and allocates all data structures
400    accordingly; otherwise the allocation will be deferred to the first call of
401    inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
402    use default allocation functions.
403
404      inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
405    memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
406    version assumed by the caller.  msg is set to null if there is no error
407    message. inflateInit does not perform any decompression apart from reading
408    the zlib header if present: this will be done by inflate().  (So next_in and
409    avail_in may be modified, but next_out and avail_out are unchanged.)
410  */
411
412
413 int inflate OF( ( z_streamp strm, int flush ) );
414 /*
415     inflate decompresses as much data as possible, and stops when the input
416    buffer becomes empty or the output buffer becomes full. It may some
417    introduce some output latency (reading input without producing any output)
418    except when forced to flush.
419
420    The detailed semantics are as follows. inflate performs one or both of the
421    following actions:
422
423    - Decompress more input starting at next_in and update next_in and avail_in
424     accordingly. If not all input can be processed (because there is not
425     enough room in the output buffer), next_in is updated and processing
426     will resume at this point for the next call of inflate().
427
428    - Provide more output starting at next_out and update next_out and avail_out
429     accordingly.  inflate() provides as much output as possible, until there
430     is no more input data or no more space in the output buffer (see below
431     about the flush parameter).
432
433    Before the call of inflate(), the application should ensure that at least
434    one of the actions is possible, by providing more input and/or consuming
435    more output, and updating the next_* and avail_* values accordingly.
436    The application can consume the uncompressed output when it wants, for
437    example when the output buffer is full (avail_out == 0), or after each
438    call of inflate(). If inflate returns Z_OK and with zero avail_out, it
439    must be called again after making room in the output buffer because there
440    might be more output pending.
441
442     If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
443    output as possible to the output buffer. The flushing behavior of inflate is
444    not specified for values of the flush parameter other than Z_SYNC_FLUSH
445    and Z_FINISH, but the current implementation actually flushes as much output
446    as possible anyway.
447
448     inflate() should normally be called until it returns Z_STREAM_END or an
449    error. However if all decompression is to be performed in a single step
450    (a single call of inflate), the parameter flush should be set to
451    Z_FINISH. In this case all pending input is processed and all pending
452    output is flushed; avail_out must be large enough to hold all the
453    uncompressed data. (The size of the uncompressed data may have been saved
454    by the compressor for this purpose.) The next operation on this stream must
455    be inflateEnd to deallocate the decompression state. The use of Z_FINISH
456    is never required, but can be used to inform inflate that a faster routine
457    may be used for the single inflate() call.
458
459      If a preset dictionary is needed at this point (see inflateSetDictionary
460    below), inflate sets strm-adler to the adler32 checksum of the
461    dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
462    it sets strm->adler to the adler32 checksum of all output produced
463    so (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
464    an error code as described below. At the end of the stream, inflate()
465    checks that its computed adler32 checksum is equal to that saved by the
466    compressor and returns Z_STREAM_END only if the checksum is correct.
467
468     inflate() returns Z_OK if some progress has been made (more input processed
469    or more output produced), Z_STREAM_END if the end of the compressed data has
470    been reached and all uncompressed output has been produced, Z_NEED_DICT if a
471    preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
472    corrupted (input stream not conforming to the zlib format or incorrect
473    adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
474    (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
475    enough memory, Z_BUF_ERROR if no progress is possible or if there was not
476    enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
477    case, the application may then call inflateSync to look for a good
478    compression block.
479  */
480
481
482 int inflateEnd OF( (z_streamp strm) );
483 /*
484      All dynamically allocated data structures for this stream are freed.
485    This function discards any unprocessed input and does not flush any
486    pending output.
487
488      inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
489    was inconsistent. In the error case, msg may be set but then points to a
490    static string (which must not be deallocated).
491  */
492
493 /* Advanced functions */
494
495 /*
496     The following functions are needed only in some special applications.
497  */
498
499 /*
500    int deflateInit2 OF((z_streamp strm,
501                                      int  level,
502                                      int  method,
503                                      int  windowBits,
504                                      int  memLevel,
505                                      int  strategy));
506
507      This is another version of deflateInit with more compression options. The
508    fields next_in, zalloc, zfree and opaque must be initialized before by
509    the caller.
510
511      The method parameter is the compression method. It must be Z_DEFLATED in
512    this version of the library.
513
514      The windowBits parameter is the base two logarithm of the window size
515    (the size of the history buffer).  It should be in the range 8..15 for this
516    version of the library. Larger values of this parameter result in better
517    compression at the expense of memory usage. The default value is 15 if
518    deflateInit is used instead.
519
520      The memLevel parameter specifies how much memory should be allocated
521    for the internal compression state. memLevel=1 uses minimum memory but
522    is slow and reduces compression ratio; memLevel=9 uses maximum memory
523    for optimal speed. The default value is 8. See zconf.h for total memory
524    usage as a function of windowBits and memLevel.
525
526      The strategy parameter is used to tune the compression algorithm. Use the
527    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
528    filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
529    string match).  Filtered data consists mostly of small values with a
530    somewhat random distribution. In this case, the compression algorithm is
531    tuned to compress them better. The effect of Z_FILTERED is to force more
532    Huffman coding and less string matching; it is somewhat intermediate
533    between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
534    the compression ratio but not the correctness of the compressed output even
535    if it is not set appropriately.
536
537       deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
538    memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
539    method). msg is set to null if there is no error message.  deflateInit2 does
540    not perform any compression: this will be done by deflate().
541  */
542
543 int deflateSetDictionary OF( ( z_streamp strm,
544                                                            const Byte * dictionary,
545                                                            uInt dictLength ) );
546 /*
547      Initializes the compression dictionary from the given byte sequence
548    without producing any compressed output. This function must be called
549    immediately after deflateInit, deflateInit2 or deflateReset, before any
550    call of deflate. The compressor and decompressor must use exactly the same
551    dictionary (see inflateSetDictionary).
552
553      The dictionary should consist of strings (byte sequences) that are likely
554    to be encountered later in the data to be compressed, with the most commonly
555    used strings preferably put towards the end of the dictionary. Using a
556    dictionary is most useful when the data to be compressed is short and can be
557    predicted with good accuracy; the data can then be compressed better than
558    with the default empty dictionary.
559
560      Depending on the size of the compression data structures selected by
561    deflateInit or deflateInit2, a part of the dictionary may in effect be
562    discarded, for example if the dictionary is larger than the window size in
563    deflate or deflate2. Thus the strings most likely to be useful should be
564    put at the end of the dictionary, not at the front.
565
566      Upon return of this function, strm->adler is set to the Adler32 value
567    of the dictionary; the decompressor may later use this value to determine
568    which dictionary has been used by the compressor. (The Adler32 value
569    applies to the whole dictionary even if only a subset of the dictionary is
570    actually used by the compressor.)
571
572      deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
573    parameter is invalid (such as NULL dictionary) or the stream state is
574    inconsistent (for example if deflate has already been called for this stream
575    or if the compression method is bsort). deflateSetDictionary does not
576    perform any compression: this will be done by deflate().
577  */
578
579 int deflateCopy OF( ( z_streamp dest,
580                                           z_streamp source ) );
581 /*
582      Sets the destination stream as a complete copy of the source stream.
583
584      This function can be useful when several compression strategies will be
585    tried, for example when there are several ways of pre-processing the input
586    data with a filter. The streams that will be discarded should then be freed
587    by calling deflateEnd.  Note that deflateCopy duplicates the internal
588    compression state which can be quite large, so this strategy is slow and
589    can consume lots of memory.
590
591      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
592    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
593    (such as zalloc being NULL). msg is left unchanged in both source and
594    destination.
595  */
596
597 int deflateReset OF( (z_streamp strm) );
598 /*
599      This function is equivalent to deflateEnd followed by deflateInit,
600    but does not free and reallocate all the internal compression state.
601    The stream will keep the same compression level and any other attributes
602    that may have been set by deflateInit2.
603
604       deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
605    stream state was inconsistent (such as zalloc or state being NULL).
606  */
607
608 int deflateParams OF( ( z_streamp strm,
609                                                 int level,
610                                                 int strategy ) );
611 /*
612      Dynamically update the compression level and compression strategy.  The
613    interpretation of level and strategy is as in deflateInit2.  This can be
614    used to switch between compression and straight copy of the input data, or
615    to switch to a different kind of input data requiring a different
616    strategy. If the compression level is changed, the input available so far
617    is compressed with the old level (and may be flushed); the new level will
618    take effect only at the next call of deflate().
619
620      Before the call of deflateParams, the stream state must be set as for
621    a call of deflate(), since the currently available input may have to
622    be compressed and flushed. In particular, strm->avail_out must be non-zero.
623
624      deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
625    stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
626    if strm->avail_out was zero.
627  */
628
629 /*
630    int inflateInit2 OF((z_streamp strm,
631                                      int  windowBits));
632
633      This is another version of inflateInit with an extra parameter. The
634    fields next_in, avail_in, zalloc, zfree and opaque must be initialized
635    before by the caller.
636
637      The windowBits parameter is the base two logarithm of the maximum window
638    size (the size of the history buffer).  It should be in the range 8..15 for
639    this version of the library. The default value is 15 if inflateInit is used
640    instead. If a compressed stream with a larger window size is given as
641    input, inflate() will return with the error code Z_DATA_ERROR instead of
642    trying to allocate a larger window.
643
644       inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
645    memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
646    memLevel). msg is set to null if there is no error message.  inflateInit2
647    does not perform any decompression apart from reading the zlib header if
648    present: this will be done by inflate(). (So next_in and avail_in may be
649    modified, but next_out and avail_out are unchanged.)
650  */
651
652 int inflateSetDictionary OF( ( z_streamp strm,
653                                                            const Byte * dictionary,
654                                                            uInt dictLength ) );
655 /*
656      Initializes the decompression dictionary from the given uncompressed byte
657    sequence. This function must be called immediately after a call of inflate
658    if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
659    can be determined from the Adler32 value returned by this call of
660    inflate. The compressor and decompressor must use exactly the same
661    dictionary (see deflateSetDictionary).
662
663      inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
664    parameter is invalid (such as NULL dictionary) or the stream state is
665    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
666    expected one (incorrect Adler32 value). inflateSetDictionary does not
667    perform any decompression: this will be done by subsequent calls of
668    inflate().
669  */
670
671 int inflateSync OF( (z_streamp strm) );
672 /*
673     Skips invalid compressed data until a full flush point (see above the
674    description of deflate with Z_FULL_FLUSH) can be found, or until all
675    available input is skipped. No output is provided.
676
677     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
678    if no more input was provided, Z_DATA_ERROR if no flush point has been found,
679    or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
680    case, the application may save the current current value of total_in which
681    indicates where valid compressed data was found. In the error case, the
682    application may repeatedly call inflateSync, providing more input each time,
683    until success or end of the input data.
684  */
685
686 int inflateReset OF( (z_streamp strm) );
687 /*
688      This function is equivalent to inflateEnd followed by inflateInit,
689    but does not free and reallocate all the internal decompression state.
690    The stream will keep attributes that may have been set by inflateInit2.
691
692       inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
693    stream state was inconsistent (such as zalloc or state being NULL).
694  */
695
696
697 /* utility functions */
698
699 /*
700      The following utility functions are implemented on top of the
701    basic stream-oriented functions. To simplify the interface, some
702    default options are assumed (compression level and memory usage,
703    standard memory allocation functions). The source code of these
704    utility functions can easily be modified if you need special options.
705  */
706
707 int compress OF( ( Byte * dest,   uLong * destLen,
708                                    const Byte * source, uLong sourceLen ) );
709 /*
710      Compresses the source buffer into the destination buffer.  sourceLen is
711    the byte length of the source buffer. Upon entry, destLen is the total
712    size of the destination buffer, which must be at least 0.1% larger than
713    sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
714    compressed buffer.
715      This function can be used to compress a whole file at once if the
716    input file is mmap'ed.
717      compress returns Z_OK if success, Z_MEM_ERROR if there was not
718    enough memory, Z_BUF_ERROR if there was not enough room in the output
719    buffer.
720  */
721
722 int compress2 OF( ( Byte * dest,   uLong * destLen,
723                                         const Byte * source, uLong sourceLen,
724                                         int level ) );
725 /*
726      Compresses the source buffer into the destination buffer. The level
727    parameter has the same meaning as in deflateInit.  sourceLen is the byte
728    length of the source buffer. Upon entry, destLen is the total size of the
729    destination buffer, which must be at least 0.1% larger than sourceLen plus
730    12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
731
732      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
733    memory, Z_BUF_ERROR if there was not enough room in the output buffer,
734    Z_STREAM_ERROR if the level parameter is invalid.
735  */
736
737 int uncompress OF( ( Byte * dest,   uLong * destLen,
738                                          const Byte * source, uLong sourceLen ) );
739 /*
740      Decompresses the source buffer into the destination buffer.  sourceLen is
741    the byte length of the source buffer. Upon entry, destLen is the total
742    size of the destination buffer, which must be large enough to hold the
743    entire uncompressed data. (The size of the uncompressed data must have
744    been saved previously by the compressor and transmitted to the decompressor
745    by some mechanism outside the scope of this compression library.)
746    Upon exit, destLen is the actual size of the compressed buffer.
747      This function can be used to decompress a whole file at once if the
748    input file is mmap'ed.
749
750      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
751    enough memory, Z_BUF_ERROR if there was not enough room in the output
752    buffer, or Z_DATA_ERROR if the input data was corrupted.
753  */
754
755
756 typedef voidp gzFile;
757
758 gzFile gzopen  OF( ( const char *path, const char *mode ) );
759 /*
760      Opens a gzip (.gz) file for reading or writing. The mode parameter
761    is as in fopen ("rb" or "wb") but can also include a compression level
762    ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
763    Huffman only compression as in "wb1h". (See the description
764    of deflateInit2 for more information about the strategy parameter.)
765
766      gzopen can be used to read a file which is not in gzip format; in this
767    case gzread will directly read from the file without decompression.
768
769      gzopen returns NULL if the file could not be opened or if there was
770    insufficient memory to allocate the (de)compression state; errno
771    can be checked to distinguish the two cases (if errno is zero, the
772    zlib error is Z_MEM_ERROR).  */
773
774 gzFile gzdopen  OF( ( int fd, const char *mode ) );
775 /*
776      gzdopen() associates a gzFile with the file descriptor fd.  File
777    descriptors are obtained from calls like open, dup, creat, pipe or
778    fileno (in the file has been previously opened with fopen).
779    The mode parameter is as in gzopen.
780      The next call of gzclose on the returned gzFile will also close the
781    file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
782    descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
783      gzdopen returns NULL if there was insufficient memory to allocate
784    the (de)compression state.
785  */
786
787 int gzsetparams OF( ( gzFile file, int level, int strategy ) );
788 /*
789      Dynamically update the compression level or strategy. See the description
790    of deflateInit2 for the meaning of these parameters.
791      gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
792    opened for writing.
793  */
794
795 int gzread  OF( ( gzFile file, voidp buf, unsigned len ) );
796 /*
797      Reads the given number of uncompressed bytes from the compressed file.
798    If the input file was not in gzip format, gzread copies the given number
799    of bytes into the buffer.
800      gzread returns the number of uncompressed bytes actually read (0 for
801    end of file, -1 for error). */
802
803 int gzwrite OF( ( gzFile file,
804                                   const voidp buf, unsigned len ) );
805 /*
806      Writes the given number of uncompressed bytes into the compressed file.
807    gzwrite returns the number of uncompressed bytes actually written
808    (0 in case of error).
809  */
810
811 int gzprintf OF( ( gzFile file, const char *format, ... ) );
812 /*
813      Converts, formats, and writes the args to the compressed file under
814    control of the format string, as in fprintf. gzprintf returns the number of
815    uncompressed bytes actually written (0 in case of error).
816  */
817
818 int gzputs OF( ( gzFile file, const char *s ) );
819 /*
820       Writes the given null-terminated string to the compressed file, excluding
821    the terminating null character.
822       gzputs returns the number of characters written, or -1 in case of error.
823  */
824
825 char * gzgets OF( ( gzFile file, char *buf, int len ) );
826 /*
827       Reads bytes from the compressed file until len-1 characters are read, or
828    a newline character is read and transferred to buf, or an end-of-file
829    condition is encountered.  The string is then terminated with a null
830    character.
831       gzgets returns buf, or Z_NULL in case of error.
832  */
833
834 int gzputc OF( ( gzFile file, int c ) );
835 /*
836       Writes c, converted to an unsigned char, into the compressed file.
837    gzputc returns the value that was written, or -1 in case of error.
838  */
839
840 int gzgetc OF( (gzFile file) );
841 /*
842       Reads one byte from the compressed file. gzgetc returns this byte
843    or -1 in case of end of file or error.
844  */
845
846 int gzflush OF( ( gzFile file, int flush ) );
847 /*
848      Flushes all pending output into the compressed file. The parameter
849    flush is as in the deflate() function. The return value is the zlib
850    error number (see function gzerror below). gzflush returns Z_OK if
851    the flush parameter is Z_FINISH and all output could be flushed.
852      gzflush should be called only when strictly necessary because it can
853    degrade compression.
854  */
855
856 long gzseek OF( ( gzFile file,
857                                   long offset, int whence ) );
858 /*
859       Sets the starting position for the next gzread or gzwrite on the
860    given compressed file. The offset represents a number of bytes in the
861    uncompressed data stream. The whence parameter is defined as in lseek(2);
862    the value SEEK_END is not supported.
863      If the file is opened for reading, this function is emulated but can be
864    extremely slow. If the file is opened for writing, only forward seeks are
865    supported; gzseek then compresses a sequence of zeroes up to the new
866    starting position.
867
868       gzseek returns the resulting offset location as measured in bytes from
869    the beginning of the uncompressed stream, or -1 in case of error, in
870    particular if the file is opened for writing and the new starting position
871    would be before the current position.
872  */
873
874 int gzrewind OF( (gzFile file) );
875 /*
876      Rewinds the given file. This function is supported only for reading.
877
878    gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
879  */
880
881 long gztell OF( (gzFile file) );
882 /*
883      Returns the starting position for the next gzread or gzwrite on the
884    given compressed file. This position represents a number of bytes in the
885    uncompressed data stream.
886
887    gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
888  */
889
890 int gzeof OF( (gzFile file) );
891 /*
892      Returns 1 when EOF has previously been detected reading the given
893    input stream, otherwise zero.
894  */
895
896 int gzclose OF( (gzFile file) );
897 /*
898      Flushes all pending output if necessary, closes the compressed file
899    and deallocates all the (de)compression state. The return value is the zlib
900    error number (see function gzerror below).
901  */
902
903 const char * gzerror OF( ( gzFile file, int *errnum ) );
904 /*
905      Returns the error message for the last error which occurred on the
906    given compressed file. errnum is set to zlib error number. If an
907    error occurred in the file system and not in the compression library,
908    errnum is set to Z_ERRNO and the application may consult errno
909    to get the exact error code.
910  */
911
912 /* checksum functions */
913
914 /*
915      These functions are not related to compression but are exported
916    anyway because they might be useful in applications using the
917    compression library.
918  */
919
920 uLong adler32 OF( ( uLong adler, const Byte * buf, uInt len ) );
921
922 /*
923      Update a running Adler-32 checksum with the bytes buf[0..len-1] and
924    return the updated checksum. If buf is NULL, this function returns
925    the required initial value for the checksum.
926    An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
927    much faster. Usage example:
928
929      uLong adler = adler32(0L, Z_NULL, 0);
930
931      while (read_buffer(buffer, length) != EOF) {
932        adler = adler32(adler, buffer, length);
933      }
934      if (adler != original_adler) error();
935  */
936
937 uLong crc32   OF( ( uLong crc, const Byte * buf, uInt len ) );
938 /*
939      Update a running crc with the bytes buf[0..len-1] and return the updated
940    crc. If buf is NULL, this function returns the required initial value
941    for the crc. Pre- and post-conditioning (one's complement) is performed
942    within this function so it shouldn't be done by the application.
943    Usage example:
944
945      uLong crc = crc32(0L, Z_NULL, 0);
946
947      while (read_buffer(buffer, length) != EOF) {
948        crc = crc32(crc, buffer, length);
949      }
950      if (crc != original_crc) error();
951  */
952
953 // private stuff to not include cmdlib.h
954 /*
955    ============================================================================
956
957                     BYTE ORDER FUNCTIONS
958
959    ============================================================================
960  */
961
962 #ifdef _SGI_SOURCE
963 #define __BIG_ENDIAN__
964 #endif
965
966 #ifdef __BIG_ENDIAN__
967
968 short   __LittleShort( short l ){
969         byte b1,b2;
970
971         b1 = l & 255;
972         b2 = ( l >> 8 ) & 255;
973
974         return ( b1 << 8 ) + b2;
975 }
976
977 short   __BigShort( short l ){
978         return l;
979 }
980
981
982 int    __LittleLong( int l ){
983         byte b1,b2,b3,b4;
984
985         b1 = l & 255;
986         b2 = ( l >> 8 ) & 255;
987         b3 = ( l >> 16 ) & 255;
988         b4 = ( l >> 24 ) & 255;
989
990         return ( (int)b1 << 24 ) + ( (int)b2 << 16 ) + ( (int)b3 << 8 ) + b4;
991 }
992
993 int    __BigLong( int l ){
994         return l;
995 }
996
997
998 float   __LittleFloat( float l ){
999         union {byte b[4]; float f; } in, out;
1000
1001         in.f = l;
1002         out.b[0] = in.b[3];
1003         out.b[1] = in.b[2];
1004         out.b[2] = in.b[1];
1005         out.b[3] = in.b[0];
1006
1007         return out.f;
1008 }
1009
1010 float   __BigFloat( float l ){
1011         return l;
1012 }
1013
1014
1015 #else
1016
1017
1018 short   __BigShort( short l ){
1019         byte b1,b2;
1020
1021         b1 = l & 255;
1022         b2 = ( l >> 8 ) & 255;
1023
1024         return ( b1 << 8 ) + b2;
1025 }
1026
1027 short   __LittleShort( short l ){
1028         return l;
1029 }
1030
1031
1032 int    __BigLong( int l ){
1033         byte b1,b2,b3,b4;
1034
1035         b1 = l & 255;
1036         b2 = ( l >> 8 ) & 255;
1037         b3 = ( l >> 16 ) & 255;
1038         b4 = ( l >> 24 ) & 255;
1039
1040         return ( (int)b1 << 24 ) + ( (int)b2 << 16 ) + ( (int)b3 << 8 ) + b4;
1041 }
1042
1043 int    __LittleLong( int l ){
1044         return l;
1045 }
1046
1047 float   __BigFloat( float l ){
1048         union {byte b[4]; float f; } in, out;
1049
1050         in.f = l;
1051         out.b[0] = in.b[3];
1052         out.b[1] = in.b[2];
1053         out.b[2] = in.b[1];
1054         out.b[3] = in.b[0];
1055
1056         return out.f;
1057 }
1058
1059 float   __LittleFloat( float l ){
1060         return l;
1061 }
1062
1063
1064
1065 #endif
1066
1067
1068
1069
1070 /* various hacks, don't look :) */
1071
1072 /* deflateInit and inflateInit are macros to allow checking the zlib version
1073  * and the compiler's view of z_stream:
1074  */
1075 int deflateInit_ OF( ( z_streamp strm, int level,
1076                                            const char *version, int stream_size ) );
1077 int inflateInit_ OF( ( z_streamp strm,
1078                                            const char *version, int stream_size ) );
1079 int deflateInit2_ OF( ( z_streamp strm, int level, int method,
1080                                                 int windowBits, int memLevel,
1081                                                 int strategy, const char *version,
1082                                                 int stream_size ) );
1083 int inflateInit2_ OF( ( z_streamp strm, int windowBits,
1084                                                 const char *version, int stream_size ) );
1085 #define deflateInit( strm, level ) \
1086         deflateInit_( ( strm ), ( level ),       ZLIB_VERSION, sizeof( z_stream ) )
1087 #define inflateInit( strm )     \
1088         inflateInit_( ( strm ),                ZLIB_VERSION, sizeof( z_stream ) )
1089 #define deflateInit2( strm, level, method, windowBits, memLevel, strategy )     \
1090         deflateInit2_( ( strm ),( level ),( method ),( windowBits ),( memLevel ), \
1091                                    ( strategy ),           ZLIB_VERSION, sizeof( z_stream ) )
1092 #define inflateInit2( strm, windowBits ) \
1093         inflateInit2_( ( strm ), ( windowBits ), ZLIB_VERSION, sizeof( z_stream ) )
1094
1095
1096 const char   * zError           OF( (int err) );
1097 int inflateSyncPoint OF( (z_streamp z) );
1098 const uLong * get_crc_table    OF( (void) );
1099
1100 typedef unsigned char uch;
1101 typedef unsigned short ush;
1102 typedef unsigned long ulg;
1103
1104 extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */
1105 /* (size given to avoid silly warnings with Visual C++) */
1106
1107 #define ERR_MSG( err ) z_errmsg[Z_NEED_DICT - ( err )]
1108
1109 #define ERR_RETURN( strm,err ) \
1110         return ( strm->msg = (char*)ERR_MSG( err ), ( err ) )
1111 /* To be used only when the state is known to be valid */
1112
1113 /* common constants */
1114
1115 #ifndef DEF_WBITS
1116 #  define DEF_WBITS MAX_WBITS
1117 #endif
1118 /* default windowBits for decompression. MAX_WBITS is for compression only */
1119
1120 #if MAX_MEM_LEVEL >= 8
1121 #  define DEF_MEM_LEVEL 8
1122 #else
1123 #  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
1124 #endif
1125 /* default memLevel */
1126
1127 #define STORED_BLOCK 0
1128 #define STATIC_TREES 1
1129 #define DYN_TREES    2
1130 /* The three kinds of block type */
1131
1132 #define MIN_MATCH  3
1133 #define MAX_MATCH  258
1134 /* The minimum and maximum match lengths */
1135
1136 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
1137
1138 /* target dependencies */
1139
1140 /* Common defaults */
1141
1142 #ifndef OS_CODE
1143 #  define OS_CODE  0x03  /* assume Unix */
1144 #endif
1145
1146 #ifndef F_OPEN
1147 #  define F_OPEN( name, mode ) fopen( ( name ), ( mode ) )
1148 #endif
1149
1150 /* functions */
1151
1152 #ifdef HAVE_STRERROR
1153 extern char *strerror OF( (int) );
1154 #  define zstrerror( errnum ) strerror( errnum )
1155 #else
1156 #  define zstrerror( errnum ) ""
1157 #endif
1158
1159 #define zmemcpy memcpy
1160 #define zmemcmp memcmp
1161 #define zmemzero( dest, len ) memset( dest, 0, len )
1162
1163 /* Diagnostic functions */
1164 #ifdef _ZIP_DEBUG_
1165 int z_verbose = 0;
1166 #  define Assert( cond,msg ) assert( cond );
1167 //{if(!(cond)) Sys_Error(msg);}
1168 #  define Trace( x ) {if ( z_verbose >= 0 ) {Sys_Error x ; }}
1169 #  define Tracev( x ) {if ( z_verbose > 0 ) {Sys_Error x ; }}
1170 #  define Tracevv( x ) {if ( z_verbose > 1 ) {Sys_Error x ; }}
1171 #  define Tracec( c,x ) {if ( z_verbose > 0 && ( c ) ) {Sys_Error x ; }}
1172 #  define Tracecv( c,x ) {if ( z_verbose > 1 && ( c ) ) {Sys_Error x ; }}
1173 #else
1174 #  define Assert( cond,msg )
1175 #  define Trace( x )
1176 #  define Tracev( x )
1177 #  define Tracevv( x )
1178 #  define Tracec( c,x )
1179 #  define Tracecv( c,x )
1180 #endif
1181
1182
1183 typedef uLong ( *check_func ) OF ( ( uLong check, const Byte * buf, uInt len ) );
1184 voidp zcalloc OF( ( voidp opaque, unsigned items, unsigned size ) );
1185 void zcfree  OF( ( voidp opaque, voidp ptr ) );
1186
1187 #define ZALLOC( strm, items, size )     \
1188         ( *( ( strm )->zalloc ) )( ( strm )->opaque, ( items ), ( size ) )
1189 #define ZFREE( strm, addr )  ( *( ( strm )->zfree ) )( ( strm )->opaque, (voidp)( addr ) )
1190 #define TRY_FREE( s, p ) {if ( p ) {ZFREE( s, p ); }}
1191
1192
1193 #if !defined( unix ) && !defined( CASESENSITIVITYDEFAULT_YES ) && \
1194         !defined( CASESENSITIVITYDEFAULT_NO )
1195 #define CASESENSITIVITYDEFAULT_NO
1196 #endif
1197
1198
1199 #ifndef UNZ_BUFSIZE
1200 #define UNZ_BUFSIZE ( 65536 )
1201 #endif
1202
1203 #ifndef UNZ_MAXFILENAMEINZIP
1204 #define UNZ_MAXFILENAMEINZIP ( 256 )
1205 #endif
1206
1207 #ifndef ALLOC
1208 # define ALLOC( size ) ( safe_malloc( size ) )
1209 #endif
1210 #ifndef TRYFREE
1211 # define TRYFREE( p ) {if ( p ) {free( p ); }}
1212 #endif
1213
1214 #define SIZECENTRALDIRITEM ( 0x2e )
1215 #define SIZEZIPLOCALHEADER ( 0x1e )
1216
1217
1218
1219 /* ===========================================================================
1220      Read a byte from a gz_stream; update next_in and avail_in. Return EOF
1221    for end of file.
1222    IN assertion: the stream s has been sucessfully opened for reading.
1223  */
1224
1225 /*
1226    static int unzlocal_getByte(FILE *fin,int *pi)
1227    {
1228     unsigned char c;
1229     int err = fread(&c, 1, 1, fin);
1230     if (err==1)
1231     {
1232    *pi = (int)c;
1233         return UNZ_OK;
1234     }
1235     else
1236     {
1237         if (ferror(fin))
1238             return UNZ_ERRNO;
1239         else
1240             return UNZ_EOF;
1241     }
1242    }
1243  */
1244
1245 /* ===========================================================================
1246    Reads a long in LSB order from the given gz_stream. Sets
1247  */
1248 static int unzlocal_getShort( FILE* fin, uLong *pX ){
1249         short v;
1250
1251         if ( fread( &v, sizeof( v ), 1, fin ) != 1 ) {
1252                 return UNZ_EOF;
1253         }
1254
1255         *pX = __LittleShort( v );
1256         return UNZ_OK;
1257
1258 /*
1259     uLong x ;
1260     int i;
1261     int err;
1262
1263     err = unzlocal_getByte(fin,&i);
1264     x = (uLong)i;
1265
1266     if (err==UNZ_OK)
1267         err = unzlocal_getByte(fin,&i);
1268     x += ((uLong)i)<<8;
1269
1270     if (err==UNZ_OK)
1271    *pX = x;
1272     else
1273    *pX = 0;
1274     return err;
1275  */
1276 }
1277
1278 static int unzlocal_getLong( FILE *fin, uLong *pX ){
1279         int v;
1280
1281         if ( fread( &v, sizeof( v ), 1, fin ) != 1 ) {
1282                 return UNZ_EOF;
1283         }
1284
1285         *pX = __LittleLong( v );
1286         return UNZ_OK;
1287
1288 /*
1289     uLong x ;
1290     int i;
1291     int err;
1292
1293     err = unzlocal_getByte(fin,&i);
1294     x = (uLong)i;
1295
1296     if (err==UNZ_OK)
1297         err = unzlocal_getByte(fin,&i);
1298     x += ((uLong)i)<<8;
1299
1300     if (err==UNZ_OK)
1301         err = unzlocal_getByte(fin,&i);
1302     x += ((uLong)i)<<16;
1303
1304     if (err==UNZ_OK)
1305         err = unzlocal_getByte(fin,&i);
1306     x += ((uLong)i)<<24;
1307
1308     if (err==UNZ_OK)
1309    *pX = x;
1310     else
1311    *pX = 0;
1312     return err;
1313  */
1314 }
1315
1316
1317 /* My own strcmpi / strcasecmp */
1318 static int strcmpcasenosensitive_internal( const char* fileName1,const char* fileName2 ){
1319         for (;; )
1320         {
1321                 char c1 = *( fileName1++ );
1322                 char c2 = *( fileName2++ );
1323                 if ( ( c1 >= 'a' ) && ( c1 <= 'z' ) ) {
1324                         c1 -= 0x20;
1325                 }
1326                 if ( ( c2 >= 'a' ) && ( c2 <= 'z' ) ) {
1327                         c2 -= 0x20;
1328                 }
1329                 if ( c1 == '\0' ) {
1330                         return ( ( c2 == '\0' ) ? 0 : -1 );
1331                 }
1332                 if ( c2 == '\0' ) {
1333                         return 1;
1334                 }
1335                 if ( c1 < c2 ) {
1336                         return -1;
1337                 }
1338                 if ( c1 > c2 ) {
1339                         return 1;
1340                 }
1341         }
1342 }
1343
1344
1345 #ifdef  CASESENSITIVITYDEFAULT_NO
1346 #define CASESENSITIVITYDEFAULTVALUE 2
1347 #else
1348 #define CASESENSITIVITYDEFAULTVALUE 1
1349 #endif
1350
1351 #ifndef STRCMPCASENOSENTIVEFUNCTION
1352 #define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
1353 #endif
1354
1355 /*
1356    Compare two filename (fileName1,fileName2).
1357    If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
1358    If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
1359                                                                 or strcasecmp)
1360    If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
1361         (like 1 on Unix, 2 on Windows)
1362
1363  */
1364 extern int unzStringFileNameCompare( const char* fileName1,const char* fileName2,int iCaseSensitivity ){
1365         if ( iCaseSensitivity == 0 ) {
1366                 iCaseSensitivity = CASESENSITIVITYDEFAULTVALUE;
1367         }
1368
1369         if ( iCaseSensitivity == 1 ) {
1370                 return strcmp( fileName1,fileName2 );
1371         }
1372
1373         return STRCMPCASENOSENTIVEFUNCTION( fileName1,fileName2 );
1374 }
1375
1376 #define BUFREADCOMMENT ( 0x400 )
1377
1378 /*
1379    Locate the Central directory of a zipfile (at the end, just before
1380     the global comment)
1381  */
1382 static uLong unzlocal_SearchCentralDir( FILE *fin ){
1383         unsigned char* buf;
1384         uLong uSizeFile;
1385         uLong uBackRead;
1386         uLong uMaxBack = 0xffff; /* maximum size of global comment */
1387         uLong uPosFound = 0;
1388
1389         if ( fseek( fin,0,SEEK_END ) != 0 ) {
1390                 return 0;
1391         }
1392
1393
1394         uSizeFile = ftell( fin );
1395
1396         if ( uMaxBack > uSizeFile ) {
1397                 uMaxBack = uSizeFile;
1398         }
1399
1400         buf = (unsigned char*)safe_malloc( BUFREADCOMMENT + 4 );
1401         if ( buf == NULL ) {
1402                 return 0;
1403         }
1404
1405         uBackRead = 4;
1406         while ( uBackRead < uMaxBack )
1407         {
1408                 uLong uReadSize,uReadPos ;
1409                 int i;
1410                 if ( uBackRead + BUFREADCOMMENT > uMaxBack ) {
1411                         uBackRead = uMaxBack;
1412                 }
1413                 else{
1414                         uBackRead += BUFREADCOMMENT;
1415                 }
1416                 uReadPos = uSizeFile - uBackRead ;
1417
1418                 uReadSize = ( ( BUFREADCOMMENT + 4 ) < ( uSizeFile - uReadPos ) ) ?
1419                                         ( BUFREADCOMMENT + 4 ) : ( uSizeFile - uReadPos );
1420                 if ( fseek( fin,uReadPos,SEEK_SET ) != 0 ) {
1421                         break;
1422                 }
1423
1424                 if ( fread( buf,(uInt)uReadSize,1,fin ) != 1 ) {
1425                         break;
1426                 }
1427
1428                 for ( i = (int)uReadSize - 3; ( i-- ) > 0; )
1429                         if ( ( ( *( buf + i ) ) == 0x50 ) && ( ( *( buf + i + 1 ) ) == 0x4b ) &&
1430                                  ( ( *( buf + i + 2 ) ) == 0x05 ) && ( ( *( buf + i + 3 ) ) == 0x06 ) ) {
1431                                 uPosFound = uReadPos + i;
1432                                 break;
1433                         }
1434
1435                 if ( uPosFound != 0 ) {
1436                         break;
1437                 }
1438         }
1439         free( buf );
1440         return uPosFound;
1441 }
1442
1443 extern unzFile unzReOpen( const char* path, unzFile file ){
1444         unz_s *s;
1445         FILE * fin;
1446
1447         fin = fopen( path,"rb" );
1448         if ( fin == NULL ) {
1449                 return NULL;
1450         }
1451
1452         s = (unz_s*)safe_malloc( sizeof( unz_s ) );
1453         memcpy( s, (unz_s*)file, sizeof( unz_s ) );
1454
1455         s->file = fin;
1456         return (unzFile)s;
1457 }
1458
1459 /*
1460    Open a Zip file. path contain the full pathname (by example,
1461      on a Windows NT computer "c:\\test\\zlib109.zip" or on an Unix computer
1462      "zlib/zlib109.zip".
1463      If the zipfile cannot be opened (file don't exist or in not valid), the
1464        return value is NULL.
1465      Else, the return value is a unzFile Handle, usable with other function
1466        of this unzip package.
1467  */
1468 extern unzFile unzOpen( const char* path ){
1469         unz_s us;
1470         unz_s *s;
1471         uLong central_pos,uL;
1472         FILE * fin ;
1473
1474         uLong number_disk;          /* number of the current dist, used for
1475                                        spaning ZIP, unsupported, always 0*/
1476         uLong number_disk_with_CD;  /* number the the disk with central dir, used
1477                                        for spaning ZIP, unsupported, always 0*/
1478         uLong number_entry_CD;      /* total number of entries in
1479                                        the central dir
1480                                        (same than number_entry on nospan) */
1481
1482         int err = UNZ_OK;
1483
1484         fin = fopen( path,"rb" );
1485         if ( fin == NULL ) {
1486                 return NULL;
1487         }
1488
1489         central_pos = unzlocal_SearchCentralDir( fin );
1490         if ( central_pos == 0 ) {
1491                 err = UNZ_ERRNO;
1492         }
1493
1494         if ( fseek( fin,central_pos,SEEK_SET ) != 0 ) {
1495                 err = UNZ_ERRNO;
1496         }
1497
1498         /* the signature, already checked */
1499         if ( unzlocal_getLong( fin,&uL ) != UNZ_OK ) {
1500                 err = UNZ_ERRNO;
1501         }
1502
1503         /* number of this disk */
1504         if ( unzlocal_getShort( fin,&number_disk ) != UNZ_OK ) {
1505                 err = UNZ_ERRNO;
1506         }
1507
1508         /* number of the disk with the start of the central directory */
1509         if ( unzlocal_getShort( fin,&number_disk_with_CD ) != UNZ_OK ) {
1510                 err = UNZ_ERRNO;
1511         }
1512
1513         /* total number of entries in the central dir on this disk */
1514         if ( unzlocal_getShort( fin,&us.gi.number_entry ) != UNZ_OK ) {
1515                 err = UNZ_ERRNO;
1516         }
1517
1518         /* total number of entries in the central dir */
1519         if ( unzlocal_getShort( fin,&number_entry_CD ) != UNZ_OK ) {
1520                 err = UNZ_ERRNO;
1521         }
1522
1523         if ( ( number_entry_CD != us.gi.number_entry ) ||
1524                  ( number_disk_with_CD != 0 ) ||
1525                  ( number_disk != 0 ) ) {
1526                 err = UNZ_BADZIPFILE;
1527         }
1528
1529         /* size of the central directory */
1530         if ( unzlocal_getLong( fin,&us.size_central_dir ) != UNZ_OK ) {
1531                 err = UNZ_ERRNO;
1532         }
1533
1534         /* offset of start of central directory with respect to the
1535               starting disk number */
1536         if ( unzlocal_getLong( fin,&us.offset_central_dir ) != UNZ_OK ) {
1537                 err = UNZ_ERRNO;
1538         }
1539
1540         /* zipfile comment length */
1541         if ( unzlocal_getShort( fin,&us.gi.size_comment ) != UNZ_OK ) {
1542                 err = UNZ_ERRNO;
1543         }
1544
1545         if ( ( central_pos < us.offset_central_dir + us.size_central_dir ) &&
1546                  ( err == UNZ_OK ) ) {
1547                 err = UNZ_BADZIPFILE;
1548         }
1549
1550         if ( err != UNZ_OK ) {
1551                 fclose( fin );
1552                 return NULL;
1553         }
1554
1555         us.file = fin;
1556         us.byte_before_the_zipfile = central_pos -
1557                                                                  ( us.offset_central_dir + us.size_central_dir );
1558         us.central_pos = central_pos;
1559         us.pfile_in_zip_read = NULL;
1560
1561
1562         s = (unz_s*)safe_malloc( sizeof( unz_s ) );
1563         *s = us;
1564 //      unzGoToFirstFile((unzFile)s);
1565         return (unzFile)s;
1566 }
1567
1568
1569 /*
1570    Close a ZipFile opened with unzipOpen.
1571    If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
1572     these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
1573    return UNZ_OK if there is no problem. */
1574 extern int unzClose( unzFile file ){
1575         unz_s* s;
1576         if ( file == NULL ) {
1577                 return UNZ_PARAMERROR;
1578         }
1579         s = (unz_s*)file;
1580
1581         if ( s->pfile_in_zip_read != NULL ) {
1582                 unzCloseCurrentFile( file );
1583         }
1584
1585         fclose( s->file );
1586         free( s );
1587         return UNZ_OK;
1588 }
1589
1590
1591 /*
1592    Write info about the ZipFile in the *pglobal_info structure.
1593    No preparation of the structure is needed
1594    return UNZ_OK if there is no problem. */
1595 extern int unzGetGlobalInfo( unzFile file,unz_global_info *pglobal_info ){
1596         unz_s* s;
1597         if ( file == NULL ) {
1598                 return UNZ_PARAMERROR;
1599         }
1600         s = (unz_s*)file;
1601         *pglobal_info = s->gi;
1602         return UNZ_OK;
1603 }
1604
1605
1606 /*
1607    Translate date/time from Dos format to tm_unz (readable more easilty)
1608  */
1609 static void unzlocal_DosDateToTmuDate( uLong ulDosDate, tm_unz* ptm ){
1610         uLong uDate;
1611         uDate = (uLong)( ulDosDate >> 16 );
1612         ptm->tm_mday = (uInt)( uDate & 0x1f ) ;
1613         ptm->tm_mon =  (uInt)( ( ( ( uDate ) & 0x1E0 ) / 0x20 ) - 1 ) ;
1614         ptm->tm_year = (uInt)( ( ( uDate & 0x0FE00 ) / 0x0200 ) + 1980 ) ;
1615
1616         ptm->tm_hour = (uInt) ( ( ulDosDate & 0xF800 ) / 0x800 );
1617         ptm->tm_min =  (uInt) ( ( ulDosDate & 0x7E0 ) / 0x20 ) ;
1618         ptm->tm_sec =  (uInt) ( 2 * ( ulDosDate & 0x1f ) ) ;
1619 }
1620
1621 /*
1622    Get Info about the current file in the zipfile, with internal only info
1623  */
1624 static int unzlocal_GetCurrentFileInfoInternal( unzFile file,
1625                                                                                                 unz_file_info *pfile_info,
1626                                                                                                 unz_file_info_internal
1627                                                                                                 *pfile_info_internal,
1628                                                                                                 char *szFileName,
1629                                                                                                 uLong fileNameBufferSize,
1630                                                                                                 void *extraField,
1631                                                                                                 uLong extraFieldBufferSize,
1632                                                                                                 char *szComment,
1633                                                                                                 uLong commentBufferSize ){
1634         unz_s* s;
1635         unz_file_info file_info;
1636         unz_file_info_internal file_info_internal;
1637         int err = UNZ_OK;
1638         uLong uMagic;
1639         long lSeek = 0;
1640
1641         if ( file == NULL ) {
1642                 return UNZ_PARAMERROR;
1643         }
1644         s = (unz_s*)file;
1645         if ( fseek( s->file,s->pos_in_central_dir + s->byte_before_the_zipfile,SEEK_SET ) != 0 ) {
1646                 err = UNZ_ERRNO;
1647         }
1648
1649
1650         /* we check the magic */
1651         if ( err == UNZ_OK ) {
1652                 if ( unzlocal_getLong( s->file,&uMagic ) != UNZ_OK ) {
1653                         err = UNZ_ERRNO;
1654                 }
1655                 else if ( uMagic != 0x02014b50 ) {
1656                         err = UNZ_BADZIPFILE;
1657                 }
1658         }
1659
1660         if ( unzlocal_getShort( s->file,&file_info.version ) != UNZ_OK ) {
1661                 err = UNZ_ERRNO;
1662         }
1663
1664         if ( unzlocal_getShort( s->file,&file_info.version_needed ) != UNZ_OK ) {
1665                 err = UNZ_ERRNO;
1666         }
1667
1668         if ( unzlocal_getShort( s->file,&file_info.flag ) != UNZ_OK ) {
1669                 err = UNZ_ERRNO;
1670         }
1671
1672         if ( unzlocal_getShort( s->file,&file_info.compression_method ) != UNZ_OK ) {
1673                 err = UNZ_ERRNO;
1674         }
1675
1676         if ( unzlocal_getLong( s->file,&file_info.dosDate ) != UNZ_OK ) {
1677                 err = UNZ_ERRNO;
1678         }
1679
1680         unzlocal_DosDateToTmuDate( file_info.dosDate,&file_info.tmu_date );
1681
1682         if ( unzlocal_getLong( s->file,&file_info.crc ) != UNZ_OK ) {
1683                 err = UNZ_ERRNO;
1684         }
1685
1686         if ( unzlocal_getLong( s->file,&file_info.compressed_size ) != UNZ_OK ) {
1687                 err = UNZ_ERRNO;
1688         }
1689
1690         if ( unzlocal_getLong( s->file,&file_info.uncompressed_size ) != UNZ_OK ) {
1691                 err = UNZ_ERRNO;
1692         }
1693
1694         if ( unzlocal_getShort( s->file,&file_info.size_filename ) != UNZ_OK ) {
1695                 err = UNZ_ERRNO;
1696         }
1697
1698         if ( unzlocal_getShort( s->file,&file_info.size_file_extra ) != UNZ_OK ) {
1699                 err = UNZ_ERRNO;
1700         }
1701
1702         if ( unzlocal_getShort( s->file,&file_info.size_file_comment ) != UNZ_OK ) {
1703                 err = UNZ_ERRNO;
1704         }
1705
1706         if ( unzlocal_getShort( s->file,&file_info.disk_num_start ) != UNZ_OK ) {
1707                 err = UNZ_ERRNO;
1708         }
1709
1710         if ( unzlocal_getShort( s->file,&file_info.internal_fa ) != UNZ_OK ) {
1711                 err = UNZ_ERRNO;
1712         }
1713
1714         if ( unzlocal_getLong( s->file,&file_info.external_fa ) != UNZ_OK ) {
1715                 err = UNZ_ERRNO;
1716         }
1717
1718         if ( unzlocal_getLong( s->file,&file_info_internal.offset_curfile ) != UNZ_OK ) {
1719                 err = UNZ_ERRNO;
1720         }
1721
1722         lSeek += file_info.size_filename;
1723         if ( ( err == UNZ_OK ) && ( szFileName != NULL ) ) {
1724                 uLong uSizeRead ;
1725                 if ( file_info.size_filename < fileNameBufferSize ) {
1726                         *( szFileName + file_info.size_filename ) = '\0';
1727                         uSizeRead = file_info.size_filename;
1728                 }
1729                 else{
1730                         uSizeRead = fileNameBufferSize;
1731                 }
1732
1733                 if ( ( file_info.size_filename > 0 ) && ( fileNameBufferSize > 0 ) ) {
1734                         if ( fread( szFileName,(uInt)uSizeRead,1,s->file ) != 1 ) {
1735                                 err = UNZ_ERRNO;
1736                         }
1737                 }
1738                 lSeek -= uSizeRead;
1739         }
1740
1741
1742         if ( ( err == UNZ_OK ) && ( extraField != NULL ) ) {
1743                 uLong uSizeRead ;
1744                 if ( file_info.size_file_extra < extraFieldBufferSize ) {
1745                         uSizeRead = file_info.size_file_extra;
1746                 }
1747                 else{
1748                         uSizeRead = extraFieldBufferSize;
1749                 }
1750
1751                 if ( lSeek != 0 ) {
1752                         if ( fseek( s->file,lSeek,SEEK_CUR ) == 0 ) {
1753                                 lSeek = 0;
1754                         }
1755                         else{
1756                                 err = UNZ_ERRNO;
1757                         }
1758                 }
1759                 if ( ( file_info.size_file_extra > 0 ) && ( extraFieldBufferSize > 0 ) ) {
1760                         if ( fread( extraField,(uInt)uSizeRead,1,s->file ) != 1 ) {
1761                                 err = UNZ_ERRNO;
1762                         }
1763                 }
1764                 lSeek += file_info.size_file_extra - uSizeRead;
1765         }
1766         else{
1767                 lSeek += file_info.size_file_extra;
1768         }
1769
1770
1771         if ( ( err == UNZ_OK ) && ( szComment != NULL ) ) {
1772                 uLong uSizeRead ;
1773                 if ( file_info.size_file_comment < commentBufferSize ) {
1774                         *( szComment + file_info.size_file_comment ) = '\0';
1775                         uSizeRead = file_info.size_file_comment;
1776                 }
1777                 else{
1778                         uSizeRead = commentBufferSize;
1779                 }
1780
1781                 if ( lSeek != 0 ) {
1782                         if ( fseek( s->file,lSeek,SEEK_CUR ) == 0 ) {
1783                                 lSeek = 0;
1784                         }
1785                         else{
1786                                 err = UNZ_ERRNO;
1787                         }
1788                 }
1789                 if ( ( file_info.size_file_comment > 0 ) && ( commentBufferSize > 0 ) ) {
1790                         if ( fread( szComment,(uInt)uSizeRead,1,s->file ) != 1 ) {
1791                                 err = UNZ_ERRNO;
1792                         }
1793                 }
1794                 lSeek += file_info.size_file_comment - uSizeRead;
1795         }
1796         else{
1797                 lSeek += file_info.size_file_comment;
1798         }
1799
1800         if ( ( err == UNZ_OK ) && ( pfile_info != NULL ) ) {
1801                 *pfile_info = file_info;
1802         }
1803
1804         if ( ( err == UNZ_OK ) && ( pfile_info_internal != NULL ) ) {
1805                 *pfile_info_internal = file_info_internal;
1806         }
1807
1808         return err;
1809 }
1810
1811
1812
1813 /*
1814    Write info about the ZipFile in the *pglobal_info structure.
1815    No preparation of the structure is needed
1816    return UNZ_OK if there is no problem.
1817  */
1818 extern int unzGetCurrentFileInfo(  unzFile file, unz_file_info *pfile_info,
1819                                                                    char *szFileName, uLong fileNameBufferSize,
1820                                                                    void *extraField, uLong extraFieldBufferSize,
1821                                                                    char *szComment, uLong commentBufferSize ){
1822         return unzlocal_GetCurrentFileInfoInternal( file,pfile_info,NULL,
1823                                                                                                 szFileName,fileNameBufferSize,
1824                                                                                                 extraField,extraFieldBufferSize,
1825                                                                                                 szComment,commentBufferSize );
1826 }
1827
1828 /*
1829    Set the current file of the zipfile to the first file.
1830    return UNZ_OK if there is no problem
1831  */
1832 extern int unzGoToFirstFile( unzFile file ){
1833         int err = UNZ_OK;
1834         unz_s* s;
1835         if ( file == NULL ) {
1836                 return UNZ_PARAMERROR;
1837         }
1838         s = (unz_s*)file;
1839         s->pos_in_central_dir = s->offset_central_dir;
1840         s->num_file = 0;
1841         err = unzlocal_GetCurrentFileInfoInternal( file,&s->cur_file_info,
1842                                                                                            &s->cur_file_info_internal,
1843                                                                                            NULL,0,NULL,0,NULL,0 );
1844         s->current_file_ok = ( err == UNZ_OK );
1845         return err;
1846 }
1847
1848
1849 /*
1850    Set the current file of the zipfile to the next file.
1851    return UNZ_OK if there is no problem
1852    return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
1853  */
1854 extern int unzGoToNextFile( unzFile file ){
1855         unz_s* s;
1856         int err;
1857
1858         if ( file == NULL ) {
1859                 return UNZ_PARAMERROR;
1860         }
1861         s = (unz_s*)file;
1862         if ( !s->current_file_ok ) {
1863                 return UNZ_END_OF_LIST_OF_FILE;
1864         }
1865         if ( s->num_file + 1 == s->gi.number_entry ) {
1866                 return UNZ_END_OF_LIST_OF_FILE;
1867         }
1868
1869         s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
1870                                                          s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
1871         s->num_file++;
1872         err = unzlocal_GetCurrentFileInfoInternal( file,&s->cur_file_info,
1873                                                                                            &s->cur_file_info_internal,
1874                                                                                            NULL,0,NULL,0,NULL,0 );
1875         s->current_file_ok = ( err == UNZ_OK );
1876         return err;
1877 }
1878
1879
1880 /*
1881    Try locate the file szFileName in the zipfile.
1882    For the iCaseSensitivity signification, see unzipStringFileNameCompare
1883
1884    return value :
1885    UNZ_OK if the file is found. It becomes the current file.
1886    UNZ_END_OF_LIST_OF_FILE if the file is not found
1887  */
1888 extern int unzLocateFile( unzFile file, const char *szFileName, int iCaseSensitivity ){
1889         unz_s* s;
1890         int err;
1891
1892
1893         uLong num_fileSaved;
1894         uLong pos_in_central_dirSaved;
1895
1896
1897         if ( file == NULL ) {
1898                 return UNZ_PARAMERROR;
1899         }
1900
1901         if ( strlen( szFileName ) >= UNZ_MAXFILENAMEINZIP ) {
1902                 return UNZ_PARAMERROR;
1903         }
1904
1905         s = (unz_s*)file;
1906         if ( !s->current_file_ok ) {
1907                 return UNZ_END_OF_LIST_OF_FILE;
1908         }
1909
1910         num_fileSaved = s->num_file;
1911         pos_in_central_dirSaved = s->pos_in_central_dir;
1912
1913         err = unzGoToFirstFile( file );
1914
1915         while ( err == UNZ_OK )
1916         {
1917                 char szCurrentFileName[UNZ_MAXFILENAMEINZIP + 1];
1918                 unzGetCurrentFileInfo( file,NULL,
1919                                                            szCurrentFileName,sizeof( szCurrentFileName ) - 1,
1920                                                            NULL,0,NULL,0 );
1921                 if ( unzStringFileNameCompare( szCurrentFileName,
1922                                                                            szFileName,iCaseSensitivity ) == 0 ) {
1923                         return UNZ_OK;
1924                 }
1925                 err = unzGoToNextFile( file );
1926         }
1927
1928         s->num_file = num_fileSaved ;
1929         s->pos_in_central_dir = pos_in_central_dirSaved ;
1930         return err;
1931 }
1932
1933
1934 /*
1935    Read the static header of the current zipfile
1936    Check the coherency of the static header and info in the end of central
1937         directory about this file
1938    store in *piSizeVar the size of extra info in static header
1939         (filename and size of extra field data)
1940  */
1941 static int unzlocal_CheckCurrentFileCoherencyHeader( unz_s* s, uInt* piSizeVar,
1942                                                                                                          uLong *poffset_local_extrafield,
1943                                                                                                          uInt *psize_local_extrafield ){
1944         uLong uMagic,uData,uFlags;
1945         uLong size_filename;
1946         uLong size_extra_field;
1947         int err = UNZ_OK;
1948
1949         *piSizeVar = 0;
1950         *poffset_local_extrafield = 0;
1951         *psize_local_extrafield = 0;
1952
1953         if ( fseek( s->file,s->cur_file_info_internal.offset_curfile +
1954                                 s->byte_before_the_zipfile,SEEK_SET ) != 0 ) {
1955                 return UNZ_ERRNO;
1956         }
1957
1958
1959         if ( err == UNZ_OK ) {
1960                 if ( unzlocal_getLong( s->file,&uMagic ) != UNZ_OK ) {
1961                         err = UNZ_ERRNO;
1962                 }
1963                 else if ( uMagic != 0x04034b50 ) {
1964                         err = UNZ_BADZIPFILE;
1965                 }
1966         }
1967
1968         if ( unzlocal_getShort( s->file,&uData ) != UNZ_OK ) {
1969                 err = UNZ_ERRNO;
1970         }
1971 /*
1972     else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
1973         err=UNZ_BADZIPFILE;
1974  */
1975         if ( unzlocal_getShort( s->file,&uFlags ) != UNZ_OK ) {
1976                 err = UNZ_ERRNO;
1977         }
1978
1979         if ( unzlocal_getShort( s->file,&uData ) != UNZ_OK ) {
1980                 err = UNZ_ERRNO;
1981         }
1982         else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.compression_method ) ) {
1983                 err = UNZ_BADZIPFILE;
1984         }
1985
1986         if ( ( err == UNZ_OK ) && ( s->cur_file_info.compression_method != 0 ) &&
1987                  ( s->cur_file_info.compression_method != Z_DEFLATED ) ) {
1988                 err = UNZ_BADZIPFILE;
1989         }
1990
1991         if ( unzlocal_getLong( s->file,&uData ) != UNZ_OK ) { /* date/time */
1992                 err = UNZ_ERRNO;
1993         }
1994
1995         if ( unzlocal_getLong( s->file,&uData ) != UNZ_OK ) { /* crc */
1996                 err = UNZ_ERRNO;
1997         }
1998         else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.crc ) &&
1999                           ( ( uFlags & 8 ) == 0 ) ) {
2000                 err = UNZ_BADZIPFILE;
2001         }
2002
2003         if ( unzlocal_getLong( s->file,&uData ) != UNZ_OK ) { /* size compr */
2004                 err = UNZ_ERRNO;
2005         }
2006         else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.compressed_size ) &&
2007                           ( ( uFlags & 8 ) == 0 ) ) {
2008                 err = UNZ_BADZIPFILE;
2009         }
2010
2011         if ( unzlocal_getLong( s->file,&uData ) != UNZ_OK ) { /* size uncompr */
2012                 err = UNZ_ERRNO;
2013         }
2014         else if ( ( err == UNZ_OK ) && ( uData != s->cur_file_info.uncompressed_size ) &&
2015                           ( ( uFlags & 8 ) == 0 ) ) {
2016                 err = UNZ_BADZIPFILE;
2017         }
2018
2019
2020         if ( unzlocal_getShort( s->file,&size_filename ) != UNZ_OK ) {
2021                 err = UNZ_ERRNO;
2022         }
2023         else if ( ( err == UNZ_OK ) && ( size_filename != s->cur_file_info.size_filename ) ) {
2024                 err = UNZ_BADZIPFILE;
2025         }
2026
2027         *piSizeVar += (uInt)size_filename;
2028
2029         if ( unzlocal_getShort( s->file,&size_extra_field ) != UNZ_OK ) {
2030                 err = UNZ_ERRNO;
2031         }
2032         *poffset_local_extrafield = s->cur_file_info_internal.offset_curfile +
2033                                                                 SIZEZIPLOCALHEADER + size_filename;
2034         *psize_local_extrafield = (uInt)size_extra_field;
2035
2036         *piSizeVar += (uInt)size_extra_field;
2037
2038         return err;
2039 }
2040
2041 /*
2042    Open for reading data the current file in the zipfile.
2043    If there is no error and the file is opened, the return value is UNZ_OK.
2044  */
2045 extern int unzOpenCurrentFile( unzFile file ){
2046         int err = UNZ_OK;
2047         int Store;
2048         uInt iSizeVar;
2049         unz_s* s;
2050         file_in_zip_read_info_s* pfile_in_zip_read_info;
2051         uLong offset_local_extrafield;  /* offset of the static extra field */
2052         uInt size_local_extrafield;     /* size of the static extra field */
2053
2054         if ( file == NULL ) {
2055                 return UNZ_PARAMERROR;
2056         }
2057         s = (unz_s*)file;
2058         if ( !s->current_file_ok ) {
2059                 return UNZ_PARAMERROR;
2060         }
2061
2062         if ( s->pfile_in_zip_read != NULL ) {
2063                 unzCloseCurrentFile( file );
2064         }
2065
2066         if ( unzlocal_CheckCurrentFileCoherencyHeader( s,&iSizeVar,
2067                                                                                                    &offset_local_extrafield,&size_local_extrafield ) != UNZ_OK ) {
2068                 return UNZ_BADZIPFILE;
2069         }
2070
2071         pfile_in_zip_read_info = (file_in_zip_read_info_s*)
2072                                                          safe_malloc( sizeof( file_in_zip_read_info_s ) );
2073         if ( pfile_in_zip_read_info == NULL ) {
2074                 return UNZ_INTERNALERROR;
2075         }
2076
2077         pfile_in_zip_read_info->read_buffer = (char*)safe_malloc( UNZ_BUFSIZE );
2078         pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
2079         pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
2080         pfile_in_zip_read_info->pos_local_extrafield = 0;
2081
2082         if ( pfile_in_zip_read_info->read_buffer == NULL ) {
2083                 free( pfile_in_zip_read_info );
2084                 return UNZ_INTERNALERROR;
2085         }
2086
2087         pfile_in_zip_read_info->stream_initialised = 0;
2088
2089         if ( ( s->cur_file_info.compression_method != 0 ) &&
2090                  ( s->cur_file_info.compression_method != Z_DEFLATED ) ) {
2091                 err = UNZ_BADZIPFILE;
2092         }
2093         Store = s->cur_file_info.compression_method == 0;
2094
2095         pfile_in_zip_read_info->crc32_wait = s->cur_file_info.crc;
2096         pfile_in_zip_read_info->crc32 = 0;
2097         pfile_in_zip_read_info->compression_method =
2098                 s->cur_file_info.compression_method;
2099         pfile_in_zip_read_info->file = s->file;
2100         pfile_in_zip_read_info->byte_before_the_zipfile = s->byte_before_the_zipfile;
2101
2102         pfile_in_zip_read_info->stream.total_out = 0;
2103
2104         if ( !Store ) {
2105                 pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
2106                 pfile_in_zip_read_info->stream.zfree = (free_func)0;
2107                 pfile_in_zip_read_info->stream.opaque = (voidp)0;
2108
2109                 err = inflateInit2( &pfile_in_zip_read_info->stream, -MAX_WBITS );
2110                 if ( err == Z_OK ) {
2111                         pfile_in_zip_read_info->stream_initialised = 1;
2112                 }
2113                 /* windowBits is passed < 0 to tell that there is no zlib header.
2114                  * Note that in this case inflate *requires* an extra "dummy" byte
2115                  * after the compressed stream in order to complete decompression and
2116                  * return Z_STREAM_END.
2117                  * In unzip, i don't wait absolutely Z_STREAM_END because I known the
2118                  * size of both compressed and uncompressed data
2119                  */
2120         }
2121         pfile_in_zip_read_info->rest_read_compressed =
2122                 s->cur_file_info.compressed_size ;
2123         pfile_in_zip_read_info->rest_read_uncompressed =
2124                 s->cur_file_info.uncompressed_size ;
2125
2126
2127         pfile_in_zip_read_info->pos_in_zipfile =
2128                 s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
2129                 iSizeVar;
2130
2131         pfile_in_zip_read_info->stream.avail_in = (uInt)0;
2132
2133
2134         s->pfile_in_zip_read = pfile_in_zip_read_info;
2135         return UNZ_OK;
2136 }
2137
2138
2139 /*
2140    Read bytes from the current file.
2141    buf contain buffer where data must be copied
2142    len the size of buf.
2143
2144    return the number of byte copied if somes bytes are copied
2145    return 0 if the end of file was reached
2146    return <0 with error code if there is an error
2147     (UNZ_ERRNO for IO error, or zLib error for uncompress error)
2148  */
2149 extern int unzReadCurrentFile( unzFile file, void *buf, unsigned len ){
2150         int err = UNZ_OK;
2151         uInt iRead = 0;
2152         unz_s* s;
2153         file_in_zip_read_info_s* pfile_in_zip_read_info;
2154         if ( file == NULL ) {
2155                 return UNZ_PARAMERROR;
2156         }
2157         s = (unz_s*)file;
2158         pfile_in_zip_read_info = s->pfile_in_zip_read;
2159
2160         if ( pfile_in_zip_read_info == NULL ) {
2161                 return UNZ_PARAMERROR;
2162         }
2163
2164
2165         if ( ( pfile_in_zip_read_info->read_buffer == NULL ) ) {
2166                 return UNZ_END_OF_LIST_OF_FILE;
2167         }
2168         if ( len == 0 ) {
2169                 return 0;
2170         }
2171
2172         pfile_in_zip_read_info->stream.next_out = (Byte*)buf;
2173
2174         pfile_in_zip_read_info->stream.avail_out = (uInt)len;
2175
2176         if ( len > pfile_in_zip_read_info->rest_read_uncompressed ) {
2177                 pfile_in_zip_read_info->stream.avail_out =
2178                         (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
2179         }
2180
2181         while ( pfile_in_zip_read_info->stream.avail_out > 0 )
2182         {
2183                 if ( ( pfile_in_zip_read_info->stream.avail_in == 0 ) &&
2184                          ( pfile_in_zip_read_info->rest_read_compressed > 0 ) ) {
2185                         uInt uReadThis = UNZ_BUFSIZE;
2186                         if ( pfile_in_zip_read_info->rest_read_compressed < uReadThis ) {
2187                                 uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
2188                         }
2189                         if ( uReadThis == 0 ) {
2190                                 return UNZ_EOF;
2191                         }
2192                         if ( s->cur_file_info.compressed_size == pfile_in_zip_read_info->rest_read_compressed ) {
2193                                 if ( fseek( pfile_in_zip_read_info->file,
2194                                                         pfile_in_zip_read_info->pos_in_zipfile +
2195                                                         pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET ) != 0 ) {
2196                                         return UNZ_ERRNO;
2197                                 }
2198                         }
2199                         if ( fread( pfile_in_zip_read_info->read_buffer,uReadThis,1,
2200                                                 pfile_in_zip_read_info->file ) != 1 ) {
2201                                 return UNZ_ERRNO;
2202                         }
2203                         pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
2204
2205                         pfile_in_zip_read_info->rest_read_compressed -= uReadThis;
2206
2207                         pfile_in_zip_read_info->stream.next_in =
2208                                 (Byte*)pfile_in_zip_read_info->read_buffer;
2209                         pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
2210                 }
2211
2212                 if ( pfile_in_zip_read_info->compression_method == 0 ) {
2213                         uInt uDoCopy,i ;
2214                         if ( pfile_in_zip_read_info->stream.avail_out <
2215                                  pfile_in_zip_read_info->stream.avail_in ) {
2216                                 uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
2217                         }
2218                         else{
2219                                 uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
2220                         }
2221
2222                         for ( i = 0; i < uDoCopy; i++ )
2223                                 *( pfile_in_zip_read_info->stream.next_out + i ) =
2224                                         *( pfile_in_zip_read_info->stream.next_in + i );
2225
2226                         pfile_in_zip_read_info->crc32 = crc32( pfile_in_zip_read_info->crc32,
2227                                                                                                    pfile_in_zip_read_info->stream.next_out,
2228                                                                                                    uDoCopy );
2229                         pfile_in_zip_read_info->rest_read_uncompressed -= uDoCopy;
2230                         pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
2231                         pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
2232                         pfile_in_zip_read_info->stream.next_out += uDoCopy;
2233                         pfile_in_zip_read_info->stream.next_in += uDoCopy;
2234                         pfile_in_zip_read_info->stream.total_out += uDoCopy;
2235                         iRead += uDoCopy;
2236                 }
2237                 else
2238                 {
2239                         uLong uTotalOutBefore,uTotalOutAfter;
2240                         const Byte *bufBefore;
2241                         uLong uOutThis;
2242                         int flush = Z_SYNC_FLUSH;
2243
2244                         uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
2245                         bufBefore = pfile_in_zip_read_info->stream.next_out;
2246
2247                         /*
2248                            if ((pfile_in_zip_read_info->rest_read_uncompressed ==
2249                                  pfile_in_zip_read_info->stream.avail_out) &&
2250                             (pfile_in_zip_read_info->rest_read_compressed == 0))
2251                             flush = Z_FINISH;
2252                          */
2253                         err = inflate( &pfile_in_zip_read_info->stream,flush );
2254
2255                         uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
2256                         uOutThis = uTotalOutAfter - uTotalOutBefore;
2257
2258                         pfile_in_zip_read_info->crc32 =
2259                                 crc32( pfile_in_zip_read_info->crc32,bufBefore,
2260                                            (uInt)( uOutThis ) );
2261
2262                         pfile_in_zip_read_info->rest_read_uncompressed -=
2263                                 uOutThis;
2264
2265                         iRead += (uInt)( uTotalOutAfter - uTotalOutBefore );
2266
2267                         if ( err == Z_STREAM_END ) {
2268                                 return ( iRead == 0 ) ? UNZ_EOF : iRead;
2269                         }
2270                         if ( err != Z_OK ) {
2271                                 break;
2272                         }
2273                 }
2274         }
2275
2276         if ( err == Z_OK ) {
2277                 return iRead;
2278         }
2279         return err;
2280 }
2281
2282
2283 /*
2284    Give the current position in uncompressed data
2285  */
2286 extern long unztell( unzFile file ){
2287         unz_s* s;
2288         file_in_zip_read_info_s* pfile_in_zip_read_info;
2289         if ( file == NULL ) {
2290                 return UNZ_PARAMERROR;
2291         }
2292         s = (unz_s*)file;
2293         pfile_in_zip_read_info = s->pfile_in_zip_read;
2294
2295         if ( pfile_in_zip_read_info == NULL ) {
2296                 return UNZ_PARAMERROR;
2297         }
2298
2299         return (long)pfile_in_zip_read_info->stream.total_out;
2300 }
2301
2302
2303 /*
2304    return 1 if the end of file was reached, 0 elsewhere
2305  */
2306 extern int unzeof( unzFile file ){
2307         unz_s* s;
2308         file_in_zip_read_info_s* pfile_in_zip_read_info;
2309         if ( file == NULL ) {
2310                 return UNZ_PARAMERROR;
2311         }
2312         s = (unz_s*)file;
2313         pfile_in_zip_read_info = s->pfile_in_zip_read;
2314
2315         if ( pfile_in_zip_read_info == NULL ) {
2316                 return UNZ_PARAMERROR;
2317         }
2318
2319         if ( pfile_in_zip_read_info->rest_read_uncompressed == 0 ) {
2320                 return 1;
2321         }
2322         else{
2323                 return 0;
2324         }
2325 }
2326
2327
2328
2329 /*
2330    Read extra field from the current file (opened by unzOpenCurrentFile)
2331    This is the static-header version of the extra field (sometimes, there is
2332     more info in the static-header version than in the central-header)
2333
2334    if buf==NULL, it return the size of the static extra field that can be read
2335
2336    if buf!=NULL, len is the size of the buffer, the extra header is copied in
2337     buf.
2338    the return value is the number of bytes copied in buf, or (if <0)
2339     the error code
2340  */
2341 extern int unzGetLocalExtrafield( unzFile file,void *buf,unsigned len ){
2342         unz_s* s;
2343         file_in_zip_read_info_s* pfile_in_zip_read_info;
2344         uInt read_now;
2345         uLong size_to_read;
2346
2347         if ( file == NULL ) {
2348                 return UNZ_PARAMERROR;
2349         }
2350         s = (unz_s*)file;
2351         pfile_in_zip_read_info = s->pfile_in_zip_read;
2352
2353         if ( pfile_in_zip_read_info == NULL ) {
2354                 return UNZ_PARAMERROR;
2355         }
2356
2357         size_to_read = ( pfile_in_zip_read_info->size_local_extrafield -
2358                                          pfile_in_zip_read_info->pos_local_extrafield );
2359
2360         if ( buf == NULL ) {
2361                 return (int)size_to_read;
2362         }
2363
2364         if ( len > size_to_read ) {
2365                 read_now = (uInt)size_to_read;
2366         }
2367         else{
2368                 read_now = (uInt)len ;
2369         }
2370
2371         if ( read_now == 0 ) {
2372                 return 0;
2373         }
2374
2375         if ( fseek( pfile_in_zip_read_info->file,
2376                                 pfile_in_zip_read_info->offset_local_extrafield +
2377                                 pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET ) != 0 ) {
2378                 return UNZ_ERRNO;
2379         }
2380
2381         if ( fread( buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file ) != 1 ) {
2382                 return UNZ_ERRNO;
2383         }
2384
2385         return (int)read_now;
2386 }
2387
2388 /*
2389    Close the file in zip opened with unzipOpenCurrentFile
2390    Return UNZ_CRCERROR if all the file was read but the CRC is not good
2391  */
2392 extern int unzCloseCurrentFile( unzFile file ){
2393         int err = UNZ_OK;
2394
2395         unz_s* s;
2396         file_in_zip_read_info_s* pfile_in_zip_read_info;
2397         if ( file == NULL ) {
2398                 return UNZ_PARAMERROR;
2399         }
2400         s = (unz_s*)file;
2401         pfile_in_zip_read_info = s->pfile_in_zip_read;
2402
2403         if ( pfile_in_zip_read_info == NULL ) {
2404                 return UNZ_PARAMERROR;
2405         }
2406
2407
2408         if ( pfile_in_zip_read_info->rest_read_uncompressed == 0 ) {
2409                 if ( pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait ) {
2410                         err = UNZ_CRCERROR;
2411                 }
2412         }
2413
2414
2415         free( pfile_in_zip_read_info->read_buffer );
2416         pfile_in_zip_read_info->read_buffer = NULL;
2417         if ( pfile_in_zip_read_info->stream_initialised ) {
2418                 inflateEnd( &pfile_in_zip_read_info->stream );
2419         }
2420
2421         pfile_in_zip_read_info->stream_initialised = 0;
2422         free( pfile_in_zip_read_info );
2423
2424         s->pfile_in_zip_read = NULL;
2425
2426         return err;
2427 }
2428
2429
2430 /*
2431    Get the global comment string of the ZipFile, in the szComment buffer.
2432    uSizeBuf is the size of the szComment buffer.
2433    return the number of byte copied or an error code <0
2434  */
2435 extern int unzGetGlobalComment( unzFile file, char *szComment, uLong uSizeBuf ){
2436         unz_s* s;
2437         uLong uReadThis ;
2438         if ( file == NULL ) {
2439                 return UNZ_PARAMERROR;
2440         }
2441         s = (unz_s*)file;
2442
2443         uReadThis = uSizeBuf;
2444         if ( uReadThis > s->gi.size_comment ) {
2445                 uReadThis = s->gi.size_comment;
2446         }
2447
2448         if ( fseek( s->file,s->central_pos + 22,SEEK_SET ) != 0 ) {
2449                 return UNZ_ERRNO;
2450         }
2451
2452         if ( uReadThis > 0 ) {
2453                 *szComment = '\0';
2454                 if ( fread( szComment,(uInt)uReadThis,1,s->file ) != 1 ) {
2455                         return UNZ_ERRNO;
2456                 }
2457         }
2458
2459         if ( ( szComment != NULL ) && ( uSizeBuf > s->gi.size_comment ) ) {
2460                 *( szComment + s->gi.size_comment ) = '\0';
2461         }
2462         return (int)uReadThis;
2463 }
2464
2465 /* crc32.c -- compute the CRC-32 of a data stream
2466  * Copyright (C) 1995-1998 Mark Adler
2467  * For conditions of distribution and use, see copyright notice in zlib.h
2468  */
2469
2470
2471 #ifdef DYNAMIC_CRC_TABLE
2472
2473 static int crc_table_empty = 1;
2474 static uLong crc_table[256];
2475 static void make_crc_table OF( (void) );
2476
2477 /*
2478    Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
2479    x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
2480
2481    Polynomials over GF(2) are represented in binary, one bit per coefficient,
2482    with the lowest powers in the most significant bit.  Then adding polynomials
2483    is just exclusive-or, and multiplying a polynomial by x is a right shift by
2484    one.  If we call the above polynomial p, and represent a byte as the
2485    polynomial q, also with the lowest power in the most significant bit (so the
2486    byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
2487    where a mod b means the remainder after dividing a by b.
2488
2489    This calculation is done using the shift-register method of multiplying and
2490    taking the remainder.  The register is initialized to zero, and for each
2491    incoming bit, x^32 is added mod p to the register if the bit is a one (where
2492    x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
2493    x (which is shifting right by one and adding x^32 mod p if the bit shifted
2494    out is a one).  We start with the highest power (least significant bit) of
2495    q and repeat for all eight bits of q.
2496
2497    The table is simply the CRC of all possible eight bit values.  This is all
2498    the information needed to generate CRC's on data a byte at a time for all
2499    combinations of CRC register values and incoming bytes.
2500  */
2501 static void make_crc_table(){
2502         uLong c;
2503         int n, k;
2504         uLong poly;          /* polynomial exclusive-or pattern */
2505         /* terms of polynomial defining this crc (except x^32): */
2506         static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
2507
2508         /* make exclusive-or pattern from polynomial (0xedb88320L) */
2509         poly = 0L;
2510         for ( n = 0; n < sizeof( p ) / sizeof( Byte ); n++ )
2511                 poly |= 1L << ( 31 - p[n] );
2512
2513         for ( n = 0; n < 256; n++ )
2514         {
2515                 c = (uLong)n;
2516                 for ( k = 0; k < 8; k++ )
2517                         c = c & 1 ? poly ^ ( c >> 1 ) : c >> 1;
2518                 crc_table[n] = c;
2519         }
2520         crc_table_empty = 0;
2521 }
2522 #else
2523 /* ========================================================================
2524  * Table of CRC-32's of all single-byte values (made by make_crc_table)
2525  */
2526 static const uLong crc_table[256] = {
2527         0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
2528         0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
2529         0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
2530         0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
2531         0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
2532         0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
2533         0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
2534         0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
2535         0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
2536         0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
2537         0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
2538         0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
2539         0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
2540         0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
2541         0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
2542         0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
2543         0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
2544         0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
2545         0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
2546         0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
2547         0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
2548         0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
2549         0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
2550         0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
2551         0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
2552         0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
2553         0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
2554         0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
2555         0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
2556         0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
2557         0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
2558         0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
2559         0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
2560         0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
2561         0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
2562         0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
2563         0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
2564         0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
2565         0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
2566         0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
2567         0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
2568         0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
2569         0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
2570         0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
2571         0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
2572         0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
2573         0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
2574         0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
2575         0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
2576         0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
2577         0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
2578         0x2d02ef8dL
2579 };
2580 #endif
2581
2582 /* =========================================================================
2583  * This function can be used by asm versions of crc32()
2584  */
2585 #ifndef __APPLE__
2586 const uLong * get_crc_table(){
2587 #ifdef DYNAMIC_CRC_TABLE
2588         if ( crc_table_empty ) {
2589                 make_crc_table();
2590         }
2591 #endif
2592         return (const uLong *)crc_table;
2593 }
2594 #endif
2595
2596 /* ========================================================================= */
2597 #define DO1( buf ) crc = crc_table[( (int)crc ^ ( *buf++ ) ) & 0xff] ^ ( crc >> 8 );
2598 #define DO2( buf )  DO1( buf ); DO1( buf );
2599 #define DO4( buf )  DO2( buf ); DO2( buf );
2600 #define DO8( buf )  DO4( buf ); DO4( buf );
2601
2602 /* ========================================================================= */
2603 #ifndef __APPLE__
2604 uLong crc32( uLong crc, const Byte *buf, uInt len ){
2605         if ( buf == Z_NULL ) {
2606                 return 0L;
2607         }
2608 #ifdef DYNAMIC_CRC_TABLE
2609         if ( crc_table_empty ) {
2610                 make_crc_table();
2611         }
2612 #endif
2613         crc = crc ^ 0xffffffffL;
2614         while ( len >= 8 )
2615         {
2616                 DO8( buf );
2617                 len -= 8;
2618         }
2619         if ( len ) {
2620                 do {
2621                         DO1( buf );
2622                 } while ( --len );
2623         }
2624         return crc ^ 0xffffffffL;
2625 }
2626 #endif
2627
2628 /* infblock.h -- header to use infblock.c
2629  * Copyright (C) 1995-1998 Mark Adler
2630  * For conditions of distribution and use, see copyright notice in zlib.h
2631  */
2632
2633 /* WARNING: this file should *not* be used by applications. It is
2634    part of the implementation of the compression library and is
2635    subject to change. Applications should only use zlib.h.
2636  */
2637
2638 struct inflate_blocks_state;
2639 typedef struct inflate_blocks_state inflate_blocks_statef;
2640
2641 extern inflate_blocks_statef * inflate_blocks_new OF( (
2642                                                                                                                   z_streamp z,
2643                                                                                                                   check_func c, /* check function */
2644                                                                                                                   uInt w ) ); /* window size */
2645
2646 extern int inflate_blocks OF( (
2647                                                                   inflate_blocks_statef *,
2648                                                                   z_streamp,
2649                                                                   int ) ); /* initial return code */
2650
2651 extern void inflate_blocks_reset OF( (
2652                                                                                  inflate_blocks_statef *,
2653                                                                                  z_streamp,
2654                                                                                  uLong * ) ); /* check value on output */
2655
2656 extern int inflate_blocks_free OF( (
2657                                                                            inflate_blocks_statef *,
2658                                                                            z_streamp ) );
2659
2660 extern void inflate_set_dictionary OF( (
2661                                                                                    inflate_blocks_statef * s,
2662                                                                                    const Byte * d, /* dictionary */
2663                                                                                    uInt n ) ); /* dictionary length */
2664
2665 extern int inflate_blocks_sync_point OF( (
2666                                                                                          inflate_blocks_statef * s ) );
2667
2668 /* simplify the use of the inflate_huft type with some defines */
2669 #define exop word.what.Exop
2670 #define bits word.what.Bits
2671
2672 /* Table for deflate from PKZIP's appnote.txt. */
2673 static const uInt border[] = { /* Order of the bit length code lengths */
2674         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
2675 };
2676
2677 /* inftrees.h -- header to use inftrees.c
2678  * Copyright (C) 1995-1998 Mark Adler
2679  * For conditions of distribution and use, see copyright notice in zlib.h
2680  */
2681
2682 /* WARNING: this file should *not* be used by applications. It is
2683    part of the implementation of the compression library and is
2684    subject to change. Applications should only use zlib.h.
2685  */
2686
2687 /* Huffman code lookup table entry--this entry is four bytes for machines
2688    that have 16-bit pointers (e.g. PC's in the small or medium model). */
2689
2690 typedef struct inflate_huft_s inflate_huft;
2691
2692 struct inflate_huft_s {
2693         union {
2694                 struct {
2695                         Byte Exop;  /* number of extra bits or operation */
2696                         Byte Bits;  /* number of bits in this code or subcode */
2697                 } what;
2698                 uInt pad;       /* pad structure to a power of 2 (4 bytes for */
2699         } word;             /*  16-bit, 8 bytes for 32-bit int's) */
2700         uInt base;          /* literal, length base, distance base,
2701                                or table offset */
2702 };
2703
2704 /* Maximum size of dynamic tree.  The maximum found in a long but non-
2705    exhaustive search was 1004 huft structures (850 for length/literals
2706    and 154 for distances, the latter actually the result of an
2707    exhaustive search).  The actual maximum is not known, but the
2708    value below is more than safe. */
2709 #define MANY 1440
2710
2711 extern int inflate_trees_bits OF( (
2712                                                                           uInt *, /* 19 code lengths */
2713                                                                           uInt *, /* bits tree desired/actual depth */
2714                                                                           inflate_huft * *, /* bits tree result */
2715                                                                           inflate_huft *, /* space for trees */
2716                                                                           z_streamp ) ); /* for messages */
2717
2718 extern int inflate_trees_dynamic OF( (
2719                                                                                  uInt, /* number of literal/length codes */
2720                                                                                  uInt, /* number of distance codes */
2721                                                                                  uInt *, /* that many (total) code lengths */
2722                                                                                  uInt *, /* literal desired/actual bit depth */
2723                                                                                  uInt *, /* distance desired/actual bit depth */
2724                                                                                  inflate_huft * *, /* literal/length tree result */
2725                                                                                  inflate_huft * *, /* distance tree result */
2726                                                                                  inflate_huft *, /* space for trees */
2727                                                                                  z_streamp ) ); /* for messages */
2728
2729 extern int inflate_trees_fixed OF( (
2730                                                                            uInt *, /* literal desired/actual bit depth */
2731                                                                            uInt *, /* distance desired/actual bit depth */
2732                                                                            inflate_huft * *, /* literal/length tree result */
2733                                                                            inflate_huft * *, /* distance tree result */
2734                                                                            z_streamp ) ); /* for memory allocation */
2735
2736
2737 /* infcodes.h -- header to use infcodes.c
2738  * Copyright (C) 1995-1998 Mark Adler
2739  * For conditions of distribution and use, see copyright notice in zlib.h
2740  */
2741
2742 /* WARNING: this file should *not* be used by applications. It is
2743    part of the implementation of the compression library and is
2744    subject to change. Applications should only use zlib.h.
2745  */
2746
2747 struct inflate_codes_state;
2748 typedef struct inflate_codes_state inflate_codes_statef;
2749
2750 extern inflate_codes_statef *inflate_codes_new OF( (
2751                                                                                                            uInt, uInt,
2752                                                                                                            inflate_huft *, inflate_huft *,
2753                                                                                                            z_streamp ) );
2754
2755 extern int inflate_codes OF( (
2756                                                                  inflate_blocks_statef *,
2757                                                                  z_streamp,
2758                                                                  int ) );
2759
2760 extern void inflate_codes_free OF( (
2761                                                                            inflate_codes_statef *,
2762                                                                            z_streamp ) );
2763
2764 /* infutil.h -- types and macros common to blocks and codes
2765  * Copyright (C) 1995-1998 Mark Adler
2766  * For conditions of distribution and use, see copyright notice in zlib.h
2767  */
2768
2769 /* WARNING: this file should *not* be used by applications. It is
2770    part of the implementation of the compression library and is
2771    subject to change. Applications should only use zlib.h.
2772  */
2773
2774 #ifndef _INFUTIL_H
2775 #define _INFUTIL_H
2776
2777 typedef enum {
2778         TYPE,       /* get type bits (3, including end bit) */
2779         LENS,       /* get lengths for stored */
2780         STORED,     /* processing stored block */
2781         TABLE,      /* get table lengths */
2782         BTREE,      /* get bit lengths tree for a dynamic block */
2783         DTREE,      /* get length, distance trees for a dynamic block */
2784         CODES,      /* processing fixed or dynamic block */
2785         DRY,        /* output remaining window bytes */
2786         DONE,       /* finished last block, done */
2787         BAD
2788 }               /* got a data error--stuck here */
2789 inflate_block_mode;
2790
2791 /* inflate blocks semi-private state */
2792 struct inflate_blocks_state {
2793
2794         /* mode */
2795         inflate_block_mode mode;    /* current inflate_block mode */
2796
2797         /* mode dependent information */
2798         union {
2799                 uInt left;      /* if STORED, bytes left to copy */
2800                 struct {
2801                         uInt table;         /* table lengths (14 bits) */
2802                         uInt index;         /* index into blens (or border) */
2803                         uInt *blens;       /* bit lengths of codes */
2804                         uInt bb;            /* bit length tree depth */
2805                         inflate_huft *tb;   /* bit length decoding tree */
2806                 } trees;        /* if DTREE, decoding info for trees */
2807                 struct {
2808                         inflate_codes_statef
2809                         *codes;
2810                 } decode;       /* if CODES, current state */
2811         } sub;              /* submode */
2812         uInt last;          /* true if this block is the last block */
2813
2814         /* mode independent information */
2815         uInt bitk;          /* bits in bit buffer */
2816         uLong bitb;         /* bit buffer */
2817         inflate_huft *hufts; /* single safe_malloc for tree space */
2818         Byte *window;      /* sliding window */
2819         Byte *end;         /* one byte after sliding window */
2820         Byte *read;        /* window read pointer */
2821         Byte *write;       /* window write pointer */
2822         check_func checkfn; /* check function */
2823         uLong check;        /* check on output */
2824
2825 };
2826
2827
2828 /* defines for inflate input/output */
2829 /*   update pointers and return */
2830 #define UPDBITS {s->bitb = b; s->bitk = k; }
2831 #define UPDIN {z->avail_in = n; z->total_in += p - z->next_in; z->next_in = p; }
2832 #define UPDOUT {s->write = q; }
2833 #define UPDATE {UPDBITS UPDIN UPDOUT}
2834 #define LEAVE {UPDATE return inflate_flush( s,z,r ); }
2835 /*   get bytes and bits */
2836 #define LOADIN {p = z->next_in; n = z->avail_in; b = s->bitb; k = s->bitk; }
2837 #define NEEDBYTE {if ( n ) {r = Z_OK; }else LEAVE}
2838 #define NEXTBYTE ( n--,*p++ )
2839 #define NEEDBITS( j ) {while ( k < ( j ) ) {NEEDBYTE; b |= ( (uLong)NEXTBYTE ) << k; k += 8; }}
2840 #define DUMPBITS( j ) {b >>= ( j ); k -= ( j ); }
2841 /*   output bytes */
2842 #define WAVAIL (uInt)( q < s->read ? s->read - q - 1 : s->end - q )
2843 #define LOADOUT {q = s->write; m = (uInt)WAVAIL; }
2844 #define WRAP {if ( q == s->end && s->read != s->window ) {q = s->window; m = (uInt)WAVAIL; }}
2845 #define FLUSH {UPDOUT r = inflate_flush( s,z,r ); LOADOUT}
2846 #define NEEDOUT {if ( m == 0 ) {WRAP if ( m == 0 ) {FLUSH WRAP if ( m == 0 ) {LEAVE}} r = Z_OK; }}
2847 #define OUTBYTE( a ) {*q++ = (Byte)( a ); m--; }
2848 /*   load static pointers */
2849 #define LOAD {LOADIN LOADOUT}
2850
2851 /* masks for lower bits (size given to avoid silly warnings with Visual C++) */
2852 extern uInt inflate_mask[17];
2853
2854 /* copy as much as possible from the sliding window to the output area */
2855 extern int inflate_flush OF( (
2856                                                                  inflate_blocks_statef *,
2857                                                                  z_streamp,
2858                                                                  int ) );
2859
2860 #endif
2861
2862
2863 /*
2864    Notes beyond the 1.93a appnote.txt:
2865
2866    1. Distance pointers never point before the beginning of the output
2867       stream.
2868    2. Distance pointers can point back across blocks, up to 32k away.
2869    3. There is an implied maximum of 7 bits for the bit length table and
2870       15 bits for the actual data.
2871    4. If only one code exists, then it is encoded using one bit.  (Zero
2872       would be more efficient, but perhaps a little confusing.)  If two
2873       codes exist, they are coded using one bit each (0 and 1).
2874    5. There is no way of sending zero distance codes--a dummy must be
2875       sent if there are none.  (History: a pre 2.0 version of PKZIP would
2876       store blocks with no distance codes, but this was discovered to be
2877       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
2878       zero distance codes, which is sent as one code of zero bits in
2879       length.
2880    6. There are up to 286 literal/length codes.  Code 256 represents the
2881       end-of-block.  Note however that the static length tree defines
2882       288 codes just to fill out the Huffman codes.  Codes 286 and 287
2883       cannot be used though, since there is no length base or extra bits
2884       defined for them.  Similarily, there are up to 30 distance codes.
2885       However, static trees define 32 codes (all 5 bits) to fill out the
2886       Huffman codes, but the last two had better not show up in the data.
2887    7. Unzip can check dynamic Huffman blocks for complete code sets.
2888       The exception is that a single code would not be complete (see #4).
2889    8. The five bits following the block type is really the number of
2890       literal codes sent minus 257.
2891    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
2892       (1+6+6).  Therefore, to output three times the length, you output
2893       three codes (1+1+1), whereas to output four times the same length,
2894       you only need two codes (1+3).  Hmm.
2895    10. In the tree reconstruction algorithm, Code = Code + Increment
2896       only if BitLength(i) is not zero.  (Pretty obvious.)
2897    11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
2898    12. Note: length code 284 can represent 227-258, but length code 285
2899       really is 258.  The last length deserves its own, short code
2900       since it gets used a lot in very redundant files.  The length
2901       258 is special since 258 - 3 (the min match length) is 255.
2902    13. The literal/length and distance code bit lengths are read as a
2903       single stream of lengths.  It is possible (and advantageous) for
2904       a repeat code (16, 17, or 18) to go across the boundary between
2905       the two sets of lengths.
2906  */
2907
2908
2909 #ifndef __APPLE__
2910 void inflate_blocks_reset( inflate_blocks_statef *s, z_streamp z, uLong *c ){
2911         if ( c != Z_NULL ) {
2912                 *c = s->check;
2913         }
2914         if ( s->mode == BTREE || s->mode == DTREE ) {
2915                 ZFREE( z, s->sub.trees.blens );
2916         }
2917         if ( s->mode == CODES ) {
2918                 inflate_codes_free( s->sub.decode.codes, z );
2919         }
2920         s->mode = TYPE;
2921         s->bitk = 0;
2922         s->bitb = 0;
2923         s->read = s->write = s->window;
2924         if ( s->checkfn != Z_NULL ) {
2925                 z->adler = s->check = ( *s->checkfn )( 0L, (const Byte *)Z_NULL, 0 );
2926         }
2927         Tracev( ( "inflate:   blocks reset\n" ) );
2928 }
2929 #endif
2930
2931 #ifndef __APPLE__
2932 inflate_blocks_statef *inflate_blocks_new( z_streamp z, check_func c, uInt w ){
2933         inflate_blocks_statef *s;
2934
2935         if ( ( s = (inflate_blocks_statef *)ZALLOC
2936                                    ( z,1,sizeof( struct inflate_blocks_state ) ) ) == Z_NULL ) {
2937                 return s;
2938         }
2939         if ( ( s->hufts =
2940                            (inflate_huft *)ZALLOC( z, sizeof( inflate_huft ), MANY ) ) == Z_NULL ) {
2941                 ZFREE( z, s );
2942                 return Z_NULL;
2943         }
2944         if ( ( s->window = (Byte *)ZALLOC( z, 1, w ) ) == Z_NULL ) {
2945                 ZFREE( z, s->hufts );
2946                 ZFREE( z, s );
2947                 return Z_NULL;
2948         }
2949         s->end = s->window + w;
2950         s->checkfn = c;
2951         s->mode = TYPE;
2952         Tracev( ( "inflate:   blocks allocated\n" ) );
2953         inflate_blocks_reset( s, z, Z_NULL );
2954         return s;
2955 }
2956 #endif
2957
2958 #ifndef __APPLE__
2959 int inflate_blocks( inflate_blocks_statef *s, z_streamp z, int r ){
2960         uInt t;             /* temporary storage */
2961         uLong b;            /* bit buffer */
2962         uInt k;             /* bits in bit buffer */
2963         Byte *p;           /* input data pointer */
2964         uInt n;             /* bytes available there */
2965         Byte *q;           /* output window write pointer */
2966         uInt m;             /* bytes to end of window or read pointer */
2967
2968         /* copy input/output information to locals (UPDATE macro restores) */
2969         LOAD
2970
2971         /* process input based on current state */
2972         while ( 1 ) switch ( s->mode )
2973                 {
2974                 case TYPE:
2975                         NEEDBITS( 3 )
2976                         t = (uInt)b & 7;
2977                         s->last = t & 1;
2978                         switch ( t >> 1 )
2979                         {
2980                         case 0:                     /* stored */
2981                                 Tracev( ( "inflate:     stored block%s\n",
2982                                                   s->last ? " (last)" : "" ) );
2983                                 DUMPBITS( 3 )
2984                                 t = k & 7;              /* go to byte boundary */
2985                                 DUMPBITS( t )
2986                                 s->mode = LENS;         /* get length of stored block */
2987                                 break;
2988                         case 1:                     /* fixed */
2989                                 Tracev( ( "inflate:     fixed codes block%s\n",
2990                                                   s->last ? " (last)" : "" ) );
2991                                 {
2992                                         uInt bl, bd;
2993                                         inflate_huft *tl, *td;
2994
2995                                         inflate_trees_fixed( &bl, &bd, &tl, &td, z );
2996                                         s->sub.decode.codes = inflate_codes_new( bl, bd, tl, td, z );
2997                                         if ( s->sub.decode.codes == Z_NULL ) {
2998                                                 r = Z_MEM_ERROR;
2999                                                 LEAVE
3000                                         }
3001                                 }
3002                                 DUMPBITS( 3 )
3003                                 s->mode = CODES;
3004                                 break;
3005                         case 2:                     /* dynamic */
3006                                 Tracev( ( "inflate:     dynamic codes block%s\n",
3007                                                   s->last ? " (last)" : "" ) );
3008                                 DUMPBITS( 3 )
3009                                 s->mode = TABLE;
3010                                 break;
3011                         case 3:                     /* illegal */
3012                                 DUMPBITS( 3 )
3013                                 s->mode = BAD;
3014                                 z->msg = (char*)"invalid block type";
3015                                 r = Z_DATA_ERROR;
3016                                 LEAVE
3017                         }
3018                         break;
3019                 case LENS:
3020                         NEEDBITS( 32 )
3021                         if ( ( ( ( ~b ) >> 16 ) & 0xffff ) != ( b & 0xffff ) ) {
3022                                 s->mode = BAD;
3023                                 z->msg = (char*)"invalid stored block lengths";
3024                                 r = Z_DATA_ERROR;
3025                                 LEAVE
3026                         }
3027                         s->sub.left = (uInt)b & 0xffff;
3028                         b = k = 0;                /* dump bits */
3029                         Tracev( ( "inflate:       stored length %u\n", s->sub.left ) );
3030                         s->mode = s->sub.left ? STORED : ( s->last ? DRY : TYPE );
3031                         break;
3032                 case STORED:
3033                         if ( n == 0 ) {
3034                                 LEAVE
3035                                 NEEDOUT
3036                                         t = s->sub.left;
3037                         }
3038                         if ( t > n ) {
3039                                 t = n;
3040                         }
3041                         if ( t > m ) {
3042                                 t = m;
3043                         }
3044                         zmemcpy( q, p, t );
3045                         p += t;  n -= t;
3046                         q += t;  m -= t;
3047                         if ( ( s->sub.left -= t ) != 0 ) {
3048                                 break;
3049                         }
3050                         Tracev( ( "inflate:       stored end, %lu total out\n",
3051                                           z->total_out + ( q >= s->read ? q - s->read :
3052                                                                            ( s->end - s->read ) + ( q - s->window ) ) ) );
3053                         s->mode = s->last ? DRY : TYPE;
3054                         break;
3055                 case TABLE:
3056                         NEEDBITS( 14 )
3057                         s->sub.trees.table = t = (uInt)b & 0x3fff;
3058 #ifndef PKZIP_BUG_WORKAROUND
3059                         if ( ( t & 0x1f ) > 29 || ( ( t >> 5 ) & 0x1f ) > 29 ) {
3060                                 s->mode = BAD;
3061                                 z->msg = (char*)"too many length or distance symbols";
3062                                 r = Z_DATA_ERROR;
3063                                 LEAVE
3064                         }
3065 #endif
3066                         t = 258 + ( t & 0x1f ) + ( ( t >> 5 ) & 0x1f );
3067                         if ( ( s->sub.trees.blens = (uInt*)ZALLOC( z, t, sizeof( uInt ) ) ) == Z_NULL ) {
3068                                 r = Z_MEM_ERROR;
3069                                 LEAVE
3070                         }
3071                         DUMPBITS( 14 )
3072                         s->sub.trees.index = 0;
3073                         Tracev( ( "inflate:       table sizes ok\n" ) );
3074                         s->mode = BTREE;
3075                 case BTREE:
3076                         while ( s->sub.trees.index < 4 + ( s->sub.trees.table >> 10 ) )
3077                         {
3078                                 NEEDBITS( 3 )
3079                                 s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
3080                                 DUMPBITS( 3 )
3081                         }
3082                         while ( s->sub.trees.index < 19 )
3083                                 s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
3084                         s->sub.trees.bb = 7;
3085                         t = inflate_trees_bits( s->sub.trees.blens, &s->sub.trees.bb,
3086                                                                         &s->sub.trees.tb, s->hufts, z );
3087                         if ( t != Z_OK ) {
3088                                 ZFREE( z, s->sub.trees.blens );
3089                                 r = t;
3090                                 if ( r == Z_DATA_ERROR ) {
3091                                         s->mode = BAD;
3092                                 }
3093                                 LEAVE
3094                         }
3095                         s->sub.trees.index = 0;
3096                         Tracev( ( "inflate:       bits tree ok\n" ) );
3097                         s->mode = DTREE;
3098                 case DTREE:
3099                         while ( t = s->sub.trees.table,
3100                                         s->sub.trees.index < 258 + ( t & 0x1f ) + ( ( t >> 5 ) & 0x1f ) )
3101                         {
3102                                 inflate_huft *h;
3103                                 uInt i, j, c;
3104
3105                                 t = s->sub.trees.bb;
3106                                 NEEDBITS( t )
3107                                 h = s->sub.trees.tb + ( (uInt)b & inflate_mask[t] );
3108                                 t = h->bits;
3109                                 c = h->base;
3110                                 if ( c < 16 ) {
3111                                         DUMPBITS( t )
3112                                         s->sub.trees.blens[s->sub.trees.index++] = c;
3113                                 }
3114                                 else /* c == 16..18 */
3115                                 {
3116                                         i = c == 18 ? 7 : c - 14;
3117                                         j = c == 18 ? 11 : 3;
3118                                         NEEDBITS( t + i )
3119                                         DUMPBITS( t )
3120                                         j += (uInt)b & inflate_mask[i];
3121                                         DUMPBITS( i )
3122                                         i = s->sub.trees.index;
3123                                         t = s->sub.trees.table;
3124                                         if ( i + j > 258 + ( t & 0x1f ) + ( ( t >> 5 ) & 0x1f ) ||
3125                                                  ( c == 16 && i < 1 ) ) {
3126                                                 ZFREE( z, s->sub.trees.blens );
3127                                                 s->mode = BAD;
3128                                                 z->msg = (char*)"invalid bit length repeat";
3129                                                 r = Z_DATA_ERROR;
3130                                                 LEAVE
3131                                         }
3132                                         c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
3133                                         do {
3134                                                 s->sub.trees.blens[i++] = c;
3135                                         } while ( --j );
3136                                         s->sub.trees.index = i;
3137                                 }
3138                         }
3139                         s->sub.trees.tb = Z_NULL;
3140                         {
3141                                 uInt bl, bd;
3142                                 inflate_huft *tl, *td;
3143                                 inflate_codes_statef *c;
3144
3145                                 bl = 9; /* must be <= 9 for lookahead assumptions */
3146                                 bd = 6; /* must be <= 9 for lookahead assumptions */
3147                                 t = s->sub.trees.table;
3148                                 t = inflate_trees_dynamic( 257 + ( t & 0x1f ), 1 + ( ( t >> 5 ) & 0x1f ),
3149                                                                                    s->sub.trees.blens, &bl, &bd, &tl, &td,
3150                                                                                    s->hufts, z );
3151                                 ZFREE( z, s->sub.trees.blens );
3152                                 if ( t != Z_OK ) {
3153                                         if ( t == (uInt)Z_DATA_ERROR ) {
3154                                                 s->mode = BAD;
3155                                         }
3156                                         r = t;
3157                                         LEAVE
3158                                 }
3159                                 Tracev( ( "inflate:       trees ok\n" ) );
3160                                 if ( ( c = inflate_codes_new( bl, bd, tl, td, z ) ) == Z_NULL ) {
3161                                         r = Z_MEM_ERROR;
3162                                         LEAVE
3163                                 }
3164                                 s->sub.decode.codes = c;
3165                         }
3166                         s->mode = CODES;
3167                 case CODES:
3168                         UPDATE
3169                         if ( ( r = inflate_codes( s, z, r ) ) != Z_STREAM_END ) {
3170                                 return inflate_flush( s, z, r );
3171                         }
3172                         r = Z_OK;
3173                         inflate_codes_free( s->sub.decode.codes, z );
3174                         LOAD
3175                         Tracev( ( "inflate:       codes end, %lu total out\n",
3176                                           z->total_out + ( q >= s->read ? q - s->read :
3177                                                                            ( s->end - s->read ) + ( q - s->window ) ) ) );
3178                         if ( !s->last ) {
3179                                 s->mode = TYPE;
3180                                 break;
3181                         }
3182                         s->mode = DRY;
3183                 case DRY:
3184                         FLUSH
3185                         if ( s->read != s->write ) {
3186                                 LEAVE
3187                                 s->mode = DONE;
3188                         }
3189                 case DONE:
3190                         r = Z_STREAM_END;
3191                         LEAVE
3192                 case BAD:
3193                         r = Z_DATA_ERROR;
3194                         LEAVE
3195                 default:
3196                         r = Z_STREAM_ERROR;
3197                         LEAVE
3198                 }
3199 }
3200 #endif
3201
3202 #ifndef __APPLE__
3203 int inflate_blocks_free( inflate_blocks_statef *s, z_streamp z ){
3204         inflate_blocks_reset( s, z, Z_NULL );
3205         ZFREE( z, s->window );
3206         ZFREE( z, s->hufts );
3207         ZFREE( z, s );
3208         Tracev( ( "inflate:   blocks freed\n" ) );
3209         return Z_OK;
3210 }
3211 #endif
3212
3213 #ifndef __APPLE__
3214 void inflate_set_dictionary( inflate_blocks_statef *s, const Byte *d, uInt n ){
3215         zmemcpy( s->window, d, n );
3216         s->read = s->write = s->window + n;
3217 }
3218 #endif
3219
3220 /* Returns true if inflate is currently at the end of a block generated
3221  * by Z_SYNC_FLUSH or Z_FULL_FLUSH.
3222  * IN assertion: s != Z_NULL
3223  */
3224 #ifndef __APPLE__
3225 int inflate_blocks_sync_point( inflate_blocks_statef *s ){
3226         return s->mode == LENS;
3227 }
3228 #endif
3229
3230 /* And'ing with mask[n] masks the lower n bits */
3231 uInt inflate_mask[17] = {
3232         0x0000,
3233         0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
3234         0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
3235 };
3236
3237 /* copy as much as possible from the sliding window to the output area */
3238 #ifndef __APPLE__
3239 int inflate_flush( inflate_blocks_statef *s, z_streamp z, int r ){
3240         uInt n;
3241         Byte *p;
3242         Byte *q;
3243
3244         /* static copies of source and destination pointers */
3245         p = z->next_out;
3246         q = s->read;
3247
3248         /* compute number of bytes to copy as as end of window */
3249         n = (uInt)( ( q <= s->write ? s->write : s->end ) - q );
3250         if ( n > z->avail_out ) {
3251                 n = z->avail_out;
3252         }
3253         if ( n && r == Z_BUF_ERROR ) {
3254                 r = Z_OK;
3255         }
3256
3257         /* update counters */
3258         z->avail_out -= n;
3259         z->total_out += n;
3260
3261         /* update check information */
3262         if ( s->checkfn != Z_NULL ) {
3263                 z->adler = s->check = ( *s->checkfn )( s->check, q, n );
3264         }
3265
3266         /* copy as as end of window */
3267         zmemcpy( p, q, n );
3268         p += n;
3269         q += n;
3270
3271         /* see if more to copy at beginning of window */
3272         if ( q == s->end ) {
3273                 /* wrap pointers */
3274                 q = s->window;
3275                 if ( s->write == s->end ) {
3276                         s->write = s->window;
3277                 }
3278
3279                 /* compute bytes to copy */
3280                 n = (uInt)( s->write - q );
3281                 if ( n > z->avail_out ) {
3282                         n = z->avail_out;
3283                 }
3284                 if ( n && r == Z_BUF_ERROR ) {
3285                         r = Z_OK;
3286                 }
3287
3288                 /* update counters */
3289                 z->avail_out -= n;
3290                 z->total_out += n;
3291
3292                 /* update check information */
3293                 if ( s->checkfn != Z_NULL ) {
3294                         z->adler = s->check = ( *s->checkfn )( s->check, q, n );
3295                 }
3296
3297                 /* copy */
3298                 zmemcpy( p, q, n );
3299                 p += n;
3300                 q += n;
3301         }
3302
3303         /* update pointers */
3304         z->next_out = p;
3305         s->read = q;
3306
3307         /* done */
3308         return r;
3309 }
3310 #endif
3311
3312 /* inftrees.c -- generate Huffman trees for efficient decoding
3313  * Copyright (C) 1995-1998 Mark Adler
3314  * For conditions of distribution and use, see copyright notice in zlib.h
3315  */
3316
3317 #ifndef __APPLE__
3318 const char inflate_copyright[] =
3319         " inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
3320 #endif
3321
3322 /*
3323    If you use the zlib library in a product, an acknowledgment is welcome
3324    in the documentation of your product. If for some reason you cannot
3325    include such an acknowledgment, I would appreciate that you keep this
3326    copyright string in the executable of your product.
3327  */
3328
3329 /* simplify the use of the inflate_huft type with some defines */
3330 #define exop word.what.Exop
3331 #define bits word.what.Bits
3332
3333
3334 static int huft_build OF( (
3335                                                           uInt *, /* code lengths in bits */
3336                                                           uInt, /* number of codes */
3337                                                           uInt, /* number of "simple" codes */
3338                                                           const uInt *, /* list of base values for non-simple codes */
3339                                                           const uInt *, /* list of extra bits for non-simple codes */
3340                                                           inflate_huft * *, /* result: starting table */
3341                                                           uInt *, /* maximum lookup bits (returns actual) */
3342                                                           inflate_huft *, /* space for trees */
3343                                                           uInt *, /* hufts used in space */
3344                                                           uInt * ) ); /* space for values */
3345
3346 /* Tables for deflate from PKZIP's appnote.txt. */
3347 static const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
3348         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
3349         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
3350 };
3351 /* see note #13 above about 258 */
3352 static const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
3353         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3354         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112
3355 };                                                        /* 112==invalid */
3356 static const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
3357         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
3358         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
3359         8193, 12289, 16385, 24577
3360 };
3361 static const uInt cpdext[30] = { /* Extra bits for distance codes */
3362         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
3363         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
3364         12, 12, 13, 13
3365 };
3366
3367 /*
3368    Huffman code decoding is performed using a multi-level table lookup.
3369    The fastest way to decode is to simply build a lookup table whose
3370    size is determined by the longest code.  However, the time it takes
3371    to build this table can also be a factor if the data being decoded
3372    is not very long.  The most common codes are necessarily the
3373    shortest codes, so those codes dominate the decoding time, and hence
3374    the speed.  The idea is you can have a shorter table that decodes the
3375    shorter, more probable codes, and then point to subsidiary tables for
3376    the longer codes.  The time it costs to decode the longer codes is
3377    then traded against the time it takes to make longer tables.
3378
3379    This results of this trade are in the variables lbits and dbits
3380    below.  lbits is the number of bits the first level table for literal/
3381    length codes can decode in one step, and dbits is the same thing for
3382    the distance codes.  Subsequent tables are also less than or equal to
3383    those sizes.  These values may be adjusted either when all of the
3384    codes are shorter than that, in which case the longest code length in
3385    bits is used, or when the shortest code is *longer* than the requested
3386    table size, in which case the length of the shortest code in bits is
3387    used.
3388
3389    There are two different values for the two tables, since they code a
3390    different number of possibilities each.  The literal/length table
3391    codes 286 possible values, or in a flat code, a little over eight
3392    bits.  The distance table codes 30 possible values, or a little less
3393    than five bits, flat.  The optimum values for speed end up being
3394    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
3395    The optimum values may differ though from machine to machine, and
3396    possibly even between compilers.  Your mileage may vary.
3397  */
3398
3399
3400 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
3401 #define BMAX 15         /* maximum bit length of any code */
3402
3403 static int huft_build( uInt *b, uInt n, uInt s, const uInt *d, const uInt *e, inflate_huft ** t, uInt *m, inflate_huft *hp, uInt *hn, uInt *v ){
3404 //uInt *b;               /* code lengths in bits (all assumed <= BMAX) */
3405 //uInt n;                 /* number of codes (assumed <= 288) */
3406 //uInt s;                 /* number of simple-valued codes (0..s-1) */
3407 //const uInt *d;         /* list of base values for non-simple codes */
3408 //const uInt *e;         /* list of extra bits for non-simple codes */
3409 //inflate_huft ** t;            /* result: starting table */
3410 //uInt *m;               /* maximum lookup bits, returns actual */
3411 //inflate_huft *hp;       /* space for trees */
3412 //uInt *hn;               /* hufts used in space */
3413 //uInt *v;               /* working area: values in order of bit length */
3414 /* Given a list of code lengths and a maximum table size, make a set of
3415    tables to decode that set of codes.  Return Z_OK on success, Z_BUF_ERROR
3416    if the given code set is incomplete (the tables are still built in this
3417    case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
3418    lengths), or Z_MEM_ERROR if not enough memory. */
3419
3420         uInt a;                     /* counter for codes of length k */
3421         uInt c[BMAX + 1];           /* bit length count table */
3422         uInt f;                     /* i repeats in table every f entries */
3423         int g;                      /* maximum code length */
3424         int h;                      /* table level */
3425         register uInt i;            /* counter, current code */
3426         register uInt j;            /* counter */
3427         register int k;             /* number of bits in current code */
3428         int l;                      /* bits per table (returned in m) */
3429         uInt mask;                  /* (1 << w) - 1, to avoid cc -O bug on HP */
3430         register uInt *p;          /* pointer into c[], b[], or v[] */
3431         inflate_huft *q;            /* points to current table */
3432         struct inflate_huft_s r;    /* table entry for structure assignment */
3433         inflate_huft *u[BMAX];      /* table stack */
3434         register int w;             /* bits before this table == (l * h) */
3435         uInt x[BMAX + 1];           /* bit offsets, then code stack */
3436         uInt *xp;                  /* pointer into x */
3437         int y;                      /* number of dummy codes added */
3438         uInt z;                     /* number of entries in current table */
3439
3440
3441         /* Generate counts for each bit length */
3442         p = c;
3443 #define C0 *p++ = 0;
3444 #define C2 C0 C0 C0 C0
3445 #define C4 C2 C2 C2 C2
3446         C4                          /* clear c[]--assume BMAX+1 is 16 */
3447                 p = b;  i = n;
3448         do {
3449                 c[*p++]++;              /* assume all entries <= BMAX */
3450         } while ( --i );
3451         if ( c[0] == n ) {          /* null input--all zero length codes */
3452                 *t = (inflate_huft *)Z_NULL;
3453                 *m = 0;
3454                 return Z_OK;
3455         }
3456
3457
3458         /* Find minimum and maximum length, bound *m by those */
3459         l = *m;
3460         for ( j = 1; j <= BMAX; j++ )
3461                 if ( c[j] ) {
3462                         break;
3463                 }
3464         k = j;                      /* minimum code length */
3465         if ( (uInt)l < j ) {
3466                 l = j;
3467         }
3468         for ( i = BMAX; i; i-- )
3469                 if ( c[i] ) {
3470                         break;
3471                 }
3472         g = i;                      /* maximum code length */
3473         if ( (uInt)l > i ) {
3474                 l = i;
3475         }
3476         *m = l;
3477
3478
3479         /* Adjust last length count to fill out codes, if needed */
3480         for ( y = 1 << j; j < i; j++, y <<= 1 )
3481                 if ( ( y -= c[j] ) < 0 ) {
3482                         return Z_DATA_ERROR;
3483                 }
3484         if ( ( y -= c[i] ) < 0 ) {
3485                 return Z_DATA_ERROR;
3486         }
3487         c[i] += y;
3488
3489
3490         /* Generate starting offsets into the value table for each length */
3491         x[1] = j = 0;
3492         p = c + 1;  xp = x + 2;
3493         while ( --i ) {             /* note that i == g from above */
3494                 *xp++ = ( j += *p++ );
3495         }
3496
3497
3498         /* Make a table of values in order of bit lengths */
3499         p = b;  i = 0;
3500         do {
3501                 if ( ( j = *p++ ) != 0 ) {
3502                         v[x[j]++] = i;
3503                 }
3504         } while ( ++i < n );
3505         n = x[g];                   /* set n to length of v */
3506
3507
3508         /* Generate the Huffman codes and for each, make the table entries */
3509         x[0] = i = 0;               /* first Huffman code is zero */
3510         p = v;                      /* grab values in bit order */
3511         h = -1;                     /* no tables yet--level -1 */
3512         w = -l;                     /* bits decoded == (l * h) */
3513         u[0] = (inflate_huft *)Z_NULL;      /* just to keep compilers happy */
3514         q = (inflate_huft *)Z_NULL; /* ditto */
3515         z = 0;                      /* ditto */
3516
3517         /* go through the bit lengths (k already is bits in shortest code) */
3518         for (; k <= g; k++ )
3519         {
3520                 a = c[k];
3521                 while ( a-- )
3522                 {
3523                         /* here i is the Huffman code of length k bits for value *p */
3524                         /* make tables up to required level */
3525                         while ( k > w + l )
3526                         {
3527                                 h++;
3528                                 w += l;         /* previous table always l bits */
3529
3530                                 /* compute minimum size table less than or equal to l bits */
3531                                 z = g - w;
3532                                 z = z > (uInt)l ? (uInt)l : z; /* table size upper limit */
3533                                 if ( ( f = 1 << ( j = k - w ) ) > a + 1 ) { /* try a k-w bit table */
3534                                         /* too few codes for k-w bit table */
3535                                         f -= a + 1; /* deduct codes from patterns left */
3536                                         xp = c + k;
3537                                         if ( j < z ) {
3538                                                 while ( ++j < z ) /* try smaller tables up to z bits */
3539                                                 {
3540                                                         if ( ( f <<= 1 ) <= *++xp ) {
3541                                                                 break; /* enough codes to use up j bits */
3542                                                         }
3543                                                         f -= *xp; /* else deduct codes from patterns */
3544                                                 }
3545                                         }
3546                                 }
3547                                 z = 1 << j;     /* table entries for j-bit table */
3548
3549                                 /* allocate new table */
3550                                 if ( *hn + z > MANY ) { /* (note: doesn't matter for fixed) */
3551                                         return Z_MEM_ERROR; /* not enough memory */
3552                                 }
3553                                 u[h] = q = hp + *hn;
3554                                 *hn += z;
3555
3556                                 /* connect to last table, if there is one */
3557                                 if ( h ) {
3558                                         x[h] = i;   /* save pattern for backing up */
3559                                         r.bits = (Byte)l; /* bits to dump before this table */
3560                                         r.exop = (Byte)j; /* bits in this table */
3561                                         j = i >> ( w - l );
3562                                         r.base = (uInt)( q - u[h - 1] - j ); /* offset to this table */
3563                                         u[h - 1][j] = r; /* connect to last table */
3564                                 }
3565                                 else{
3566                                         *t = q;     /* first table is returned result */
3567                                 }
3568                         }
3569
3570                         /* set up table entry in r */
3571                         r.bits = (Byte)( k - w );
3572                         if ( p >= v + n ) {
3573                                 r.exop = 128 + 64; /* out of values--invalid code */
3574                                 r.base = 0;
3575                         }
3576                         else if ( *p < s ) {
3577                                 r.exop = (Byte)( *p < 256 ? 0 : 32 + 64 ); /* 256 is end-of-block */
3578                                 r.base = *p++;  /* simple code is just the value */
3579                         }
3580                         else
3581                         {
3582                                 r.exop = (Byte)( e[*p - s] + 16 + 64 ); /* non-simple--look up in lists */
3583                                 r.base = d[*p++ - s];
3584                         }
3585
3586                         /* fill code-like entries with r */
3587                         f = 1 << ( k - w );
3588                         for ( j = i >> w; j < z; j += f )
3589                                 q[j] = r;
3590
3591                         /* backwards increment the k-bit code i */
3592                         for ( j = 1 << ( k - 1 ); i &j; j >>= 1 )
3593                                 i ^= j;
3594                         i ^= j;
3595
3596                         /* backup over finished tables */
3597                         mask = ( 1 << w ) - 1; /* needed on HP, cc -O bug */
3598                         while ( ( i & mask ) != x[h] )
3599                         {
3600                                 h--;            /* don't need to update q */
3601                                 w -= l;
3602                                 mask = ( 1 << w ) - 1;
3603                         }
3604                 }
3605         }
3606
3607
3608         /* Return Z_BUF_ERROR if we were given an incomplete table */
3609         return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
3610 }
3611
3612
3613 #ifndef __APPLE__
3614 int inflate_trees_bits( uInt *c, uInt *bb, inflate_huft * *tb, inflate_huft *hp, z_streamp z ){
3615 //uInt *c;               /* 19 code lengths */
3616 //uInt *bb;              /* bits tree desired/actual depth */
3617 //inflate_huft * *tb; /* bits tree result */
3618 //inflate_huft *hp;       /* space for trees */
3619 //z_streamp z;            /* for messages */
3620         int r;
3621         uInt hn = 0;        /* hufts used in space */
3622         uInt *v;           /* work area for huft_build */
3623
3624         if ( ( v = (uInt*)ZALLOC( z, 19, sizeof( uInt ) ) ) == Z_NULL ) {
3625                 return Z_MEM_ERROR;
3626         }
3627         r = huft_build( c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL,
3628                                         tb, bb, hp, &hn, v );
3629         if ( r == Z_DATA_ERROR ) {
3630                 z->msg = (char*)"oversubscribed dynamic bit lengths tree";
3631         }
3632         else if ( r == Z_BUF_ERROR || *bb == 0 ) {
3633                 z->msg = (char*)"incomplete dynamic bit lengths tree";
3634                 r = Z_DATA_ERROR;
3635         }
3636         ZFREE( z, v );
3637         return r;
3638 }
3639 #endif
3640
3641 #ifndef __APPLE__
3642 int inflate_trees_dynamic( uInt nl, uInt nd, uInt *c, uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, inflate_huft *hp, z_streamp z ){
3643 //uInt nl;                /* number of literal/length codes */
3644 //uInt nd;                /* number of distance codes */
3645 //uInt *c;               /* that many (total) code lengths */
3646 //uInt *bl;              /* literal desired/actual bit depth */
3647 //uInt *bd;              /* distance desired/actual bit depth */
3648 //inflate_huft * *tl; /* literal/length tree result */
3649 //inflate_huft * *td; /* distance tree result */
3650 //inflate_huft *hp;       /* space for trees */
3651 //z_streamp z;            /* for messages */
3652         int r;
3653         uInt hn = 0;        /* hufts used in space */
3654         uInt *v;           /* work area for huft_build */
3655
3656         /* allocate work area */
3657         if ( ( v = (uInt*)ZALLOC( z, 288, sizeof( uInt ) ) ) == Z_NULL ) {
3658                 return Z_MEM_ERROR;
3659         }
3660
3661         /* build literal/length tree */
3662         r = huft_build( c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v );
3663         if ( r != Z_OK || *bl == 0 ) {
3664                 if ( r == Z_DATA_ERROR ) {
3665                         z->msg = (char*)"oversubscribed literal/length tree";
3666                 }
3667                 else if ( r != Z_MEM_ERROR ) {
3668                         z->msg = (char*)"incomplete literal/length tree";
3669                         r = Z_DATA_ERROR;
3670                 }
3671                 ZFREE( z, v );
3672                 return r;
3673         }
3674
3675         /* build distance tree */
3676         r = huft_build( c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v );
3677         if ( r != Z_OK || ( *bd == 0 && nl > 257 ) ) {
3678                 if ( r == Z_DATA_ERROR ) {
3679                         z->msg = (char*)"oversubscribed distance tree";
3680                 }
3681                 else if ( r == Z_BUF_ERROR ) {
3682 #ifdef PKZIP_BUG_WORKAROUND
3683                         r = Z_OK;
3684                 }
3685 #else
3686                         z->msg = (char*)"incomplete distance tree";
3687                         r = Z_DATA_ERROR;
3688                 }
3689                 else if ( r != Z_MEM_ERROR ) {
3690                         z->msg = (char*)"empty distance tree with lengths";
3691                         r = Z_DATA_ERROR;
3692                 }
3693                 ZFREE( z, v );
3694                 return r;
3695 #endif
3696         }
3697
3698         /* done */
3699         ZFREE( z, v );
3700         return Z_OK;
3701 }
3702 #endif
3703
3704 /* inffixed.h -- table for decoding fixed codes
3705  * Generated automatically by the maketree.c program
3706  */
3707
3708 /* WARNING: this file should *not* be used by applications. It is
3709    part of the implementation of the compression library and is
3710    subject to change. Applications should only use zlib.h.
3711  */
3712
3713 static uInt fixed_bl = 9;
3714 static uInt fixed_bd = 5;
3715 static inflate_huft fixed_tl[] = {
3716         {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
3717         {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
3718         {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
3719         {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
3720         {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
3721         {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
3722         {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
3723         {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
3724         {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
3725         {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
3726         {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
3727         {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
3728         {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
3729         {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
3730         {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
3731         {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
3732         {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
3733         {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
3734         {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
3735         {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
3736         {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
3737         {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
3738         {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
3739         {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
3740         {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
3741         {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
3742         {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
3743         {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
3744         {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
3745         {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
3746         {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
3747         {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
3748         {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
3749         {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
3750         {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
3751         {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
3752         {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
3753         {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
3754         {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
3755         {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
3756         {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
3757         {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
3758         {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
3759         {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
3760         {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
3761         {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
3762         {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
3763         {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
3764         {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
3765         {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
3766         {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
3767         {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
3768         {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
3769         {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
3770         {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
3771         {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
3772         {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
3773         {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
3774         {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
3775         {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
3776         {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
3777         {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
3778         {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
3779         {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
3780         {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
3781         {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
3782         {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
3783         {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
3784         {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
3785         {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
3786         {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
3787         {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
3788         {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
3789         {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
3790         {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
3791         {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
3792         {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
3793         {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
3794         {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
3795         {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
3796         {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
3797         {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
3798         {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
3799         {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
3800         {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
3801         {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
3802         {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
3803         {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
3804         {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
3805         {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
3806         {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
3807         {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
3808         {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
3809         {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
3810         {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
3811         {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
3812         {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
3813         {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
3814         {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
3815         {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
3816         {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
3817         {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
3818         {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
3819         {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
3820         {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
3821         {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
3822         {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
3823         {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
3824         {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
3825         {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
3826         {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
3827         {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
3828         {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
3829         {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
3830         {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
3831         {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
3832         {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
3833         {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
3834         {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
3835         {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
3836         {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
3837         {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
3838         {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
3839         {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
3840         {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
3841         {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
3842         {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
3843         {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
3844 };
3845 static inflate_huft fixed_td[] = {
3846         {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
3847         {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
3848         {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
3849         {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
3850         {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
3851         {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
3852         {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
3853         {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
3854 };
3855
3856 #ifndef __APPLE__
3857 int inflate_trees_fixed( uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, z_streamp z ){
3858 //uInt *bl;               /* literal desired/actual bit depth */
3859 //uInt *bd;               /* distance desired/actual bit depth */
3860 //inflate_huft * *tl;  /* literal/length tree result */
3861 //inflate_huft * *td;  /* distance tree result */
3862 //z_streamp z;             /* for memory allocation */
3863         *bl = fixed_bl;
3864         *bd = fixed_bd;
3865         *tl = fixed_tl;
3866         *td = fixed_td;
3867         return Z_OK;
3868 }
3869 #endif
3870
3871 /* simplify the use of the inflate_huft type with some defines */
3872 #define exop word.what.Exop
3873 #define bits word.what.Bits
3874
3875 /* macros for bit input with no checking and for returning unused bytes */
3876 #define GRABBITS( j ) {while ( k < ( j ) ) {b |= ( (uLong)NEXTBYTE ) << k; k += 8; }}
3877 #define UNGRAB {c = z->avail_in - n; c = ( k >> 3 ) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; }
3878
3879 /* Called with number of bytes left to write in window at least 258
3880    (the maximum string length) and number of input bytes available
3881    at least ten.  The ten bytes are six bytes for the longest length/
3882    distance pair plus four bytes for overloading the bit buffer. */
3883
3884 #ifndef __APPLE__
3885 int inflate_fast( uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, inflate_blocks_statef *s, z_streamp z ){
3886         inflate_huft *t;    /* temporary pointer */
3887         uInt e;             /* extra bits or operation */
3888         uLong b;            /* bit buffer */
3889         uInt k;             /* bits in bit buffer */
3890         Byte *p;           /* input data pointer */
3891         uInt n;             /* bytes available there */
3892         Byte *q;           /* output window write pointer */
3893         uInt m;             /* bytes to end of window or read pointer */
3894         uInt ml;            /* mask for literal/length tree */
3895         uInt md;            /* mask for distance tree */
3896         uInt c;             /* bytes to copy */
3897         uInt d;             /* distance back to copy from */
3898         Byte *r;           /* copy source pointer */
3899
3900         /* load input, output, bit values */
3901         LOAD
3902
3903         /* initialize masks */
3904                 ml = inflate_mask[bl];
3905         md = inflate_mask[bd];
3906
3907         /* do until not enough input or output space for fast loop */
3908         do {                        /* assume called with m >= 258 && n >= 10 */
3909                 /* get literal/length code */
3910                 GRABBITS( 20 )          /* max bits for literal/length code */
3911                 if ( ( e = ( t = tl + ( (uInt)b & ml ) )->exop ) == 0 ) {
3912                         DUMPBITS( t->bits )
3913                         Tracevv( ( t->base >= 0x20 && t->base < 0x7f ?
3914                                            "inflate:         * literal '%c'\n" :
3915                                            "inflate:         * literal 0x%02x\n", t->base ) );
3916                         *q++ = (Byte)t->base;
3917                         m--;
3918                         continue;
3919                 }
3920                 do {
3921                         DUMPBITS( t->bits )
3922                         if ( e & 16 ) {
3923                                 /* get extra bits for length */
3924                                 e &= 15;
3925                                 c = t->base + ( (uInt)b & inflate_mask[e] );
3926                                 DUMPBITS( e )
3927                                 Tracevv( ( "inflate:         * length %u\n", c ) );
3928
3929                                 /* decode distance base of block to copy */
3930                                 GRABBITS( 15 ); /* max bits for distance code */
3931                                 e = ( t = td + ( (uInt)b & md ) )->exop;
3932                                 do {
3933                                         DUMPBITS( t->bits )
3934                                         if ( e & 16 ) {
3935                                                 /* get extra bits to add to distance base */
3936                                                 e &= 15;
3937                                                 GRABBITS( e ) /* get extra bits (up to 13) */
3938                                                 d = t->base + ( (uInt)b & inflate_mask[e] );
3939                                                 DUMPBITS( e )
3940                                                 Tracevv( ( "inflate:         * distance %u\n", d ) );
3941
3942                                                 /* do the copy */
3943                                                 m -= c;
3944                                                 if ( (uInt)( q - s->window ) >= d ) { /* offset before dest */
3945                                                                                           /*  just copy */
3946                                                         r = q - d;
3947                                                         *q++ = *r++;  c--; /* minimum count is three, */
3948                                                         *q++ = *r++;  c--; /*  so unroll loop a little */
3949                                                 }
3950                                                 else            /* else offset after destination */
3951                                                 {
3952                                                         e = d - (uInt)( q - s->window ); /* bytes from offset to end */
3953                                                         r = s->end - e; /* pointer to offset */
3954                                                         if ( c > e ) { /* if source crosses, */
3955                                                                 c -= e; /* copy to end of window */
3956                                                                 do {
3957                                                                         *q++ = *r++;
3958                                                                 } while ( --e );
3959                                                                 r = s->window; /* copy rest from start of window */
3960                                                         }
3961                                                 }
3962                                                 do {            /* copy all or what's left */
3963                                                         *q++ = *r++;
3964                                                 } while ( --c );
3965                                                 break;
3966                                         }
3967                                         else if ( ( e & 64 ) == 0 ) {
3968                                                 t += t->base;
3969                                                 e = ( t += ( (uInt)b & inflate_mask[e] ) )->exop;
3970                                         }
3971                                         else
3972                                         {
3973                                                 z->msg = (char*)"invalid distance code";
3974                                                 UNGRAB
3975                                                         UPDATE
3976                                                 return Z_DATA_ERROR;
3977                                         }
3978                                 } while ( 1 );
3979                                 break;
3980                         }
3981                         if ( ( e & 64 ) == 0 ) {
3982                                 t += t->base;
3983                                 if ( ( e = ( t += ( (uInt)b & inflate_mask[e] ) )->exop ) == 0 ) {
3984                                         DUMPBITS( t->bits )
3985                                         Tracevv( ( t->base >= 0x20 && t->base < 0x7f ?
3986                                                            "inflate:         * literal '%c'\n" :
3987                                                            "inflate:         * literal 0x%02x\n", t->base ) );
3988                                         *q++ = (Byte)t->base;
3989                                         m--;
3990                                         break;
3991                                 }
3992                         }
3993                         else if ( e & 32 ) {
3994                                 Tracevv( ( "inflate:         * end of block\n" ) );
3995                                 UNGRAB
3996                                         UPDATE
3997                                 return Z_STREAM_END;
3998                         }
3999                         else
4000                         {
4001                                 z->msg = (char*)"invalid literal/length code";
4002                                 UNGRAB
4003                                         UPDATE
4004                                 return Z_DATA_ERROR;
4005                         }
4006                 } while ( 1 );
4007         } while ( m >= 258 && n >= 10 );
4008
4009         /* not enough input or output--restore pointers and return */
4010         UNGRAB
4011                 UPDATE
4012         return Z_OK;
4013 }
4014 #endif
4015
4016 /* infcodes.c -- process literals and length/distance pairs
4017  * Copyright (C) 1995-1998 Mark Adler
4018  * For conditions of distribution and use, see copyright notice in zlib.h
4019  */
4020
4021 /* simplify the use of the inflate_huft type with some defines */
4022 #define exop word.what.Exop
4023 #define bits word.what.Bits
4024
4025 typedef enum {        /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
4026         START,      /* x: set up for LEN */
4027         LEN,        /* i: get length/literal/eob next */
4028         LENEXT,     /* i: getting length extra (have base) */
4029         DIST,       /* i: get distance next */
4030         DISTEXT,    /* i: getting distance extra */
4031         COPY,       /* o: copying bytes in window, waiting for space */
4032         LIT,        /* o: got literal, waiting for output space */
4033         WASH,       /* o: got eob, possibly still output waiting */
4034         END,        /* x: got eob and all data flushed */
4035         BADCODE
4036 }               /* x: got error */
4037 inflate_codes_mode;
4038
4039 /* inflate codes private state */
4040 struct inflate_codes_state {
4041
4042         /* mode */
4043         inflate_codes_mode mode;    /* current inflate_codes mode */
4044
4045         /* mode dependent information */
4046         uInt len;
4047         union {
4048                 struct {
4049                         inflate_huft *tree; /* pointer into tree */
4050                         uInt need;          /* bits needed */
4051                 } code;         /* if LEN or DIST, where in tree */
4052                 uInt lit;       /* if LIT, literal */
4053                 struct {
4054                         uInt get;           /* bits to get for extra */
4055                         uInt dist;          /* distance back to copy from */
4056                 } copy;         /* if EXT or COPY, where and how much */
4057         } sub;              /* submode */
4058
4059         /* mode independent information */
4060         Byte lbits;         /* ltree bits decoded per branch */
4061         Byte dbits;         /* dtree bits decoder per branch */
4062         inflate_huft *ltree;        /* literal/length/eob tree */
4063         inflate_huft *dtree;        /* distance tree */
4064
4065 };
4066
4067 #ifndef __APPLE__
4068 inflate_codes_statef *inflate_codes_new( uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, z_streamp z ){
4069         inflate_codes_statef *c;
4070
4071         if ( ( c = (inflate_codes_statef *)
4072                            ZALLOC( z,1,sizeof( struct inflate_codes_state ) ) ) != Z_NULL ) {
4073                 c->mode = START;
4074                 c->lbits = (Byte)bl;
4075                 c->dbits = (Byte)bd;
4076                 c->ltree = tl;
4077                 c->dtree = td;
4078                 Tracev( ( "inflate:       codes new\n" ) );
4079         }
4080         return c;
4081 }
4082 #endif
4083
4084 #ifndef __APPLE__
4085 int inflate_codes( inflate_blocks_statef *s, z_streamp z, int r ){
4086         uInt j;             /* temporary storage */
4087         inflate_huft *t;    /* temporary pointer */
4088         uInt e;             /* extra bits or operation */
4089         uLong b;            /* bit buffer */
4090         uInt k;             /* bits in bit buffer */
4091         Byte *p;           /* input data pointer */
4092         uInt n;             /* bytes available there */
4093         Byte *q;           /* output window write pointer */
4094         uInt m;             /* bytes to end of window or read pointer */
4095         Byte *f;           /* pointer to copy strings from */
4096         inflate_codes_statef *c = s->sub.decode.codes; /* codes state */
4097
4098         /* copy input/output information to locals (UPDATE macro restores) */
4099         LOAD
4100
4101         /* process input and output based on current state */
4102         while ( 1 ) switch ( c->mode )
4103                 {       /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
4104                 case START:     /* x: set up for LEN */
4105 #ifndef SLOW
4106                         if ( m >= 258 && n >= 10 ) {
4107                                 UPDATE
4108                                         r = inflate_fast( c->lbits, c->dbits, c->ltree, c->dtree, s, z );
4109                                 LOAD
4110                                 if ( r != Z_OK ) {
4111                                         c->mode = r == Z_STREAM_END ? WASH : BADCODE;
4112                                         break;
4113                                 }
4114                         }
4115 #endif /* !SLOW */
4116                         c->sub.code.need = c->lbits;
4117                         c->sub.code.tree = c->ltree;
4118                         c->mode = LEN;
4119                 case LEN:       /* i: get length/literal/eob next */
4120                         j = c->sub.code.need;
4121                         NEEDBITS( j )
4122                         t = c->sub.code.tree + ( (uInt)b & inflate_mask[j] );
4123                         DUMPBITS( t->bits )
4124                         e = (uInt)( t->exop );
4125                         if ( e == 0 ) {     /* literal */
4126                                 c->sub.lit = t->base;
4127                                 Tracevv( ( t->base >= 0x20 && t->base < 0x7f ?
4128                                                    "inflate:         literal '%c'\n" :
4129                                                    "inflate:         literal 0x%02x\n", t->base ) );
4130                                 c->mode = LIT;
4131                                 break;
4132                         }
4133                         if ( e & 16 ) {     /* length */
4134                                 c->sub.copy.get = e & 15;
4135                                 c->len = t->base;
4136                                 c->mode = LENEXT;
4137                                 break;
4138                         }
4139                         if ( ( e & 64 ) == 0 ) { /* next table */
4140                                 c->sub.code.need = e;
4141                                 c->sub.code.tree = t + t->base;
4142                                 break;
4143                         }
4144                         if ( e & 32 ) {     /* end of block */
4145                                 Tracevv( ( "inflate:         end of block\n" ) );
4146                                 c->mode = WASH;
4147                                 break;
4148                         }
4149                         c->mode = BADCODE;  /* invalid code */
4150                         z->msg = (char*)"invalid literal/length code";
4151                         r = Z_DATA_ERROR;
4152                         LEAVE
4153                 case LENEXT:    /* i: getting length extra (have base) */
4154                         j = c->sub.copy.get;
4155                         NEEDBITS( j )
4156                         c->len += (uInt)b & inflate_mask[j];
4157                         DUMPBITS( j )
4158                         c->sub.code.need = c->dbits;
4159                         c->sub.code.tree = c->dtree;
4160                         Tracevv( ( "inflate:         length %u\n", c->len ) );
4161                         c->mode = DIST;
4162                 case DIST:      /* i: get distance next */
4163                         j = c->sub.code.need;
4164                         NEEDBITS( j )
4165                         t = c->sub.code.tree + ( (uInt)b & inflate_mask[j] );
4166                         DUMPBITS( t->bits )
4167                         e = (uInt)( t->exop );
4168                         if ( e & 16 ) {     /* distance */
4169                                 c->sub.copy.get = e & 15;
4170                                 c->sub.copy.dist = t->base;
4171                                 c->mode = DISTEXT;
4172                                 break;
4173                         }
4174                         if ( ( e & 64 ) == 0 ) { /* next table */
4175                                 c->sub.code.need = e;
4176                                 c->sub.code.tree = t + t->base;
4177                                 break;
4178                         }
4179                         c->mode = BADCODE;  /* invalid code */
4180                         z->msg = (char*)"invalid distance code";
4181                         r = Z_DATA_ERROR;
4182                         LEAVE
4183                 case DISTEXT:   /* i: getting distance extra */
4184                         j = c->sub.copy.get;
4185                         NEEDBITS( j )
4186                         c->sub.copy.dist += (uInt)b & inflate_mask[j];
4187                         DUMPBITS( j )
4188                         Tracevv( ( "inflate:         distance %u\n", c->sub.copy.dist ) );
4189                         c->mode = COPY;
4190                 case COPY:      /* o: copying bytes in window, waiting for space */
4191 #ifndef __TURBOC__ /* Turbo C bug for following expression */
4192                         f = (uInt)( q - s->window ) < c->sub.copy.dist ?
4193                                 s->end - ( c->sub.copy.dist - ( q - s->window ) ) :
4194                                 q - c->sub.copy.dist;
4195 #else
4196                         f = q - c->sub.copy.dist;
4197                         if ( (uInt)( q - s->window ) < c->sub.copy.dist ) {
4198                                 f = s->end - ( c->sub.copy.dist - (uInt)( q - s->window ) );
4199                         }
4200 #endif
4201                         while ( c->len )
4202                         {
4203                                 NEEDOUT
4204                                 OUTBYTE( *f++ )
4205                                 if ( f == s->end ) {
4206                                         f = s->window;
4207                                 }
4208                                 c->len--;
4209                         }
4210                         c->mode = START;
4211                         break;
4212                 case LIT:       /* o: got literal, waiting for output space */
4213                         NEEDOUT
4214                         OUTBYTE( c->sub.lit )
4215                         c->mode = START;
4216                         break;
4217                 case WASH:      /* o: got eob, possibly more output */
4218                         if ( k > 7 ) { /* return unused byte, if any */
4219                                 Assert( k < 16, "inflate_codes grabbed too many bytes" )
4220                                 k -= 8;
4221                                 n++;
4222                                 p--;    /* can always return one */
4223                         }
4224                         FLUSH
4225                         if ( s->read != s->write ) {
4226                                 LEAVE
4227                                 c->mode = END;
4228                         }
4229                 case END:
4230                         r = Z_STREAM_END;
4231                         LEAVE
4232                 case BADCODE:   /* x: got error */
4233                         r = Z_DATA_ERROR;
4234                         LEAVE
4235                 default:
4236                         r = Z_STREAM_ERROR;
4237                         LEAVE
4238                 }
4239 #ifdef NEED_DUMMY_RETURN
4240         return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
4241 #endif
4242 }
4243 #endif
4244
4245 #ifndef __APPLE__
4246 void inflate_codes_free( inflate_codes_statef *c, z_streamp z ){
4247         ZFREE( z, c );
4248         Tracev( ( "inflate:       codes free\n" ) );
4249 }
4250 #endif
4251
4252 /* adler32.c -- compute the Adler-32 checksum of a data stream
4253  * Copyright (C) 1995-1998 Mark Adler
4254  * For conditions of distribution and use, see copyright notice in zlib.h
4255  */
4256
4257 #define BASE 65521L /* largest prime smaller than 65536 */
4258 #define NMAX 5552
4259 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
4260
4261 #undef DO1
4262 #undef DO2
4263 #undef DO4
4264 #undef DO8
4265
4266 #define DO1( buf,i )  {s1 += buf[i]; s2 += s1; }
4267 #define DO2( buf,i )  DO1( buf,i ); DO1( buf,i + 1 );
4268 #define DO4( buf,i )  DO2( buf,i ); DO2( buf,i + 2 );
4269 #define DO8( buf,i )  DO4( buf,i ); DO4( buf,i + 4 );
4270 #define DO16( buf )   DO8( buf,0 ); DO8( buf,8 );
4271
4272 /* ========================================================================= */
4273 #ifndef __APPLE__
4274 uLong adler32( uLong adler, const Byte *buf, uInt len ){
4275         unsigned long s1 = adler & 0xffff;
4276         unsigned long s2 = ( adler >> 16 ) & 0xffff;
4277         int k;
4278
4279         if ( buf == Z_NULL ) {
4280                 return 1L;
4281         }
4282
4283         while ( len > 0 ) {
4284                 k = len < NMAX ? len : NMAX;
4285                 len -= k;
4286                 while ( k >= 16 ) {
4287                         DO16( buf );
4288                         buf += 16;
4289                         k -= 16;
4290                 }
4291                 if ( k != 0 ) {
4292                         do {
4293                                 s1 += *buf++;
4294                                 s2 += s1;
4295                         } while ( --k );
4296                 }
4297                 s1 %= BASE;
4298                 s2 %= BASE;
4299         }
4300         return ( s2 << 16 ) | s1;
4301 }
4302 #endif
4303
4304
4305 /* infblock.h -- header to use infblock.c
4306  * Copyright (C) 1995-1998 Mark Adler
4307  * For conditions of distribution and use, see copyright notice in zlib.h
4308  */
4309
4310 /* WARNING: this file should *not* be used by applications. It is
4311    part of the implementation of the compression library and is
4312    subject to change. Applications should only use zlib.h.
4313  */
4314
4315 extern inflate_blocks_statef * inflate_blocks_new OF( (
4316                                                                                                                   z_streamp z,
4317                                                                                                                   check_func c, /* check function */
4318                                                                                                                   uInt w ) ); /* window size */
4319
4320 extern int inflate_blocks OF( (
4321                                                                   inflate_blocks_statef *,
4322                                                                   z_streamp,
4323                                                                   int ) ); /* initial return code */
4324
4325 extern void inflate_blocks_reset OF( (
4326                                                                                  inflate_blocks_statef *,
4327                                                                                  z_streamp,
4328                                                                                  uLong * ) ); /* check value on output */
4329
4330 extern int inflate_blocks_free OF( (
4331                                                                            inflate_blocks_statef *,
4332                                                                            z_streamp ) );
4333
4334 extern void inflate_set_dictionary OF( (
4335                                                                                    inflate_blocks_statef * s,
4336                                                                                    const Byte * d, /* dictionary */
4337                                                                                    uInt n ) ); /* dictionary length */
4338
4339 extern int inflate_blocks_sync_point OF( (
4340                                                                                          inflate_blocks_statef * s ) );
4341
4342 typedef enum {
4343         imMETHOD,     /* waiting for method byte */
4344         imFLAG,       /* waiting for flag byte */
4345         imDICT4,      /* four dictionary check bytes to go */
4346         imDICT3,      /* three dictionary check bytes to go */
4347         imDICT2,      /* two dictionary check bytes to go */
4348         imDICT1,      /* one dictionary check byte to go */
4349         imDICT0,      /* waiting for inflateSetDictionary */
4350         imBLOCKS,     /* decompressing blocks */
4351         imCHECK4,     /* four check bytes to go */
4352         imCHECK3,     /* three check bytes to go */
4353         imCHECK2,     /* two check bytes to go */
4354         imCHECK1,     /* one check byte to go */
4355         imDONE,       /* finished check, done */
4356         imBAD
4357 }                 /* got an error--stay here */
4358 inflate_mode;
4359
4360 /* inflate private state */
4361 struct internal_state {
4362
4363         /* mode */
4364         inflate_mode mode;  /* current inflate mode */
4365
4366         /* mode dependent information */
4367         union {
4368                 uInt method;    /* if FLAGS, method byte */
4369                 struct {
4370                         uLong was;          /* computed check value */
4371                         uLong need;         /* stream check value */
4372                 } check;        /* if CHECK, check values to compare */
4373                 uInt marker;    /* if BAD, inflateSync's marker bytes count */
4374         } sub;      /* submode */
4375
4376         /* mode independent information */
4377         int nowrap;         /* flag for no wrapper */
4378         uInt wbits;         /* log2(window size)  (8..15, defaults to 15) */
4379         inflate_blocks_statef
4380         *blocks;            /* current inflate_blocks state */
4381
4382 };
4383
4384
4385 #ifndef __APPLE__
4386 int inflateReset( z_streamp z ){
4387         if ( z == Z_NULL || z->state == Z_NULL ) {
4388                 return Z_STREAM_ERROR;
4389         }
4390         z->total_in = z->total_out = 0;
4391         z->msg = Z_NULL;
4392         z->state->mode = z->state->nowrap ? imBLOCKS : imMETHOD;
4393         inflate_blocks_reset( z->state->blocks, z, Z_NULL );
4394         Tracev( ( "inflate: reset\n" ) );
4395         return Z_OK;
4396 }
4397 #endif
4398
4399 #ifndef __APPLE__
4400 int inflateEnd( z_streamp z ){
4401         if ( z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL ) {
4402                 return Z_STREAM_ERROR;
4403         }
4404         if ( z->state->blocks != Z_NULL ) {
4405                 inflate_blocks_free( z->state->blocks, z );
4406         }
4407         ZFREE( z, z->state );
4408         z->state = Z_NULL;
4409         Tracev( ( "inflate: end\n" ) );
4410         return Z_OK;
4411 }
4412 #endif
4413
4414 #ifndef __APPLE__
4415 int inflateInit2_( z_streamp z, int w, const char *version, int stream_size ){
4416         if ( version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
4417                  stream_size != sizeof( z_stream ) ) {
4418                 return Z_VERSION_ERROR;
4419         }
4420
4421         /* initialize state */
4422         if ( z == Z_NULL ) {
4423                 return Z_STREAM_ERROR;
4424         }
4425         z->msg = Z_NULL;
4426         if ( z->zalloc == Z_NULL ) {
4427                 z->zalloc = ( void *( * )( void *, unsigned, unsigned ) )zcalloc;
4428                 z->opaque = (voidp)0;
4429         }
4430         if ( z->zfree == Z_NULL ) {
4431                 z->zfree = ( void ( * )( void *, void * ) )zcfree;
4432         }
4433         if ( ( z->state = (struct internal_state *)
4434                                           ZALLOC( z,1,sizeof( struct internal_state ) ) ) == Z_NULL ) {
4435                 return Z_MEM_ERROR;
4436         }
4437         z->state->blocks = Z_NULL;
4438
4439         /* handle undocumented nowrap option (no zlib header or check) */
4440         z->state->nowrap = 0;
4441         if ( w < 0 ) {
4442                 w = -w;
4443                 z->state->nowrap = 1;
4444         }
4445
4446         /* set window size */
4447         if ( w < 8 || w > 15 ) {
4448                 inflateEnd( z );
4449                 return Z_STREAM_ERROR;
4450         }
4451         z->state->wbits = (uInt)w;
4452
4453         /* create inflate_blocks state */
4454         if ( ( z->state->blocks =
4455                            inflate_blocks_new( z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w ) )
4456                  == Z_NULL ) {
4457                 inflateEnd( z );
4458                 return Z_MEM_ERROR;
4459         }
4460         Tracev( ( "inflate: allocated\n" ) );
4461
4462         /* reset state */
4463         inflateReset( z );
4464         return Z_OK;
4465 }
4466 #endif
4467
4468 #ifndef __APPLE__
4469 int inflateInit_( z_streamp z, const char *version, int stream_size ){
4470         return inflateInit2_( z, DEF_WBITS, version, stream_size );
4471 }
4472 #endif
4473
4474 #define iNEEDBYTE {if ( z->avail_in == 0 ) {return r; } r = f; }
4475 #define iNEXTBYTE ( z->avail_in--,z->total_in++,*z->next_in++ )
4476
4477 #ifndef __APPLE__
4478 int inflate( z_streamp z, int f ){
4479         int r;
4480         uInt b;
4481
4482         if ( z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL ) {
4483                 return Z_STREAM_ERROR;
4484         }
4485         f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
4486         r = Z_BUF_ERROR;
4487         while ( 1 ) switch ( z->state->mode )
4488                 {
4489                 case imMETHOD:
4490                         iNEEDBYTE
4491                         if ( ( ( z->state->sub.method = iNEXTBYTE ) & 0xf ) != Z_DEFLATED ) {
4492                                 z->state->mode = imBAD;
4493                                 z->msg = (char*)"unknown compression method";
4494                                 z->state->sub.marker = 5; /* can't try inflateSync */
4495                                 break;
4496                         }
4497                         if ( ( z->state->sub.method >> 4 ) + 8 > z->state->wbits ) {
4498                                 z->state->mode = imBAD;
4499                                 z->msg = (char*)"invalid window size";
4500                                 z->state->sub.marker = 5; /* can't try inflateSync */
4501                                 break;
4502                         }
4503                         z->state->mode = imFLAG;
4504                 case imFLAG:
4505                         iNEEDBYTE
4506                         b = iNEXTBYTE;
4507                         if ( ( ( z->state->sub.method << 8 ) + b ) % 31 ) {
4508                                 z->state->mode = imBAD;
4509                                 z->msg = (char*)"incorrect header check";
4510                                 z->state->sub.marker = 5; /* can't try inflateSync */
4511                                 break;
4512                         }
4513                         Tracev( ( "inflate: zlib header ok\n" ) );
4514                         if ( !( b & PRESET_DICT ) ) {
4515                                 z->state->mode = imBLOCKS;
4516                                 break;
4517                         }
4518                         z->state->mode = imDICT4;
4519                 case imDICT4:
4520                         iNEEDBYTE
4521                         z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
4522                         z->state->mode = imDICT3;
4523                 case imDICT3:
4524                         iNEEDBYTE
4525                         z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
4526                         z->state->mode = imDICT2;
4527                 case imDICT2:
4528                         iNEEDBYTE
4529                         z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
4530                         z->state->mode = imDICT1;
4531                 case imDICT1:
4532                         iNEEDBYTE
4533                         z->state->sub.check.need += (uLong)iNEXTBYTE;
4534                         z->adler = z->state->sub.check.need;
4535                         z->state->mode = imDICT0;
4536                         return Z_NEED_DICT;
4537                 case imDICT0:
4538                         z->state->mode = imBAD;
4539                         z->msg = (char*)"need dictionary";
4540                         z->state->sub.marker = 0; /* can try inflateSync */
4541                         return Z_STREAM_ERROR;
4542                 case imBLOCKS:
4543                         r = inflate_blocks( z->state->blocks, z, r );
4544                         if ( r == Z_DATA_ERROR ) {
4545                                 z->state->mode = imBAD;
4546                                 z->state->sub.marker = 0; /* can try inflateSync */
4547                                 break;
4548                         }
4549                         if ( r == Z_OK ) {
4550                                 r = f;
4551                         }
4552                         if ( r != Z_STREAM_END ) {
4553                                 return r;
4554                         }
4555                         r = f;
4556                         inflate_blocks_reset( z->state->blocks, z, &z->state->sub.check.was );
4557                         if ( z->state->nowrap ) {
4558                                 z->state->mode = imDONE;
4559                                 break;
4560                         }
4561                         z->state->mode = imCHECK4;
4562                 case imCHECK4:
4563                         iNEEDBYTE
4564                         z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
4565                         z->state->mode = imCHECK3;
4566                 case imCHECK3:
4567                         iNEEDBYTE
4568                         z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
4569                         z->state->mode = imCHECK2;
4570                 case imCHECK2:
4571                         iNEEDBYTE
4572                         z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
4573                         z->state->mode = imCHECK1;
4574                 case imCHECK1:
4575                         iNEEDBYTE
4576                         z->state->sub.check.need += (uLong)iNEXTBYTE;
4577
4578                         if ( z->state->sub.check.was != z->state->sub.check.need ) {
4579                                 z->state->mode = imBAD;
4580                                 z->msg = (char*)"incorrect data check";
4581                                 z->state->sub.marker = 5; /* can't try inflateSync */
4582                                 break;
4583                         }
4584                         Tracev( ( "inflate: zlib check ok\n" ) );
4585                         z->state->mode = imDONE;
4586                 case imDONE:
4587                         return Z_STREAM_END;
4588                 case imBAD:
4589                         return Z_DATA_ERROR;
4590                 default:
4591                         return Z_STREAM_ERROR;
4592                 }
4593 #ifdef NEED_DUMMY_RETURN
4594         return Z_STREAM_ERROR; /* Some dumb compilers complain without this */
4595 #endif
4596 }
4597 #endif
4598
4599 #ifndef __APPLE__
4600 int inflateSetDictionary( z_streamp z, const Byte *dictionary, uInt dictLength ){
4601         uInt length = dictLength;
4602
4603         if ( z == Z_NULL || z->state == Z_NULL || z->state->mode != imDICT0 ) {
4604                 return Z_STREAM_ERROR;
4605         }
4606
4607         if ( adler32( 1L, dictionary, dictLength ) != z->adler ) {
4608                 return Z_DATA_ERROR;
4609         }
4610         z->adler = 1L;
4611
4612         if ( length >= ( (uInt)1 << z->state->wbits ) ) {
4613                 length = ( 1 << z->state->wbits ) - 1;
4614                 dictionary += dictLength - length;
4615         }
4616         inflate_set_dictionary( z->state->blocks, dictionary, length );
4617         z->state->mode = imBLOCKS;
4618         return Z_OK;
4619 }
4620 #endif
4621
4622 #ifndef __APPLE__
4623 int inflateSync( z_streamp z ){
4624         uInt n;     /* number of bytes to look at */
4625         Byte *p;   /* pointer to bytes */
4626         uInt m;     /* number of marker bytes found in a row */
4627         uLong r, w; /* temporaries to save total_in and total_out */
4628
4629         /* set up */
4630         if ( z == Z_NULL || z->state == Z_NULL ) {
4631                 return Z_STREAM_ERROR;
4632         }
4633         if ( z->state->mode != imBAD ) {
4634                 z->state->mode = imBAD;
4635                 z->state->sub.marker = 0;
4636         }
4637         if ( ( n = z->avail_in ) == 0 ) {
4638                 return Z_BUF_ERROR;
4639         }
4640         p = z->next_in;
4641         m = z->state->sub.marker;
4642
4643         /* search */
4644         while ( n && m < 4 )
4645         {
4646                 static const Byte mark[4] = {0, 0, 0xff, 0xff};
4647                 if ( *p == mark[m] ) {
4648                         m++;
4649                 }
4650                 else if ( *p ) {
4651                         m = 0;
4652                 }
4653                 else{
4654                         m = 4 - m;
4655                 }
4656                 p++, n--;
4657         }
4658
4659         /* restore */
4660         z->total_in += p - z->next_in;
4661         z->next_in = p;
4662         z->avail_in = n;
4663         z->state->sub.marker = m;
4664
4665         /* return no joy or set up to restart on a new block */
4666         if ( m != 4 ) {
4667                 return Z_DATA_ERROR;
4668         }
4669         r = z->total_in;  w = z->total_out;
4670         inflateReset( z );
4671         z->total_in = r;  z->total_out = w;
4672         z->state->mode = imBLOCKS;
4673         return Z_OK;
4674 }
4675 #endif
4676
4677 /* Returns true if inflate is currently at the end of a block generated
4678  * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
4679  * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
4680  * but removes the length bytes of the resulting empty stored block. When
4681  * decompressing, PPP checks that at the end of input packet, inflate is
4682  * waiting for these length bytes.
4683  */
4684 #ifndef __APPLE__
4685 int inflateSyncPoint( z_streamp z ){
4686         if ( z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL ) {
4687                 return Z_STREAM_ERROR;
4688         }
4689         return inflate_blocks_sync_point( z->state->blocks );
4690 }
4691 #endif
4692
4693 #ifndef __APPLE__
4694 voidp zcalloc( voidp opaque, unsigned items, unsigned size ){
4695         if ( opaque ) {
4696                 items += size - size;         /* make compiler happy */
4697         }
4698         return (voidp)safe_malloc( items * size );
4699 }
4700
4701 void  zcfree( voidp opaque, voidp ptr ){
4702         free( ptr );
4703         if ( opaque ) {
4704                 return;         /* make compiler happy */
4705         }
4706 }
4707 #endif