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