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