xref: /titanic_52/usr/src/contrib/ast/src/cmd/INIT/ratz.c (revision 906afcb89d0412cc073b95c2d701a804a8cdb62c)
1 /*
2  * ratz -- read a tar gzip archive from the standard input
3  *
4  * coded for portability
5  * _SEAR_* macros for win32 self extracting archives -- see sear(1).
6  */
7 
8 static char id[] = "\n@(#)$Id: ratz (Jean-loup Gailly, Mark Adler, Glenn Fowler) 1.2.3 2010-10-10 $\0\n";
9 
10 #if _PACKAGE_ast
11 
12 #include <ast.h>
13 #include <error.h>
14 
15 static const char usage[] =
16 "[-?\n@(#)$Id: ratz (Jean-loup Gailly, Mark Adler, Glenn Fowler) 1.2.3 2010-10-10 $\n]"
17 "[-author?Jean-loup Gailly]"
18 "[-author?Mark Adler]"
19 "[-author?Glenn Fowler <gsf@research.att.com>]"
20 "[-copyright?Copyright (c) 1995-2005 Jean-loup Gailly and Mark Adler]"
21 "[-license?http://www.opensource.org/licenses/zlib-license]"
22 "[+NAME?ratz - read a tar gzip archive]"
23 "[+DESCRIPTION?\bratz\b extracts files and directories from a tar gzip"
24 "	archive on the standard input. It is a standalone program for systems"
25 "	that do not have \bpax\b(1), \btar\b(1) or \bgunzip\b(1). Only regular"
26 "	files and directories are extracted; all other file types are ignored.]"
27 "[+?\b.exe\b files generated by \bsear\b(1) are fully functional \bratz\b"
28 "	executables, so any \bratz\b option may be used on a \bsear\b file."
29 "	This allows \bsear\b file contents to be examined and extracted without"
30 "	executing any embedded installation scripts.]"
31 "[c:cat|uncompress?Uncompress the standard input and copy it to the standard"
32 "	output.]"
33 #if defined(_SEAR_EXEC) || defined(_SEAR_SEEK)
34 "[i!:install?Execute the sear installation script.]"
35 "[k:keep?Keep the installation temporary directory.]"
36 #endif
37 "[l:local?Reject files that traverse outside the current directory.]"
38 "[m:meter?Display a one line text meter showing archive read progress.]"
39 "[n!:convert?In ebcdic environments convert text archive members from ascii"
40 "	to the native ebcdic.]"
41 "[t:list?List each file path on the standard output but do not extract.]"
42 "[v:verbose?List each file path on the standard output as it is extracted.]"
43 "[V?Print the program version and exit.]"
44 "[+SEE ALSO?\bgunzip\b(1), \bpackage\b(1), \bpax\b(1), \bsear\b(1), \btar\b(1)]"
45 ;
46 
47 #else
48 
49 #define NiL		((char*)0)
50 
51 #endif
52 
53 #define METER_width	80
54 #define METER_parts	20
55 
56 #ifndef _GUNZIP_H
57 #define _GUNZIP_H	1
58 
59 /*
60  * stripped down zlib containing public gzfopen()+gzread() in one file
61  * USE THE REAL ZLIB AFTER BOOTSTRAP
62  */
63 
64 #define ZLIB_INTERNAL	1
65 #define NO_GZCOMPRESS	1
66 
67 #define gz_headerp	voidp
68 
69 #include <stdio.h>
70 #include <sys/types.h>
71 
72 #if _PACKAGE_ast || defined(__STDC__) || defined(_SEAR_EXEC) || defined(_WIN32)
73 
74 #define FOPEN_READ	"rb"
75 #define FOPEN_WRITE	"wb"
76 
77 #else
78 
79 #define FOPEN_READ	"r"
80 #define FOPEN_WRITE	"w"
81 
82 #endif
83 
84 #ifndef O_BINARY
85 #define O_BINARY	0
86 #endif
87 
88 #if _PACKAGE_ast
89 
90 #ifndef setmode
91 #define setmode(d,m)
92 #endif
93 
94 #else
95 
96 #if !defined(_WINIX) && (_UWIN || __CYGWIN__ || __EMX__)
97 #define _WINIX		1
98 #endif
99 
100 #if _WIN32 && !_WINIX
101 
102 #include <direct.h>
103 #include <io.h>
104 #include <fcntl.h>
105 #include <windows.h>
106 
107 #define access		_access
108 #define chmod		_chmod
109 #define close		_close
110 #define dup		_dup
111 #define lseek		_lseek
112 #define open		_open
113 #define read		_read
114 #define setmode		_setmode
115 #define unlink		_unlink
116 
117 #define mkdir(a,b)	_mkdir(a)
118 
119 #else
120 
121 #define HAVE_UNISTD_H	1
122 
123 #include <unistd.h>
124 #include <errno.h>
125 
126 #ifndef setmode
127 #define setmode(d,m)
128 #endif
129 
130 #endif
131 
132 #if defined(__STDC__)
133 
134 #include <stdlib.h>
135 #include <string.h>
136 
137 #endif
138 
139 #endif
140 
141 #ifndef _ZLIB_H
142 #define _ZLIB_H		1
143 
144 /* zlib.h -- interface of the 'zlib' general purpose compression library
145   version 1.2.3, July 18th, 2005
146 
147   Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
148 
149   This software is provided 'as-is', without any express or implied
150   warranty.  In no event will the authors be held liable for any damages
151   arising from the use of this software.
152 
153   Permission is granted to anyone to use this software for any purpose,
154   including commercial applications, and to alter it and redistribute it
155   freely, subject to the following restrictions:
156 
157   1. The origin of this software must not be misrepresented; you must not
158      claim that you wrote the original software. If you use this software
159      in a product, an acknowledgment in the product documentation would be
160      appreciated but is not required.
161   2. Altered source versions must be plainly marked as such, and must not be
162      misrepresented as being the original software.
163   3. This notice may not be removed or altered from any source distribution.
164 
165   Jean-loup Gailly        Mark Adler
166   jloup@gzip.org          madler@alumni.caltech.edu
167 
168 
169   The data format used by the zlib library is described by RFCs (Request for
170   Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
171   (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
172 */
173 
174 #ifndef _ZCONF_H
175 #define _ZCONF_H	1
176 
177 #if _PACKAGE_ast
178 #include <ast_std.h>	/* for { _WINIX __IMPORT__ __EXPORT__ } */
179 #define z_off_t		int32_t
180 #if _typ_int64_t
181 #define z_off64_t	int64_t
182 #endif
183 #else
184 #if !defined(_WINIX) && (_UWIN || __CYGWIN__ || __EMX__)
185 #define _WINIX		1
186 #endif
187 #endif
188 
189 #if _BLD_z && defined(__EXPORT__)
190 #define ZEXTERN		__EXPORT__
191 #define ZEXPORT
192 #endif
193 
194 #if defined(__MSDOS__) && !defined(MSDOS)
195 #  define MSDOS
196 #endif
197 #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
198 #  define OS2
199 #endif
200 #if defined(_WINDOWS) && !defined(WINDOWS)
201 #  define WINDOWS
202 #endif
203 #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
204 #  ifndef WIN32
205 #    define WIN32
206 #  endif
207 #endif
208 #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
209 #  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
210 #    ifndef SYS16BIT
211 #      define SYS16BIT
212 #    endif
213 #  endif
214 #endif
215 
216 /*
217  * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
218  * than 64k bytes at a time (needed on systems with 16-bit int).
219  */
220 #ifdef SYS16BIT
221 #  define MAXSEG_64K
222 #endif
223 #ifdef MSDOS
224 #  define UNALIGNED_OK
225 #endif
226 
227 #ifdef __STDC_VERSION__
228 #  ifndef STDC
229 #    define STDC
230 #  endif
231 #  if __STDC_VERSION__ >= 199901L
232 #    ifndef STDC99
233 #      define STDC99
234 #    endif
235 #  endif
236 #endif
237 #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
238 #  define STDC
239 #endif
240 #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
241 #  define STDC
242 #endif
243 #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
244 #  define STDC
245 #endif
246 #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
247 #  define STDC
248 #endif
249 
250 #if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
251 #  define STDC
252 #endif
253 
254 #ifndef STDC
255 #  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
256 #    define const       /* note: need a more gentle solution here */
257 #  endif
258 #endif
259 
260 /* Some Mac compilers merge all .h files incorrectly: */
261 #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
262 #  define NO_DUMMY_DECL
263 #endif
264 
265 /* Maximum value for memLevel in deflateInit2 */
266 #ifndef MAX_MEM_LEVEL
267 #  ifdef MAXSEG_64K
268 #    define MAX_MEM_LEVEL 8
269 #  else
270 #    define MAX_MEM_LEVEL 9
271 #  endif
272 #endif
273 
274 /* Maximum value for windowBits in deflateInit2 and inflateInit2.
275  * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
276  * created by gzip. (Files created by minigzip can still be extracted by
277  * gzip.)
278  */
279 #ifndef MAX_WBITS
280 #  define MAX_WBITS   15 /* 32K LZ77 window */
281 #endif
282 
283 /* The memory requirements for deflate are (in bytes):
284             (1 << (windowBits+2)) +  (1 << (memLevel+9))
285  that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
286  plus a few kilobytes for small objects. For example, if you want to reduce
287  the default memory requirements from 256K to 128K, compile with
288      make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
289  Of course this will generally degrade compression (there's no free lunch).
290 
291    The memory requirements for inflate are (in bytes) 1 << windowBits
292  that is, 32K for windowBits=15 (default value) plus a few kilobytes
293  for small objects.
294 */
295 
296                         /* Type declarations */
297 
298 #ifndef OF /* function prototypes */
299 #  ifdef STDC
300 #    define OF(args)  args
301 #  else
302 #    define OF(args)  ()
303 #  endif
304 #endif
305 
306 /* The following definitions for FAR are needed only for MSDOS mixed
307  * model programming (small or medium model with some far allocations).
308  * This was tested only with MSC; for other MSDOS compilers you may have
309  * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
310  * just define FAR to be empty.
311  */
312 #ifdef SYS16BIT
313 #  if defined(M_I86SM) || defined(M_I86MM)
314      /* MSC small or medium model */
315 #    define SMALL_MEDIUM
316 #    ifdef _MSC_VER
317 #      define FAR _far
318 #    else
319 #      define FAR far
320 #    endif
321 #  endif
322 #  if (defined(__SMALL__) || defined(__MEDIUM__))
323      /* Turbo C small or medium model */
324 #    define SMALL_MEDIUM
325 #    ifdef __BORLANDC__
326 #      define FAR _far
327 #    else
328 #      define FAR far
329 #    endif
330 #  endif
331 #endif
332 
333 #if defined(WINDOWS) || defined(WIN32)
334    /* If building or using zlib as a DLL, define ZLIB_DLL.
335     * This is not mandatory, but it offers a little performance increase.
336     */
337 #  ifdef ZLIB_DLL
338 #    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
339 #      ifdef ZLIB_INTERNAL
340 #        define ZEXTERN extern __declspec(dllexport)
341 #      else
342 #        define ZEXTERN extern __declspec(dllimport)
343 #      endif
344 #    endif
345 #  endif  /* ZLIB_DLL */
346    /* If building or using zlib with the WINAPI/WINAPIV calling convention,
347     * define ZLIB_WINAPI.
348     * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
349     */
350 #  ifdef ZLIB_WINAPI
351 #    ifdef FAR
352 #      undef FAR
353 #    endif
354 #    include <windows.h>
355      /* No need for _export, use ZLIB.DEF instead. */
356      /* For complete Windows compatibility, use WINAPI, not __stdcall. */
357 #    define ZEXPORT WINAPI
358 #    ifdef WIN32
359 #      define ZEXPORTVA WINAPIV
360 #    else
361 #      define ZEXPORTVA FAR CDECL
362 #    endif
363 #  endif
364 #endif
365 
366 #if defined (__BEOS__)
367 #  ifdef ZLIB_DLL
368 #    ifdef ZLIB_INTERNAL
369 #      define ZEXPORT   __declspec(dllexport)
370 #      define ZEXPORTVA __declspec(dllexport)
371 #    else
372 #      define ZEXPORT   __declspec(dllimport)
373 #      define ZEXPORTVA __declspec(dllimport)
374 #    endif
375 #  endif
376 #endif
377 
378 #ifndef ZEXTERN
379 #  define ZEXTERN extern
380 #endif
381 #ifndef ZEXPORT
382 #  define ZEXPORT
383 #endif
384 #ifndef ZEXPORTVA
385 #  define ZEXPORTVA
386 #endif
387 
388 #ifndef FAR
389 #  define FAR
390 #endif
391 
392 #if !defined(__MACTYPES__)
393 typedef unsigned char  Byte;  /* 8 bits */
394 #endif
395 typedef unsigned int   uInt;  /* 16 bits or more */
396 typedef unsigned long  uLong; /* 32 bits or more */
397 
398 #ifdef SMALL_MEDIUM
399    /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
400 #  define Bytef Byte FAR
401 #else
402    typedef Byte  FAR Bytef;
403 #endif
404 typedef char  FAR charf;
405 typedef int   FAR intf;
406 typedef uInt  FAR uIntf;
407 typedef uLong FAR uLongf;
408 
409 #ifdef STDC
410    typedef void const *voidpc;
411    typedef void FAR   *voidpf;
412    typedef void       *voidp;
413 #else
414    typedef Byte const *voidpc;
415    typedef Byte FAR   *voidpf;
416    typedef Byte       *voidp;
417 #endif
418 
419 #if HAVE_UNISTD_H
420 #  include <sys/types.h> /* for off_t */
421 #  include <unistd.h>    /* for SEEK_* and off_t */
422 #  ifdef VMS
423 #    include <unixio.h>   /* for off_t */
424 #  endif
425 #  define z_off_t off_t
426 #endif
427 #ifndef SEEK_SET
428 #  define SEEK_SET        0       /* Seek from beginning of file.  */
429 #  define SEEK_CUR        1       /* Seek from current position.  */
430 #  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
431 #endif
432 #ifndef z_off_t
433 #  define z_off_t long
434 #endif
435 
436 #if defined(__OS400__)
437 #  define NO_vsnprintf
438 #endif
439 
440 #if defined(__MVS__)
441 #  define NO_vsnprintf
442 #endif
443 
444 /* MVS linker does not support external names larger than 8 bytes */
445 #if defined(__MVS__)
446 #   pragma map(deflateInit_,"DEIN")
447 #   pragma map(deflateInit2_,"DEIN2")
448 #   pragma map(deflateEnd,"DEEND")
449 #   pragma map(deflateBound,"DEBND")
450 #   pragma map(inflateInit_,"ININ")
451 #   pragma map(inflateInit2_,"ININ2")
452 #   pragma map(inflateEnd,"INEND")
453 #   pragma map(inflateSync,"INSY")
454 #   pragma map(inflateSetDictionary,"INSEDI")
455 #   pragma map(compressBound,"CMBND")
456 #   pragma map(inflate_table,"INTABL")
457 #   pragma map(inflate_fast,"INFA")
458 #   pragma map(inflate_copyright,"INCOPY")
459 #endif
460 
461 #endif /* _ZCONF_H */
462 
463 #define ZLIB_VERSION "1.2.3"
464 #define ZLIB_VERNUM 0x1230
465 
466 /*
467      The 'zlib' compression library provides in-memory compression and
468   decompression functions, including integrity checks of the uncompressed
469   data.  This version of the library supports only one compression method
470   (deflation) but other algorithms will be added later and will have the same
471   stream interface.
472 
473      Compression can be done in a single step if the buffers are large
474   enough (for example if an input file is mmap'ed), or can be done by
475   repeated calls of the compression function.  In the latter case, the
476   application must provide more input and/or consume the output
477   (providing more output space) before each call.
478 
479      The compressed data format used by default by the in-memory functions is
480   the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
481   around a deflate stream, which is itself documented in RFC 1951.
482 
483      The library also supports reading and writing files in gzip (.gz) format
484   with an interface similar to that of stdio using the functions that start
485   with "gz".  The gzip format is different from the zlib format.  gzip is a
486   gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
487 
488      This library can optionally read and write gzip streams in memory as well.
489 
490      The zlib format was designed to be compact and fast for use in memory
491   and on communications channels.  The gzip format was designed for single-
492   file compression on file systems, has a larger header than zlib to maintain
493   directory information, and uses a different, slower check method than zlib.
494 
495      The library does not install any signal handler. The decoder checks
496   the consistency of the compressed data, so the library should never
497   crash even in case of corrupted input.
498 */
499 
500 typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
501 typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
502 
503 struct internal_state;
504 
505 typedef struct z_stream_s {
506     Bytef    *next_in;  /* next input byte */
507     uInt     avail_in;  /* number of bytes available at next_in */
508     uLong    total_in;  /* total nb of input bytes read so far */
509 
510     Bytef    *next_out; /* next output byte should be put there */
511     uInt     avail_out; /* remaining free space at next_out */
512     uLong    total_out; /* total nb of bytes output so far */
513 
514     char     *msg;      /* last error message, NULL if no error */
515     struct internal_state FAR *state; /* not visible by applications */
516 
517     alloc_func zalloc;  /* used to allocate the internal state */
518     free_func  zfree;   /* used to free the internal state */
519     voidpf     opaque;  /* private data object passed to zalloc and zfree */
520 
521     int     data_type;  /* best guess about the data type: binary or text */
522     uLong   adler;      /* adler32 value of the uncompressed data */
523     uLong   reserved;   /* reserved for future use */
524 } z_stream;
525 
526 typedef z_stream FAR *z_streamp;
527 
528                         /* constants */
529 
530 #define Z_NO_FLUSH      0
531 #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
532 #define Z_SYNC_FLUSH    2
533 #define Z_FULL_FLUSH    3
534 #define Z_FINISH        4
535 #define Z_BLOCK         5
536 /* Allowed flush values; see deflate() and inflate() below for details */
537 
538 #define Z_OK            0
539 #define Z_STREAM_END    1
540 #define Z_NEED_DICT     2
541 #define Z_ERRNO        (-1)
542 #define Z_STREAM_ERROR (-2)
543 #define Z_DATA_ERROR   (-3)
544 #define Z_MEM_ERROR    (-4)
545 #define Z_BUF_ERROR    (-5)
546 #define Z_VERSION_ERROR (-6)
547 /* Return codes for the compression/decompression functions. Negative
548  * values are errors, positive values are used for special but normal events.
549  */
550 
551 #define Z_NO_COMPRESSION         0
552 #define Z_BEST_SPEED             1
553 #define Z_BEST_COMPRESSION       9
554 #define Z_DEFAULT_COMPRESSION  (-1)
555 /* compression levels */
556 
557 #define Z_FILTERED            1
558 #define Z_HUFFMAN_ONLY        2
559 #define Z_RLE                 3
560 #define Z_FIXED               4
561 #define Z_DEFAULT_STRATEGY    0
562 /* compression strategy; see deflateInit2() below for details */
563 
564 #define Z_BINARY   0
565 #define Z_TEXT     1
566 #define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
567 #define Z_UNKNOWN  2
568 /* Possible values of the data_type field (though see inflate()) */
569 
570 #define Z_DEFLATED   8
571 /* The deflate compression method (the only one supported in this version) */
572 
573 #define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
574 
575 #define inflateInit2(strm, windowBits) \
576 	inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
577 
578 #endif /* _ZLIB_H */
579 
580 #ifndef _ZUTIL_H
581 #define _ZUTIL_H	1
582 
583 #if !_PACKAGE_ast && !defined(STDC)
584 #if defined(__STDC__)
585 #  include <stddef.h>
586 #endif
587 #  include <string.h>
588 #  include <stdlib.h>
589 #endif
590 
591 #ifndef local
592 #  define local static
593 #endif
594 /* compile with -Dlocal if your debugger can't find static symbols */
595 
596 typedef unsigned char  uch;
597 typedef uch FAR uchf;
598 typedef unsigned short ush;
599 typedef ush FAR ushf;
600 typedef unsigned long  ulg;
601 
602         /* common constants */
603 
604 #ifndef DEF_WBITS
605 #  define DEF_WBITS MAX_WBITS
606 #endif
607 /* default windowBits for decompression. MAX_WBITS is for compression only */
608 
609 #if MAX_MEM_LEVEL >= 8
610 #  define DEF_MEM_LEVEL 8
611 #else
612 #  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
613 #endif
614 /* default memLevel */
615 
616 #define STORED_BLOCK 0
617 #define STATIC_TREES 1
618 #define DYN_TREES    2
619 /* The three kinds of block type */
620 
621 #define MIN_MATCH  3
622 #define MAX_MATCH  258
623 /* The minimum and maximum match lengths */
624 
625 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
626 
627         /* target dependencies */
628 
629 #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
630 #  define OS_CODE  0x00
631 #  if defined(__TURBOC__) || defined(__BORLANDC__)
632 #    if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
633        /* Allow compilation with ANSI keywords only enabled */
634        void _Cdecl farfree( void *block );
635        void *_Cdecl farmalloc( unsigned long nbytes );
636 #    else
637 #      include <alloc.h>
638 #    endif
639 #  else /* MSC or DJGPP */
640 #    include <malloc.h>
641 #  endif
642 #endif
643 
644 #ifdef AMIGA
645 #  define OS_CODE  0x01
646 #endif
647 
648 #if defined(VAXC) || defined(VMS)
649 #  define OS_CODE  0x02
650 #  define F_OPEN(name, mode) \
651      fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
652 #endif
653 
654 #if defined(ATARI) || defined(atarist)
655 #  define OS_CODE  0x05
656 #endif
657 
658 #ifdef OS2
659 #  define OS_CODE  0x06
660 #  ifdef M_I86
661      #include <malloc.h>
662 #  endif
663 #endif
664 
665 #if defined(MACOS) || defined(TARGET_OS_MAC)
666 #  define OS_CODE  0x07
667 #  if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
668 #    include <unix.h> /* for fdopen */
669 #  else
670 #    ifndef fdopen
671 #      define fdopen(fd,mode) NULL /* No fdopen() */
672 #    endif
673 #  endif
674 #endif
675 
676 #ifdef TOPS20
677 #  define OS_CODE  0x0a
678 #endif
679 
680 #ifdef WIN32
681 #  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */
682 #    define OS_CODE  0x0b
683 #  endif
684 #endif
685 
686 #ifdef __50SERIES /* Prime/PRIMOS */
687 #  define OS_CODE  0x0f
688 #endif
689 
690 #if defined(_BEOS_) || defined(RISCOS)
691 #  define fdopen(fd,mode) NULL /* No fdopen() */
692 #endif
693 
694 #if (defined(_MSC_VER) && (_MSC_VER > 600))
695 #  if defined(_WIN32_WCE)
696 #    define fdopen(fd,mode) NULL /* No fdopen() */
697 #    ifndef _PTRDIFF_T_DEFINED
698        typedef int ptrdiff_t;
699 #      define _PTRDIFF_T_DEFINED
700 #    endif
701 #  else
702 #    define fdopen(fd,type)  _fdopen(fd,type)
703 #  endif
704 #endif
705 
706         /* common defaults */
707 
708 #ifndef OS_CODE
709 #  define OS_CODE  0x03  /* assume Unix */
710 #endif
711 
712 #ifndef F_OPEN
713 #  define F_OPEN(name, mode) fopen((name), (mode))
714 #endif
715 
716          /* functions */
717 
718 #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
719 #  ifndef HAVE_VSNPRINTF
720 #    define HAVE_VSNPRINTF
721 #  endif
722 #endif
723 #if defined(__CYGWIN__)
724 #  ifndef HAVE_VSNPRINTF
725 #    define HAVE_VSNPRINTF
726 #  endif
727 #endif
728 #ifndef HAVE_VSNPRINTF
729 #  ifdef MSDOS
730      /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
731         but for now we just assume it doesn't. */
732 #    define NO_vsnprintf
733 #  endif
734 #  ifdef __TURBOC__
735 #    define NO_vsnprintf
736 #  endif
737 #  ifdef WIN32
738      /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
739 #    if !defined(vsnprintf) && !defined(NO_vsnprintf)
740 #      define vsnprintf _vsnprintf
741 #    endif
742 #  endif
743 #  ifdef __SASC
744 #    define NO_vsnprintf
745 #  endif
746 #endif
747 #ifdef VMS
748 #  define NO_vsnprintf
749 #endif
750 
751 #if defined(pyr)
752 #  define NO_MEMCPY
753 #endif
754 #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
755  /* Use our own functions for small and medium model with MSC <= 5.0.
756   * You may have to use the same strategy for Borland C (untested).
757   * The __SC__ check is for Symantec.
758   */
759 #  define NO_MEMCPY
760 #endif
761 #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
762 #  define HAVE_MEMCPY
763 #endif
764 #ifdef HAVE_MEMCPY
765 #  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
766 #    define zmemcpy _fmemcpy
767 #    define zmemcmp _fmemcmp
768 #    define zmemzero(dest, len) _fmemset(dest, 0, len)
769 #  else
770 #    define zmemcpy memcpy
771 #    define zmemcmp memcmp
772 #    define zmemzero(dest, len) memset(dest, 0, len)
773 #  endif
774 #else
775    extern void zmemcpy  OF((Bytef* dest, const Bytef* source, uInt len));
776    extern int  zmemcmp  OF((const Bytef* s1, const Bytef* s2, uInt len));
777    extern void zmemzero OF((Bytef* dest, uInt len));
778 #endif
779 
780 /* Diagnostic functions */
781 #ifdef Z_DEBUG
782 #  include <stdio.h>
783    extern int z_verbose;
784    extern void z_error    OF((char *m));
785 #  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
786 #  define Trace(x) {if (z_verbose>=0) fprintf x ;}
787 #  define Tracev(x) {if (z_verbose>0) fprintf x ;}
788 #  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
789 #  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
790 #  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
791 #else
792 #  define Assert(cond,msg)
793 #  define Trace(x)
794 #  define Tracev(x)
795 #  define Tracevv(x)
796 #  define Tracec(c,x)
797 #  define Tracecv(c,x)
798 #endif
799 
800 
801 voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
802 void   zcfree  OF((voidpf opaque, voidpf ptr));
803 
804 #define ZALLOC(strm, items, size) \
805            (*((strm)->zalloc))((strm)->opaque, (items), (size))
806 #define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
807 #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
808 #endif /* _ZUTIL_H */
809 
810 #ifndef _ZUTIL_C
811 #define _ZUTIL_C
812 
813 #if 0 && !_PACKAGE_ast && !defined(STDC)
814 extern void exit OF((int));
815 #endif
816 
817 #ifndef HAVE_MEMCPY
818 
819 void zmemcpy(dest, source, len)
820     Bytef* dest;
821     const Bytef* source;
822     uInt  len;
823 {
824     if (len == 0) return;
825     do {
826         *dest++ = *source++; /* ??? to be unrolled */
827     } while (--len != 0);
828 }
829 
830 int zmemcmp(s1, s2, len)
831     const Bytef* s1;
832     const Bytef* s2;
833     uInt  len;
834 {
835     uInt j;
836 
837     for (j = 0; j < len; j++) {
838         if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
839     }
840     return 0;
841 }
842 
843 void zmemzero(dest, len)
844     Bytef* dest;
845     uInt  len;
846 {
847     if (len == 0) return;
848     do {
849         *dest++ = 0;  /* ??? to be unrolled */
850     } while (--len != 0);
851 }
852 #endif
853 
854 
855 #ifdef SYS16BIT
856 
857 #ifdef __TURBOC__
858 /* Turbo C in 16-bit mode */
859 
860 #  define MY_ZCALLOC
861 
862 /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
863  * and farmalloc(64K) returns a pointer with an offset of 8, so we
864  * must fix the pointer. Warning: the pointer must be put back to its
865  * original form in order to free it, use zcfree().
866  */
867 
868 #define MAX_PTR 10
869 /* 10*64K = 640K */
870 
871 local int next_ptr = 0;
872 
873 typedef struct ptr_table_s {
874     voidpf org_ptr;
875     voidpf new_ptr;
876 } ptr_table;
877 
878 local ptr_table table[MAX_PTR];
879 /* This table is used to remember the original form of pointers
880  * to large buffers (64K). Such pointers are normalized with a zero offset.
881  * Since MSDOS is not a preemptive multitasking OS, this table is not
882  * protected from concurrent access. This hack doesn't work anyway on
883  * a protected system like OS/2. Use Microsoft C instead.
884  */
885 
886 voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
887 {
888     voidpf buf = opaque; /* just to make some compilers happy */
889     ulg bsize = (ulg)items*size;
890 
891     /* If we allocate less than 65520 bytes, we assume that farmalloc
892      * will return a usable pointer which doesn't have to be normalized.
893      */
894     if (bsize < 65520L) {
895         buf = farmalloc(bsize);
896         if (*(ush*)&buf != 0) return buf;
897     } else {
898         buf = farmalloc(bsize + 16L);
899     }
900     if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
901     table[next_ptr].org_ptr = buf;
902 
903     /* Normalize the pointer to seg:0 */
904     *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
905     *(ush*)&buf = 0;
906     table[next_ptr++].new_ptr = buf;
907     return buf;
908 }
909 
910 void  zcfree (voidpf opaque, voidpf ptr)
911 {
912     int n;
913     if (*(ush*)&ptr != 0) { /* object < 64K */
914         farfree(ptr);
915         return;
916     }
917     /* Find the original pointer */
918     for (n = 0; n < next_ptr; n++) {
919         if (ptr != table[n].new_ptr) continue;
920 
921         farfree(table[n].org_ptr);
922         while (++n < next_ptr) {
923             table[n-1] = table[n];
924         }
925         next_ptr--;
926         return;
927     }
928     ptr = opaque; /* just to make some compilers happy */
929     Assert(0, "zcfree: ptr not found");
930 }
931 
932 #endif /* __TURBOC__ */
933 
934 
935 #ifdef M_I86
936 /* Microsoft C in 16-bit mode */
937 
938 #  define MY_ZCALLOC
939 
940 #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
941 #  define _halloc  halloc
942 #  define _hfree   hfree
943 #endif
944 
945 voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
946 {
947     if (opaque) opaque = 0; /* to make compiler happy */
948     return _halloc((long)items, size);
949 }
950 
951 void  zcfree (voidpf opaque, voidpf ptr)
952 {
953     if (opaque) opaque = 0; /* to make compiler happy */
954     _hfree(ptr);
955 }
956 
957 #endif /* M_I86 */
958 
959 #endif /* SYS16BIT */
960 
961 
962 #ifndef MY_ZCALLOC /* Any system without a special alloc function */
963 
964 #if 0 && !_PACKAGE_ast
965 #ifndef STDC
966 extern voidp  malloc OF((uInt size));
967 extern voidp  calloc OF((uInt items, uInt size));
968 extern void   free   OF((voidpf ptr));
969 #endif
970 #endif
971 
972 voidpf zcalloc (opaque, items, size)
973     voidpf opaque;
974     unsigned items;
975     unsigned size;
976 {
977     if (opaque) items += size - size; /* make compiler happy */
978     return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
979                               (voidpf)calloc(items, size);
980 }
981 
982 void  zcfree (opaque, ptr)
983     voidpf opaque;
984     voidpf ptr;
985 {
986     free(ptr);
987     if (opaque) return; /* make compiler happy */
988 }
989 
990 #endif /* MY_ZCALLOC */
991 
992 #endif /* _ZUTIL_C */
993 
994 #ifndef _CRC32_H
995 #define _CRC32_H	1
996 
997 /* crc32.h -- tables for rapid CRC calculation
998  * Generated automatically by crc32.c
999  */
1000 
1001 #ifndef TBLS
1002 #define TBLS	1
1003 #endif
1004 
1005 local const unsigned long FAR crc_table[TBLS][256] =
1006 {
1007   {
1008     0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
1009     0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
1010     0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
1011     0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
1012     0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
1013     0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
1014     0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
1015     0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
1016     0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
1017     0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
1018     0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
1019     0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
1020     0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
1021     0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
1022     0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
1023     0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
1024     0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
1025     0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
1026     0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
1027     0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
1028     0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
1029     0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
1030     0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
1031     0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
1032     0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
1033     0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
1034     0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
1035     0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
1036     0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
1037     0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
1038     0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
1039     0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
1040     0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
1041     0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
1042     0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
1043     0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
1044     0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
1045     0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
1046     0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
1047     0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
1048     0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
1049     0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
1050     0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
1051     0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
1052     0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
1053     0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
1054     0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
1055     0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
1056     0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
1057     0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
1058     0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
1059     0x2d02ef8d
1060   },
1061 };
1062 
1063 #endif /* _CRC32_H */
1064 
1065 #ifndef _CRC32_C
1066 #define _CRC32_C	1
1067 
1068 /* ========================================================================= */
1069 #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
1070 #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
1071 
1072 /* ========================================================================= */
1073 unsigned long ZEXPORT crc32(crc, buf, len)
1074     unsigned long crc;
1075     const unsigned char FAR *buf;
1076     unsigned len;
1077 {
1078     if (buf == Z_NULL) return 0;
1079 
1080 #ifdef DYNAMIC_CRC_TABLE
1081     if (crc_table_empty)
1082         make_crc_table();
1083 #endif /* DYNAMIC_CRC_TABLE */
1084 
1085 #ifdef BYFOUR
1086     if (sizeof(void *) == sizeof(ptrdiff_t)) {
1087         u4 endian;
1088 
1089         endian = 1;
1090         if (*((unsigned char *)(&endian)))
1091             return crc32_little(crc, buf, len);
1092         else
1093             return crc32_big(crc, buf, len);
1094     }
1095 #endif /* BYFOUR */
1096     crc = crc ^ 0xffffffff;
1097     while (len >= 8) {
1098         DO8;
1099         len -= 8;
1100     }
1101     if (len) do {
1102         DO1;
1103     } while (--len);
1104     return crc ^ 0xffffffff;
1105 }
1106 
1107 #undef	DO1
1108 #undef	DO8
1109 
1110 #endif /* _CRC32_C */
1111 
1112 #ifndef _ADLER32_C
1113 #define _ADLER32_C	1
1114 
1115 #define BASE 65521    /* largest prime smaller than 65536 */
1116 #define NMAX 5552
1117 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
1118 
1119 #define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
1120 #define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
1121 #define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
1122 #define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
1123 #define DO16(buf)   DO8(buf,0); DO8(buf,8);
1124 
1125 /* use NO_DIVIDE if your processor does not do division in hardware */
1126 #ifdef NO_DIVIDE
1127 #  define MOD(a) \
1128     do { \
1129         if (a >= (BASE << 16)) a -= (BASE << 16); \
1130         if (a >= (BASE << 15)) a -= (BASE << 15); \
1131         if (a >= (BASE << 14)) a -= (BASE << 14); \
1132         if (a >= (BASE << 13)) a -= (BASE << 13); \
1133         if (a >= (BASE << 12)) a -= (BASE << 12); \
1134         if (a >= (BASE << 11)) a -= (BASE << 11); \
1135         if (a >= (BASE << 10)) a -= (BASE << 10); \
1136         if (a >= (BASE << 9)) a -= (BASE << 9); \
1137         if (a >= (BASE << 8)) a -= (BASE << 8); \
1138         if (a >= (BASE << 7)) a -= (BASE << 7); \
1139         if (a >= (BASE << 6)) a -= (BASE << 6); \
1140         if (a >= (BASE << 5)) a -= (BASE << 5); \
1141         if (a >= (BASE << 4)) a -= (BASE << 4); \
1142         if (a >= (BASE << 3)) a -= (BASE << 3); \
1143         if (a >= (BASE << 2)) a -= (BASE << 2); \
1144         if (a >= (BASE << 1)) a -= (BASE << 1); \
1145         if (a >= BASE) a -= BASE; \
1146     } while (0)
1147 #  define MOD4(a) \
1148     do { \
1149         if (a >= (BASE << 4)) a -= (BASE << 4); \
1150         if (a >= (BASE << 3)) a -= (BASE << 3); \
1151         if (a >= (BASE << 2)) a -= (BASE << 2); \
1152         if (a >= (BASE << 1)) a -= (BASE << 1); \
1153         if (a >= BASE) a -= BASE; \
1154     } while (0)
1155 #else
1156 #  define MOD(a) a %= BASE
1157 #  define MOD4(a) a %= BASE
1158 #endif
1159 
1160 /* ========================================================================= */
1161 uLong ZEXPORT adler32(adler, buf, len)
1162     uLong adler;
1163     const Bytef *buf;
1164     uInt len;
1165 {
1166     unsigned long sum2;
1167     unsigned n;
1168 
1169     /* split Adler-32 into component sums */
1170     sum2 = (adler >> 16) & 0xffff;
1171     adler &= 0xffff;
1172 
1173     /* in case user likes doing a byte at a time, keep it fast */
1174     if (len == 1) {
1175         adler += buf[0];
1176         if (adler >= BASE)
1177             adler -= BASE;
1178         sum2 += adler;
1179         if (sum2 >= BASE)
1180             sum2 -= BASE;
1181         return adler | (sum2 << 16);
1182     }
1183 
1184     /* initial Adler-32 value (deferred check for len == 1 speed) */
1185     if (buf == Z_NULL)
1186         return 1L;
1187 
1188     /* in case short lengths are provided, keep it somewhat fast */
1189     if (len < 16) {
1190         while (len--) {
1191             adler += *buf++;
1192             sum2 += adler;
1193         }
1194         if (adler >= BASE)
1195             adler -= BASE;
1196         MOD4(sum2);             /* only added so many BASE's */
1197         return adler | (sum2 << 16);
1198     }
1199 
1200     /* do length NMAX blocks -- requires just one modulo operation */
1201     while (len >= NMAX) {
1202         len -= NMAX;
1203         n = NMAX / 16;          /* NMAX is divisible by 16 */
1204         do {
1205             DO16(buf);          /* 16 sums unrolled */
1206             buf += 16;
1207         } while (--n);
1208         MOD(adler);
1209         MOD(sum2);
1210     }
1211 
1212     /* do remaining bytes (less than NMAX, still just one modulo) */
1213     if (len) {                  /* avoid modulos if none remaining */
1214         while (len >= 16) {
1215             len -= 16;
1216             DO16(buf);
1217             buf += 16;
1218         }
1219         while (len--) {
1220             adler += *buf++;
1221             sum2 += adler;
1222         }
1223         MOD(adler);
1224         MOD(sum2);
1225     }
1226 
1227     /* return recombined sums */
1228     return adler | (sum2 << 16);
1229 }
1230 
1231 #endif /* _ADLER32_C */
1232 
1233 #ifndef _DEFLATE_H
1234 #define _DEFLATE_H	1
1235 
1236 /* ===========================================================================
1237  * Internal compression state.
1238  */
1239 
1240 #define LENGTH_CODES 29
1241 /* number of length codes, not counting the special END_BLOCK code */
1242 
1243 #define LITERALS  256
1244 /* number of literal bytes 0..255 */
1245 
1246 #define L_CODES (LITERALS+1+LENGTH_CODES)
1247 /* number of Literal or Length codes, including the END_BLOCK code */
1248 
1249 #define D_CODES   30
1250 /* number of distance codes */
1251 
1252 #define BL_CODES  19
1253 /* number of codes used to transfer the bit lengths */
1254 
1255 #define HEAP_SIZE (2*L_CODES+1)
1256 /* maximum heap size */
1257 
1258 #define MAX_BITS 15
1259 /* All codes must not exceed MAX_BITS bits */
1260 
1261 #define INIT_STATE    42
1262 #define EXTRA_STATE   69
1263 #define NAME_STATE    73
1264 #define COMMENT_STATE 91
1265 #define HCRC_STATE   103
1266 #define BUSY_STATE   113
1267 #define FINISH_STATE 666
1268 /* Stream status */
1269 
1270 
1271 /* Data structure describing a single value and its code string. */
1272 typedef struct ct_data_s {
1273     union {
1274         ush  freq;       /* frequency count */
1275         ush  code;       /* bit string */
1276     } fc;
1277     union {
1278         ush  dad;        /* father node in Huffman tree */
1279         ush  len;        /* length of bit string */
1280     } dl;
1281 } FAR ct_data;
1282 
1283 #define Freq fc.freq
1284 #define Code fc.code
1285 #define Dad  dl.dad
1286 #define Len  dl.len
1287 
1288 typedef struct static_tree_desc_s  static_tree_desc;
1289 
1290 typedef struct tree_desc_s {
1291     ct_data *dyn_tree;           /* the dynamic tree */
1292     int     max_code;            /* largest code with non zero frequency */
1293     static_tree_desc *stat_desc; /* the corresponding static tree */
1294 } FAR tree_desc;
1295 
1296 typedef ush Pos;
1297 typedef Pos FAR Posf;
1298 typedef unsigned IPos;
1299 
1300 /* A Pos is an index in the character window. We use short instead of int to
1301  * save space in the various tables. IPos is used only for parameter passing.
1302  */
1303 
1304 typedef struct internal_state {
1305     z_streamp strm;      /* pointer back to this zlib stream */
1306     int   status;        /* as the name implies */
1307     Bytef *pending_buf;  /* output still pending */
1308     ulg   pending_buf_size; /* size of pending_buf */
1309     Bytef *pending_out;  /* next pending byte to output to the stream */
1310     uInt   pending;      /* nb of bytes in the pending buffer */
1311     int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
1312     gz_headerp  gzhead;  /* gzip header information to write */
1313     uInt   gzindex;      /* where in extra, name, or comment */
1314     Byte  method;        /* STORED (for zip only) or DEFLATED */
1315     int   last_flush;    /* value of flush param for previous deflate call */
1316 
1317                 /* used by deflate.c: */
1318 
1319     uInt  w_size;        /* LZ77 window size (32K by default) */
1320     uInt  w_bits;        /* log2(w_size)  (8..16) */
1321     uInt  w_mask;        /* w_size - 1 */
1322 
1323     Bytef *window;
1324     /* Sliding window. Input bytes are read into the second half of the window,
1325      * and move to the first half later to keep a dictionary of at least wSize
1326      * bytes. With this organization, matches are limited to a distance of
1327      * wSize-MAX_MATCH bytes, but this ensures that IO is always
1328      * performed with a length multiple of the block size. Also, it limits
1329      * the window size to 64K, which is quite useful on MSDOS.
1330      * To do: use the user input buffer as sliding window.
1331      */
1332 
1333     ulg window_size;
1334     /* Actual size of window: 2*wSize, except when the user input buffer
1335      * is directly used as sliding window.
1336      */
1337 
1338     Posf *prev;
1339     /* Link to older string with same hash index. To limit the size of this
1340      * array to 64K, this link is maintained only for the last 32K strings.
1341      * An index in this array is thus a window index modulo 32K.
1342      */
1343 
1344     Posf *head; /* Heads of the hash chains or NIL. */
1345 
1346     uInt  ins_h;          /* hash index of string to be inserted */
1347     uInt  hash_size;      /* number of elements in hash table */
1348     uInt  hash_bits;      /* log2(hash_size) */
1349     uInt  hash_mask;      /* hash_size-1 */
1350 
1351     uInt  hash_shift;
1352     /* Number of bits by which ins_h must be shifted at each input
1353      * step. It must be such that after MIN_MATCH steps, the oldest
1354      * byte no longer takes part in the hash key, that is:
1355      *   hash_shift * MIN_MATCH >= hash_bits
1356      */
1357 
1358     long block_start;
1359     /* Window position at the beginning of the current output block. Gets
1360      * negative when the window is moved backwards.
1361      */
1362 
1363     uInt match_length;           /* length of best match */
1364     IPos prev_match;             /* previous match */
1365     int match_available;         /* set if previous match exists */
1366     uInt strstart;               /* start of string to insert */
1367     uInt match_start;            /* start of matching string */
1368     uInt lookahead;              /* number of valid bytes ahead in window */
1369 
1370     uInt prev_length;
1371     /* Length of the best match at previous step. Matches not greater than this
1372      * are discarded. This is used in the lazy match evaluation.
1373      */
1374 
1375     uInt max_chain_length;
1376     /* To speed up deflation, hash chains are never searched beyond this
1377      * length.  A higher limit improves compression ratio but degrades the
1378      * speed.
1379      */
1380 
1381     uInt max_lazy_match;
1382     /* Attempt to find a better match only when the current match is strictly
1383      * smaller than this value. This mechanism is used only for compression
1384      * levels >= 4.
1385      */
1386 #   define max_insert_length  max_lazy_match
1387     /* Insert new strings in the hash table only if the match length is not
1388      * greater than this length. This saves time but degrades compression.
1389      * max_insert_length is used only for compression levels <= 3.
1390      */
1391 
1392     int level;    /* compression level (1..9) */
1393     int strategy; /* favor or force Huffman coding*/
1394 
1395     uInt good_match;
1396     /* Use a faster search when the previous match is longer than this */
1397 
1398     int nice_match; /* Stop searching when current match exceeds this */
1399 
1400                 /* used by trees.c: */
1401     /* Didn't use ct_data typedef below to supress compiler warning */
1402     struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
1403     struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
1404     struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
1405 
1406     struct tree_desc_s l_desc;               /* desc. for literal tree */
1407     struct tree_desc_s d_desc;               /* desc. for distance tree */
1408     struct tree_desc_s bl_desc;              /* desc. for bit length tree */
1409 
1410     ush bl_count[MAX_BITS+1];
1411     /* number of codes at each bit length for an optimal tree */
1412 
1413     int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
1414     int heap_len;               /* number of elements in the heap */
1415     int heap_max;               /* element of largest frequency */
1416     /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
1417      * The same heap array is used to build all trees.
1418      */
1419 
1420     uch depth[2*L_CODES+1];
1421     /* Depth of each subtree used as tie breaker for trees of equal frequency
1422      */
1423 
1424     uchf *l_buf;          /* buffer for literals or lengths */
1425 
1426     uInt  lit_bufsize;
1427     /* Size of match buffer for literals/lengths.  There are 4 reasons for
1428      * limiting lit_bufsize to 64K:
1429      *   - frequencies can be kept in 16 bit counters
1430      *   - if compression is not successful for the first block, all input
1431      *     data is still in the window so we can still emit a stored block even
1432      *     when input comes from standard input.  (This can also be done for
1433      *     all blocks if lit_bufsize is not greater than 32K.)
1434      *   - if compression is not successful for a file smaller than 64K, we can
1435      *     even emit a stored file instead of a stored block (saving 5 bytes).
1436      *     This is applicable only for zip (not gzip or zlib).
1437      *   - creating new Huffman trees less frequently may not provide fast
1438      *     adaptation to changes in the input data statistics. (Take for
1439      *     example a binary file with poorly compressible code followed by
1440      *     a highly compressible string table.) Smaller buffer sizes give
1441      *     fast adaptation but have of course the overhead of transmitting
1442      *     trees more frequently.
1443      *   - I can't count above 4
1444      */
1445 
1446     uInt last_lit;      /* running index in l_buf */
1447 
1448     ushf *d_buf;
1449     /* Buffer for distances. To simplify the code, d_buf and l_buf have
1450      * the same number of elements. To use different lengths, an extra flag
1451      * array would be necessary.
1452      */
1453 
1454     ulg opt_len;        /* bit length of current block with optimal trees */
1455     ulg static_len;     /* bit length of current block with static trees */
1456     uInt matches;       /* number of string matches in current block */
1457     int last_eob_len;   /* bit length of EOB code for last block */
1458 
1459 #ifdef Z_DEBUG
1460     ulg compressed_len; /* total bit length of compressed file mod 2^32 */
1461     ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
1462 #endif
1463 
1464     ush bi_buf;
1465     /* Output buffer. bits are inserted starting at the bottom (least
1466      * significant bits).
1467      */
1468     int bi_valid;
1469     /* Number of valid bits in bi_buf.  All bits above the last valid bit
1470      * are always zero.
1471      */
1472 
1473 } FAR deflate_state;
1474 
1475 /* Output a byte on the stream.
1476  * IN assertion: there is enough room in pending_buf.
1477  */
1478 #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
1479 
1480 
1481 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
1482 /* Minimum amount of lookahead, except at the end of the input file.
1483  * See deflate.c for comments about the MIN_MATCH+1.
1484  */
1485 
1486 #define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
1487 /* In order to simplify the code, particularly on 16 bit machines, match
1488  * distances are limited to MAX_DIST instead of WSIZE.
1489  */
1490 
1491         /* in trees.c */
1492 void _tr_init         OF((deflate_state *s));
1493 int  _tr_tally        OF((deflate_state *s, unsigned dist, unsigned lc));
1494 void _tr_flush_block  OF((deflate_state *s, charf *buf, ulg stored_len,
1495                           int eof));
1496 void _tr_align        OF((deflate_state *s));
1497 void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
1498                           int eof));
1499 
1500 #define d_code(dist) \
1501    ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
1502 /* Mapping from a distance to a distance code. dist is the distance - 1 and
1503  * must not have side effects. _dist_code[256] and _dist_code[257] are never
1504  * used.
1505  */
1506 
1507 #ifndef Z_DEBUG
1508 /* Inline versions of _tr_tally for speed: */
1509 
1510 #if defined(GEN_TREES_H) || !defined(STDC)
1511   extern uch _length_code[];
1512   extern uch _dist_code[];
1513 #else
1514   extern const uch _length_code[];
1515   extern const uch _dist_code[];
1516 #endif
1517 
1518 # define _tr_tally_lit(s, c, flush) \
1519   { uch cc = (c); \
1520     s->d_buf[s->last_lit] = 0; \
1521     s->l_buf[s->last_lit++] = cc; \
1522     s->dyn_ltree[cc].Freq++; \
1523     flush = (s->last_lit == s->lit_bufsize-1); \
1524    }
1525 # define _tr_tally_dist(s, distance, length, flush) \
1526   { uch len = (length); \
1527     ush dist = (distance); \
1528     s->d_buf[s->last_lit] = dist; \
1529     s->l_buf[s->last_lit++] = len; \
1530     dist--; \
1531     s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
1532     s->dyn_dtree[d_code(dist)].Freq++; \
1533     flush = (s->last_lit == s->lit_bufsize-1); \
1534   }
1535 #else
1536 # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
1537 # define _tr_tally_dist(s, distance, length, flush) \
1538               flush = _tr_tally(s, distance, length)
1539 #endif
1540 
1541 #endif /* _DEFLATE_H */
1542 
1543 #ifndef _INFTREES_H
1544 #define _INFTREES_H	1
1545 
1546 typedef struct {
1547     unsigned char op;           /* operation, extra bits, table bits */
1548     unsigned char bits;         /* bits in this part of the code */
1549     unsigned short val;         /* offset in table or code value */
1550 } code;
1551 
1552 /* op values as set by inflate_table():
1553     00000000 - literal
1554     0000tttt - table link, tttt != 0 is the number of table index bits
1555     0001eeee - length or distance, eeee is the number of extra bits
1556     01100000 - end of block
1557     01000000 - invalid code
1558  */
1559 
1560 /* Maximum size of dynamic tree.  The maximum found in a long but non-
1561    exhaustive search was 1444 code structures (852 for length/literals
1562    and 592 for distances, the latter actually the result of an
1563    exhaustive search).  The true maximum is not known, but the value
1564    below is more than safe. */
1565 #define ENOUGH 2048
1566 #define MAXD 592
1567 
1568 /* Type of code to build for inftable() */
1569 typedef enum {
1570     CODES,
1571     LENS,
1572     DISTS
1573 } codetype;
1574 
1575 #endif /* _INFTREES_H */
1576 
1577 #ifndef _INFLATE_H
1578 #define _INFLATE_H	1
1579 
1580 /* Possible inflate modes between inflate() calls */
1581 typedef enum {
1582     HEAD,       /* i: waiting for magic header */
1583     FLAGS,      /* i: waiting for method and flags (gzip) */
1584     TIME,       /* i: waiting for modification time (gzip) */
1585     OS,         /* i: waiting for extra flags and operating system (gzip) */
1586     EXLEN,      /* i: waiting for extra length (gzip) */
1587     EXTRA,      /* i: waiting for extra bytes (gzip) */
1588     NAME,       /* i: waiting for end of file name (gzip) */
1589     COMMENT,    /* i: waiting for end of comment (gzip) */
1590     HCRC,       /* i: waiting for header crc (gzip) */
1591     DICTID,     /* i: waiting for dictionary check value */
1592     DICT,       /* waiting for inflateSetDictionary() call */
1593         TYPE,       /* i: waiting for type bits, including last-flag bit */
1594         TYPEDO,     /* i: same, but skip check to exit inflate on new block */
1595         STORED,     /* i: waiting for stored size (length and complement) */
1596         COPY,       /* i/o: waiting for input or output to copy stored block */
1597         TABLE,      /* i: waiting for dynamic block table lengths */
1598         LENLENS,    /* i: waiting for code length code lengths */
1599         CODELENS,   /* i: waiting for length/lit and distance code lengths */
1600             LEN,        /* i: waiting for length/lit code */
1601             LENEXT,     /* i: waiting for length extra bits */
1602             DIST,       /* i: waiting for distance code */
1603             DISTEXT,    /* i: waiting for distance extra bits */
1604             MATCH,      /* o: waiting for output space to copy string */
1605             LIT,        /* o: waiting for output space to write literal */
1606     CHECK,      /* i: waiting for 32-bit check value */
1607     LENGTH,     /* i: waiting for 32-bit length (gzip) */
1608     DONE,       /* finished check, done -- remain here until reset */
1609     BAD,        /* got a data error -- remain here until reset */
1610     MEM,        /* got an inflate() memory error -- remain here until reset */
1611     SYNC        /* looking for synchronization bytes to restart inflate() */
1612 } inflate_mode;
1613 
1614 /*
1615     State transitions between above modes -
1616 
1617     (most modes can go to the BAD or MEM mode -- not shown for clarity)
1618 
1619     Process header:
1620         HEAD -> (gzip) or (zlib)
1621         (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
1622         NAME -> COMMENT -> HCRC -> TYPE
1623         (zlib) -> DICTID or TYPE
1624         DICTID -> DICT -> TYPE
1625     Read deflate blocks:
1626             TYPE -> STORED or TABLE or LEN or CHECK
1627             STORED -> COPY -> TYPE
1628             TABLE -> LENLENS -> CODELENS -> LEN
1629     Read deflate codes:
1630                 LEN -> LENEXT or LIT or TYPE
1631                 LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
1632                 LIT -> LEN
1633     Process trailer:
1634         CHECK -> LENGTH -> DONE
1635  */
1636 
1637 /* state maintained between inflate() calls.  Approximately 7K bytes. */
1638 struct inflate_state {
1639     inflate_mode mode;          /* current inflate mode */
1640     int last;                   /* true if processing last block */
1641     int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip */
1642     int havedict;               /* true if dictionary provided */
1643     int flags;                  /* gzip header method and flags (0 if zlib) */
1644     unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
1645     unsigned long check;        /* protected copy of check value */
1646     unsigned long total;        /* protected copy of output count */
1647     gz_headerp head;            /* where to save gzip header information */
1648         /* sliding window */
1649     unsigned wbits;             /* log base 2 of requested window size */
1650     unsigned wsize;             /* window size or zero if not using window */
1651     unsigned whave;             /* valid bytes in the window */
1652     unsigned write;             /* window write index */
1653     unsigned char FAR *window;  /* allocated sliding window, if needed */
1654         /* bit accumulator */
1655     unsigned long hold;         /* input bit accumulator */
1656     unsigned bits;              /* number of bits in "in" */
1657         /* for string and stored block copying */
1658     unsigned length;            /* literal or length of data to copy */
1659     unsigned offset;            /* distance back to copy string from */
1660         /* for table and code decoding */
1661     unsigned extra;             /* extra bits needed */
1662         /* fixed and dynamic code tables */
1663     code const FAR *lencode;    /* starting table for length/literal codes */
1664     code const FAR *distcode;   /* starting table for distance codes */
1665     unsigned lenbits;           /* index bits for lencode */
1666     unsigned distbits;          /* index bits for distcode */
1667         /* dynamic table building */
1668     unsigned ncode;             /* number of code length code lengths */
1669     unsigned nlen;              /* number of length code lengths */
1670     unsigned ndist;             /* number of distance code lengths */
1671     unsigned have;              /* number of code lengths in lens[] */
1672     code FAR *next;             /* next available space in codes[] */
1673     unsigned short lens[320];   /* temporary storage for code lengths */
1674     unsigned short work[288];   /* work area for code table building */
1675     code codes[ENOUGH];         /* space for code tables */
1676 };
1677 #endif /* _INFLATE_H */
1678 
1679 #ifndef _INFTREES_C
1680 #define _INFTREES_C	1
1681 
1682 #define MAXBITS 15
1683 
1684 const char inflate_copyright[] =
1685    " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
1686 /*
1687   If you use the zlib library in a product, an acknowledgment is welcome
1688   in the documentation of your product. If for some reason you cannot
1689   include such an acknowledgment, I would appreciate that you keep this
1690   copyright string in the executable of your product.
1691  */
1692 
1693 /*
1694    Build a set of tables to decode the provided canonical Huffman code.
1695    The code lengths are lens[0..codes-1].  The result starts at *table,
1696    whose indices are 0..2^bits-1.  work is a writable array of at least
1697    lens shorts, which is used as a work area.  type is the type of code
1698    to be generated, CODES, LENS, or DISTS.  On return, zero is success,
1699    -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
1700    on return points to the next available entry's address.  bits is the
1701    requested root table index bits, and on return it is the actual root
1702    table index bits.  It will differ if the request is greater than the
1703    longest code or if it is less than the shortest code.
1704  */
1705 int inflate_table(type, lens, codes, table, bits, work)
1706 codetype type;
1707 unsigned short FAR *lens;
1708 unsigned codes;
1709 code FAR * FAR *table;
1710 unsigned FAR *bits;
1711 unsigned short FAR *work;
1712 {
1713     unsigned len;               /* a code's length in bits */
1714     unsigned sym;               /* index of code symbols */
1715     unsigned min, max;          /* minimum and maximum code lengths */
1716     unsigned root;              /* number of index bits for root table */
1717     unsigned curr;              /* number of index bits for current table */
1718     unsigned drop;              /* code bits to drop for sub-table */
1719     int left;                   /* number of prefix codes available */
1720     unsigned used;              /* code entries in table used */
1721     unsigned huff;              /* Huffman code */
1722     unsigned incr;              /* for incrementing code, index */
1723     unsigned fill;              /* index for replicating entries */
1724     unsigned low;               /* low bits for current root entry */
1725     unsigned mask;              /* mask for low root bits */
1726     code this;                  /* table entry for duplication */
1727     code FAR *next;             /* next available space in table */
1728     const unsigned short FAR *base;     /* base value table to use */
1729     const unsigned short FAR *extra;    /* extra bits table to use */
1730     int end;                    /* use base and extra for symbol > end */
1731     unsigned short count[MAXBITS+1];    /* number of codes of each length */
1732     unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
1733     static const unsigned short lbase[31] = { /* Length codes 257..285 base */
1734         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
1735         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
1736     static const unsigned short lext[31] = { /* Length codes 257..285 extra */
1737         16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
1738         19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
1739     static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
1740         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
1741         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
1742         8193, 12289, 16385, 24577, 0, 0};
1743     static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
1744         16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
1745         23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
1746         28, 28, 29, 29, 64, 64};
1747 
1748     /*
1749        Process a set of code lengths to create a canonical Huffman code.  The
1750        code lengths are lens[0..codes-1].  Each length corresponds to the
1751        symbols 0..codes-1.  The Huffman code is generated by first sorting the
1752        symbols by length from short to long, and retaining the symbol order
1753        for codes with equal lengths.  Then the code starts with all zero bits
1754        for the first code of the shortest length, and the codes are integer
1755        increments for the same length, and zeros are appended as the length
1756        increases.  For the deflate format, these bits are stored backwards
1757        from their more natural integer increment ordering, and so when the
1758        decoding tables are built in the large loop below, the integer codes
1759        are incremented backwards.
1760 
1761        This routine assumes, but does not check, that all of the entries in
1762        lens[] are in the range 0..MAXBITS.  The caller must assure this.
1763        1..MAXBITS is interpreted as that code length.  zero means that that
1764        symbol does not occur in this code.
1765 
1766        The codes are sorted by computing a count of codes for each length,
1767        creating from that a table of starting indices for each length in the
1768        sorted table, and then entering the symbols in order in the sorted
1769        table.  The sorted table is work[], with that space being provided by
1770        the caller.
1771 
1772        The length counts are used for other purposes as well, i.e. finding
1773        the minimum and maximum length codes, determining if there are any
1774        codes at all, checking for a valid set of lengths, and looking ahead
1775        at length counts to determine sub-table sizes when building the
1776        decoding tables.
1777      */
1778 
1779     /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
1780     for (len = 0; len <= MAXBITS; len++)
1781         count[len] = 0;
1782     for (sym = 0; sym < codes; sym++)
1783         count[lens[sym]]++;
1784 
1785     /* bound code lengths, force root to be within code lengths */
1786     root = *bits;
1787     for (max = MAXBITS; max >= 1; max--)
1788         if (count[max] != 0) break;
1789     if (root > max) root = max;
1790     if (max == 0) {                     /* no symbols to code at all */
1791         this.op = (unsigned char)64;    /* invalid code marker */
1792         this.bits = (unsigned char)1;
1793         this.val = (unsigned short)0;
1794         *(*table)++ = this;             /* make a table to force an error */
1795         *(*table)++ = this;
1796         *bits = 1;
1797         return 0;     /* no symbols, but wait for decoding to report error */
1798     }
1799     for (min = 1; min <= MAXBITS; min++)
1800         if (count[min] != 0) break;
1801     if (root < min) root = min;
1802 
1803     /* check for an over-subscribed or incomplete set of lengths */
1804     left = 1;
1805     for (len = 1; len <= MAXBITS; len++) {
1806         left <<= 1;
1807         left -= count[len];
1808         if (left < 0) return -1;        /* over-subscribed */
1809     }
1810     if (left > 0 && (type == CODES || max != 1))
1811         return -1;                      /* incomplete set */
1812 
1813     /* generate offsets into symbol table for each length for sorting */
1814     offs[1] = 0;
1815     for (len = 1; len < MAXBITS; len++)
1816         offs[len + 1] = offs[len] + count[len];
1817 
1818     /* sort symbols by length, by symbol order within each length */
1819     for (sym = 0; sym < codes; sym++)
1820         if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
1821 
1822     /*
1823        Create and fill in decoding tables.  In this loop, the table being
1824        filled is at next and has curr index bits.  The code being used is huff
1825        with length len.  That code is converted to an index by dropping drop
1826        bits off of the bottom.  For codes where len is less than drop + curr,
1827        those top drop + curr - len bits are incremented through all values to
1828        fill the table with replicated entries.
1829 
1830        root is the number of index bits for the root table.  When len exceeds
1831        root, sub-tables are created pointed to by the root entry with an index
1832        of the low root bits of huff.  This is saved in low to check for when a
1833        new sub-table should be started.  drop is zero when the root table is
1834        being filled, and drop is root when sub-tables are being filled.
1835 
1836        When a new sub-table is needed, it is necessary to look ahead in the
1837        code lengths to determine what size sub-table is needed.  The length
1838        counts are used for this, and so count[] is decremented as codes are
1839        entered in the tables.
1840 
1841        used keeps track of how many table entries have been allocated from the
1842        provided *table space.  It is checked when a LENS table is being made
1843        against the space in *table, ENOUGH, minus the maximum space needed by
1844        the worst case distance code, MAXD.  This should never happen, but the
1845        sufficiency of ENOUGH has not been proven exhaustively, hence the check.
1846        This assumes that when type == LENS, bits == 9.
1847 
1848        sym increments through all symbols, and the loop terminates when
1849        all codes of length max, i.e. all codes, have been processed.  This
1850        routine permits incomplete codes, so another loop after this one fills
1851        in the rest of the decoding tables with invalid code markers.
1852      */
1853 
1854     /* set up for code type */
1855     switch (type) {
1856     case CODES:
1857         base = extra = work;    /* dummy value--not used */
1858         end = 19;
1859         break;
1860     case LENS:
1861         base = lbase;
1862         base -= 257;
1863         extra = lext;
1864         extra -= 257;
1865         end = 256;
1866         break;
1867     default:            /* DISTS */
1868         base = dbase;
1869         extra = dext;
1870         end = -1;
1871     }
1872 
1873     /* initialize state for loop */
1874     huff = 0;                   /* starting code */
1875     sym = 0;                    /* starting code symbol */
1876     len = min;                  /* starting code length */
1877     next = *table;              /* current table to fill in */
1878     curr = root;                /* current table index bits */
1879     drop = 0;                   /* current bits to drop from code for index */
1880     low = (unsigned)(-1);       /* trigger new sub-table when len > root */
1881     used = ((unsigned int)1) << root;          /* use root table entries */
1882     mask = used - 1;            /* mask for comparing low */
1883 
1884     /* check available table space */
1885     if (type == LENS && used >= ENOUGH - MAXD)
1886         return 1;
1887 
1888     /* process all codes and make table entries */
1889     for (;;) {
1890         /* create table entry */
1891         this.bits = (unsigned char)(len - drop);
1892         if ((int)(work[sym]) < end) {
1893             this.op = (unsigned char)0;
1894             this.val = work[sym];
1895         }
1896         else if ((int)(work[sym]) > end) {
1897             this.op = (unsigned char)(extra[work[sym]]);
1898             this.val = base[work[sym]];
1899         }
1900         else {
1901             this.op = (unsigned char)(32 + 64);         /* end of block */
1902             this.val = 0;
1903         }
1904 
1905         /* replicate for those indices with low len bits equal to huff */
1906         incr = ((unsigned int)1) << (len - drop);
1907         fill = ((unsigned int)1) << curr;
1908         min = fill;                 /* save offset to next table */
1909         do {
1910             fill -= incr;
1911             next[(huff >> drop) + fill] = this;
1912         } while (fill != 0);
1913 
1914         /* backwards increment the len-bit code huff */
1915         incr = ((unsigned int)1) << (len - 1);
1916         while (huff & incr)
1917             incr >>= 1;
1918         if (incr != 0) {
1919             huff &= incr - 1;
1920             huff += incr;
1921         }
1922         else
1923             huff = 0;
1924 
1925         /* go to next symbol, update count, len */
1926         sym++;
1927         if (--(count[len]) == 0) {
1928             if (len == max) break;
1929             len = lens[work[sym]];
1930         }
1931 
1932         /* create new sub-table if needed */
1933         if (len > root && (huff & mask) != low) {
1934             /* if first time, transition to sub-tables */
1935             if (drop == 0)
1936                 drop = root;
1937 
1938             /* increment past last table */
1939             next += min;            /* here min is 1 << curr */
1940 
1941             /* determine length of next table */
1942             curr = len - drop;
1943             left = (int)(1 << curr);
1944             while (curr + drop < max) {
1945                 left -= count[curr + drop];
1946                 if (left <= 0) break;
1947                 curr++;
1948                 left <<= 1;
1949             }
1950 
1951             /* check for enough space */
1952             used += ((unsigned int)1) << curr;
1953             if (type == LENS && used >= ENOUGH - MAXD)
1954                 return 1;
1955 
1956             /* point entry in root table to sub-table */
1957             low = huff & mask;
1958             (*table)[low].op = (unsigned char)curr;
1959             (*table)[low].bits = (unsigned char)root;
1960             (*table)[low].val = (unsigned short)(next - *table);
1961         }
1962     }
1963 
1964     /*
1965        Fill in rest of table for incomplete codes.  This loop is similar to the
1966        loop above in incrementing huff for table indices.  It is assumed that
1967        len is equal to curr + drop, so there is no loop needed to increment
1968        through high index bits.  When the current sub-table is filled, the loop
1969        drops back to the root table to fill in any remaining entries there.
1970      */
1971     this.op = (unsigned char)64;                /* invalid code marker */
1972     this.bits = (unsigned char)(len - drop);
1973     this.val = (unsigned short)0;
1974     while (huff != 0) {
1975         /* when done with sub-table, drop back to root table */
1976         if (drop != 0 && (huff & mask) != low) {
1977             drop = 0;
1978             len = root;
1979             next = *table;
1980             this.bits = (unsigned char)len;
1981         }
1982 
1983         /* put invalid code marker in table */
1984         next[huff >> drop] = this;
1985 
1986         /* backwards increment the len-bit code huff */
1987         incr = ((unsigned int)1) << (len - 1);
1988         while (huff & incr)
1989             incr >>= 1;
1990         if (incr != 0) {
1991             huff &= incr - 1;
1992             huff += incr;
1993         }
1994         else
1995             huff = 0;
1996     }
1997 
1998     /* set return parameters */
1999     *table += used;
2000     *bits = root;
2001     return 0;
2002 }
2003 
2004 #endif /* _INFTREES_C */
2005 
2006 #ifndef _INFFAST_C
2007 #define _INFFAST_C	1
2008 
2009 /* Allow machine dependent optimization for post-increment or pre-increment.
2010    Based on testing to date,
2011    Pre-increment preferred for:
2012    - PowerPC G3 (Adler)
2013    - MIPS R5000 (Randers-Pehrson)
2014    Post-increment preferred for:
2015    - none
2016    No measurable difference:
2017    - Pentium III (Anderson)
2018    - M68060 (Nikl)
2019  */
2020 #undef	OFF		/* (ancient) sunos <locale.h> */
2021 #ifdef POSTINC
2022 #  define OFF 0
2023 #  define PUP(a) *(a)++
2024 #else
2025 #  define OFF 1
2026 #  define PUP(a) *++(a)
2027 #endif
2028 
2029 /*
2030    Decode literal, length, and distance codes and write out the resulting
2031    literal and match bytes until either not enough input or output is
2032    available, an end-of-block is encountered, or a data error is encountered.
2033    When large enough input and output buffers are supplied to inflate(), for
2034    example, a 16K input buffer and a 64K output buffer, more than 95% of the
2035    inflate execution time is spent in this routine.
2036 
2037    Entry assumptions:
2038 
2039         state->mode == LEN
2040         strm->avail_in >= 6
2041         strm->avail_out >= 258
2042         start >= strm->avail_out
2043         state->bits < 8
2044 
2045    On return, state->mode is one of:
2046 
2047         LEN -- ran out of enough output space or enough available input
2048         TYPE -- reached end of block code, inflate() to interpret next block
2049         BAD -- error in block data
2050 
2051    Notes:
2052 
2053     - The maximum input bits used by a length/distance pair is 15 bits for the
2054       length code, 5 bits for the length extra, 15 bits for the distance code,
2055       and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
2056       Therefore if strm->avail_in >= 6, then there is enough input to avoid
2057       checking for available input while decoding.
2058 
2059     - The maximum bytes that a single length/distance pair can output is 258
2060       bytes, which is the maximum length that can be coded.  inflate_fast()
2061       requires strm->avail_out >= 258 for each loop to avoid checking for
2062       output space.
2063  */
2064 void inflate_fast(strm, start)
2065 z_streamp strm;
2066 unsigned start;         /* inflate()'s starting value for strm->avail_out */
2067 {
2068     struct inflate_state FAR *state;
2069     unsigned char FAR *in;      /* local strm->next_in */
2070     unsigned char FAR *last;    /* while in < last, enough input available */
2071     unsigned char FAR *out;     /* local strm->next_out */
2072     unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */
2073     unsigned char FAR *end;     /* while out < end, enough space available */
2074 #ifdef INFLATE_STRICT
2075     unsigned dmax;              /* maximum distance from zlib header */
2076 #endif
2077     unsigned wsize;             /* window size or zero if not using window */
2078     unsigned whave;             /* valid bytes in the window */
2079     unsigned write;             /* window write index */
2080     unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
2081     unsigned long hold;         /* local strm->hold */
2082     unsigned bits;              /* local strm->bits */
2083     code const FAR *lcode;      /* local strm->lencode */
2084     code const FAR *dcode;      /* local strm->distcode */
2085     unsigned lmask;             /* mask for first level of length codes */
2086     unsigned dmask;             /* mask for first level of distance codes */
2087     code this;                  /* retrieved table entry */
2088     unsigned op;                /* code bits, operation, extra bits, or */
2089                                 /*  window position, window bytes to copy */
2090     unsigned len;               /* match length, unused bytes */
2091     unsigned dist;              /* match distance */
2092     unsigned char FAR *from;    /* where to copy match from */
2093 
2094     /* copy state to local variables */
2095     state = (struct inflate_state FAR *)strm->state;
2096     in = strm->next_in - OFF;
2097     last = in + (strm->avail_in - 5);
2098     out = strm->next_out - OFF;
2099     beg = out - (start - strm->avail_out);
2100     end = out + (strm->avail_out - 257);
2101 #ifdef INFLATE_STRICT
2102     dmax = state->dmax;
2103 #endif
2104     wsize = state->wsize;
2105     whave = state->whave;
2106     write = state->write;
2107     window = state->window;
2108     hold = state->hold;
2109     bits = state->bits;
2110     lcode = state->lencode;
2111     dcode = state->distcode;
2112     lmask = (((unsigned int)1) << state->lenbits) - 1;
2113     dmask = (((unsigned int)1) << state->distbits) - 1;
2114 
2115     /* decode literals and length/distances until end-of-block or not enough
2116        input data or output space */
2117     do {
2118         if (bits < 15) {
2119             hold += (unsigned long)(PUP(in)) << bits;
2120             bits += 8;
2121             hold += (unsigned long)(PUP(in)) << bits;
2122             bits += 8;
2123         }
2124         this = lcode[hold & lmask];
2125       dolen:
2126         op = (unsigned)(this.bits);
2127         hold >>= op;
2128         bits -= op;
2129         op = (unsigned)(this.op);
2130         if (op == 0) {                          /* literal */
2131             Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
2132                     "inflate:         literal '%c'\n" :
2133                     "inflate:         literal 0x%02x\n", this.val));
2134             PUP(out) = (unsigned char)(this.val);
2135         }
2136         else if (op & 16) {                     /* length base */
2137             len = (unsigned)(this.val);
2138             op &= 15;                           /* number of extra bits */
2139             if (op) {
2140                 if (bits < op) {
2141                     hold += (unsigned long)(PUP(in)) << bits;
2142                     bits += 8;
2143                 }
2144                 len += (unsigned)hold & ((((unsigned int)1) << op) - 1);
2145                 hold >>= op;
2146                 bits -= op;
2147             }
2148             Tracevv((stderr, "inflate:         length %u\n", len));
2149             if (bits < 15) {
2150                 hold += (unsigned long)(PUP(in)) << bits;
2151                 bits += 8;
2152                 hold += (unsigned long)(PUP(in)) << bits;
2153                 bits += 8;
2154             }
2155             this = dcode[hold & dmask];
2156           dodist:
2157             op = (unsigned)(this.bits);
2158             hold >>= op;
2159             bits -= op;
2160             op = (unsigned)(this.op);
2161             if (op & 16) {                      /* distance base */
2162                 dist = (unsigned)(this.val);
2163                 op &= 15;                       /* number of extra bits */
2164                 if (bits < op) {
2165                     hold += (unsigned long)(PUP(in)) << bits;
2166                     bits += 8;
2167                     if (bits < op) {
2168                         hold += (unsigned long)(PUP(in)) << bits;
2169                         bits += 8;
2170                     }
2171                 }
2172                 dist += (unsigned)hold & ((((unsigned int)1) << op) - 1);
2173 #ifdef INFLATE_STRICT
2174                 if (dist > dmax) {
2175                     strm->msg = (char *)"invalid distance too far back";
2176                     state->mode = BAD;
2177                     break;
2178                 }
2179 #endif
2180                 hold >>= op;
2181                 bits -= op;
2182                 Tracevv((stderr, "inflate:         distance %u\n", dist));
2183                 op = (unsigned)(out - beg);     /* max distance in output */
2184                 if (dist > op) {                /* see if copy from window */
2185                     op = dist - op;             /* distance back in window */
2186                     if (op > whave) {
2187                         strm->msg = (char *)"invalid distance too far back";
2188                         state->mode = BAD;
2189                         break;
2190                     }
2191                     from = window - OFF;
2192                     if (write == 0) {           /* very common case */
2193                         from += wsize - op;
2194                         if (op < len) {         /* some from window */
2195                             len -= op;
2196                             do {
2197                                 PUP(out) = PUP(from);
2198                             } while (--op);
2199                             from = out - dist;  /* rest from output */
2200                         }
2201                     }
2202                     else if (write < op) {      /* wrap around window */
2203                         from += wsize + write - op;
2204                         op -= write;
2205                         if (op < len) {         /* some from end of window */
2206                             len -= op;
2207                             do {
2208                                 PUP(out) = PUP(from);
2209                             } while (--op);
2210                             from = window - OFF;
2211                             if (write < len) {  /* some from start of window */
2212                                 op = write;
2213                                 len -= op;
2214                                 do {
2215                                     PUP(out) = PUP(from);
2216                                 } while (--op);
2217                                 from = out - dist;      /* rest from output */
2218                             }
2219                         }
2220                     }
2221                     else {                      /* contiguous in window */
2222                         from += write - op;
2223                         if (op < len) {         /* some from window */
2224                             len -= op;
2225                             do {
2226                                 PUP(out) = PUP(from);
2227                             } while (--op);
2228                             from = out - dist;  /* rest from output */
2229                         }
2230                     }
2231                     while (len > 2) {
2232                         PUP(out) = PUP(from);
2233                         PUP(out) = PUP(from);
2234                         PUP(out) = PUP(from);
2235                         len -= 3;
2236                     }
2237                     if (len) {
2238                         PUP(out) = PUP(from);
2239                         if (len > 1)
2240                             PUP(out) = PUP(from);
2241                     }
2242                 }
2243                 else {
2244                     from = out - dist;          /* copy direct from output */
2245                     do {                        /* minimum length is three */
2246                         PUP(out) = PUP(from);
2247                         PUP(out) = PUP(from);
2248                         PUP(out) = PUP(from);
2249                         len -= 3;
2250                     } while (len > 2);
2251                     if (len) {
2252                         PUP(out) = PUP(from);
2253                         if (len > 1)
2254                             PUP(out) = PUP(from);
2255                     }
2256                 }
2257             }
2258             else if ((op & 64) == 0) {          /* 2nd level distance code */
2259                 this = dcode[this.val + (hold & ((((unsigned int)1) << op) - 1))];
2260                 goto dodist;
2261             }
2262             else {
2263                 strm->msg = (char *)"invalid distance code";
2264                 state->mode = BAD;
2265                 break;
2266             }
2267         }
2268         else if ((op & 64) == 0) {              /* 2nd level length code */
2269             this = lcode[this.val + (hold & ((((unsigned int)1) << op) - 1))];
2270             goto dolen;
2271         }
2272         else if (op & 32) {                     /* end-of-block */
2273             Tracevv((stderr, "inflate:         end of block\n"));
2274             state->mode = TYPE;
2275             break;
2276         }
2277         else {
2278             strm->msg = (char *)"invalid literal/length code";
2279             state->mode = BAD;
2280             break;
2281         }
2282     } while (in < last && out < end);
2283 
2284     /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
2285     len = bits >> 3;
2286     in -= len;
2287     bits -= len << 3;
2288     hold &= (((unsigned int)1) << bits) - 1;
2289 
2290     /* update state and return */
2291     strm->next_in = in + OFF;
2292     strm->next_out = out + OFF;
2293     strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
2294     strm->avail_out = (unsigned)(out < end ?
2295                                  257 + (end - out) : 257 - (out - end));
2296     state->hold = hold;
2297     state->bits = bits;
2298     return;
2299 }
2300 
2301 /*
2302    inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
2303    - Using bit fields for code structure
2304    - Different op definition to avoid & for extra bits (do & for table bits)
2305    - Three separate decoding do-loops for direct, window, and write == 0
2306    - Special case for distance > 1 copies to do overlapped load and store copy
2307    - Explicit branch predictions (based on measured branch probabilities)
2308    - Deferring match copy and interspersed it with decoding subsequent codes
2309    - Swapping literal/length else
2310    - Swapping window/direct else
2311    - Larger unrolled copy loops (three is about right)
2312    - Moving len -= 3 statement into middle of loop
2313  */
2314 
2315 #endif /* _INFFAST_C */
2316 
2317 #ifndef _INFLATE_C
2318 #define _INFLATE_C	1
2319 
2320 /* function prototypes */
2321 local void fixedtables OF((struct inflate_state FAR *state));
2322 local int updatewindow OF((z_streamp strm, unsigned out));
2323 #ifdef BUILDFIXED
2324    void makefixed OF((void));
2325 #endif
2326 local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
2327                               unsigned len));
2328 
2329 int ZEXPORT inflateReset(strm)
2330 z_streamp strm;
2331 {
2332     struct inflate_state FAR *state;
2333 
2334     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
2335     state = (struct inflate_state FAR *)strm->state;
2336     strm->total_in = strm->total_out = state->total = 0;
2337     strm->msg = Z_NULL;
2338     strm->adler = 1;        /* to support ill-conceived Java test suite */
2339     state->mode = HEAD;
2340     state->last = 0;
2341     state->havedict = 0;
2342     state->dmax = 32768;
2343     state->head = Z_NULL;
2344     state->wsize = 0;
2345     state->whave = 0;
2346     state->write = 0;
2347     state->hold = 0;
2348     state->bits = 0;
2349     state->lencode = state->distcode = state->next = state->codes;
2350     Tracev((stderr, "inflate: reset\n"));
2351     return Z_OK;
2352 }
2353 
2354 int ZEXPORT inflatePrime(strm, bits, value)
2355 z_streamp strm;
2356 int bits;
2357 int value;
2358 {
2359     struct inflate_state FAR *state;
2360 
2361     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
2362     state = (struct inflate_state FAR *)strm->state;
2363     if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
2364     value &= (1L << bits) - 1;
2365     state->hold += value << state->bits;
2366     state->bits += bits;
2367     return Z_OK;
2368 }
2369 
2370 int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
2371 z_streamp strm;
2372 int windowBits;
2373 const char *version;
2374 int stream_size;
2375 {
2376     struct inflate_state FAR *state;
2377 
2378     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
2379         stream_size != (int)(sizeof(z_stream)))
2380         return Z_VERSION_ERROR;
2381     if (strm == Z_NULL) return Z_STREAM_ERROR;
2382     strm->msg = Z_NULL;                 /* in case we return an error */
2383     if (strm->zalloc == (alloc_func)0) {
2384         strm->zalloc = zcalloc;
2385         strm->opaque = (voidpf)0;
2386     }
2387     if (strm->zfree == (free_func)0) strm->zfree = zcfree;
2388     state = (struct inflate_state FAR *)
2389             ZALLOC(strm, 1, sizeof(struct inflate_state));
2390     if (state == Z_NULL) return Z_MEM_ERROR;
2391     Tracev((stderr, "inflate: allocated\n"));
2392     strm->state = (struct internal_state FAR *)state;
2393     if (windowBits < 0) {
2394         state->wrap = 0;
2395         windowBits = -windowBits;
2396     }
2397     else {
2398         state->wrap = (windowBits >> 4) + 1;
2399 #ifdef GUNZIP
2400         if (windowBits < 48) windowBits &= 15;
2401 #endif
2402     }
2403     if (windowBits < 8 || windowBits > 15) {
2404         ZFREE(strm, state);
2405         strm->state = Z_NULL;
2406         return Z_STREAM_ERROR;
2407     }
2408     state->wbits = (unsigned)windowBits;
2409     state->window = Z_NULL;
2410     return inflateReset(strm);
2411 }
2412 
2413 int ZEXPORT inflateInit_(strm, version, stream_size)
2414 z_streamp strm;
2415 const char *version;
2416 int stream_size;
2417 {
2418     return inflateInit2_(strm, DEF_WBITS, version, stream_size);
2419 }
2420 
2421 /*
2422    Return state with length and distance decoding tables and index sizes set to
2423    fixed code decoding.  Normally this returns fixed tables from inffixed.h.
2424    If BUILDFIXED is defined, then instead this routine builds the tables the
2425    first time it's called, and returns those tables the first time and
2426    thereafter.  This reduces the size of the code by about 2K bytes, in
2427    exchange for a little execution time.  However, BUILDFIXED should not be
2428    used for threaded applications, since the rewriting of the tables and virgin
2429    may not be thread-safe.
2430  */
2431 local void fixedtables(state)
2432 struct inflate_state FAR *state;
2433 {
2434 #ifndef _INFFIXED_H
2435 #define _INFFIXED_H	1
2436     static const code lenfix[512] = {
2437         {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
2438         {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
2439         {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
2440         {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
2441         {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
2442         {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
2443         {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
2444         {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
2445         {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
2446         {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
2447         {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
2448         {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
2449         {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
2450         {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
2451         {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
2452         {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
2453         {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
2454         {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
2455         {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
2456         {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
2457         {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
2458         {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
2459         {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
2460         {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
2461         {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
2462         {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
2463         {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
2464         {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
2465         {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
2466         {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
2467         {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
2468         {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
2469         {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
2470         {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
2471         {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
2472         {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
2473         {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
2474         {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
2475         {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
2476         {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
2477         {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
2478         {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
2479         {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
2480         {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
2481         {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
2482         {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
2483         {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
2484         {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
2485         {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
2486         {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
2487         {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
2488         {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
2489         {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
2490         {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
2491         {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
2492         {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
2493         {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
2494         {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
2495         {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
2496         {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
2497         {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
2498         {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
2499         {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
2500         {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
2501         {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
2502         {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
2503         {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
2504         {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
2505         {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
2506         {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
2507         {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
2508         {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
2509         {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
2510         {0,9,255}
2511     };
2512 
2513     static const code distfix[32] = {
2514         {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
2515         {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
2516         {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
2517         {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
2518         {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
2519         {22,5,193},{64,5,0}
2520     };
2521 #endif /* _INFFIXED_H */
2522     state->lencode = lenfix;
2523     state->lenbits = 9;
2524     state->distcode = distfix;
2525     state->distbits = 5;
2526 }
2527 
2528 /*
2529    Update the window with the last wsize (normally 32K) bytes written before
2530    returning.  If window does not exist yet, create it.  This is only called
2531    when a window is already in use, or when output has been written during this
2532    inflate call, but the end of the deflate stream has not been reached yet.
2533    It is also called to create a window for dictionary data when a dictionary
2534    is loaded.
2535 
2536    Providing output buffers larger than 32K to inflate() should provide a speed
2537    advantage, since only the last 32K of output is copied to the sliding window
2538    upon return from inflate(), and since all distances after the first 32K of
2539    output will fall in the output data, making match copies simpler and faster.
2540    The advantage may be dependent on the size of the processor's data caches.
2541  */
2542 local int updatewindow(strm, out)
2543 z_streamp strm;
2544 unsigned out;
2545 {
2546     struct inflate_state FAR *state;
2547     unsigned copy, dist;
2548 
2549     state = (struct inflate_state FAR *)strm->state;
2550 
2551     /* if it hasn't been done already, allocate space for the window */
2552     if (state->window == Z_NULL) {
2553         state->window = (unsigned char FAR *)
2554                         ZALLOC(strm, ((unsigned int)1) << state->wbits,
2555                                sizeof(unsigned char));
2556         if (state->window == Z_NULL) return 1;
2557     }
2558 
2559     /* if window not in use yet, initialize */
2560     if (state->wsize == 0) {
2561         state->wsize = ((unsigned int)1) << state->wbits;
2562         state->write = 0;
2563         state->whave = 0;
2564     }
2565 
2566     /* copy state->wsize or less output bytes into the circular window */
2567     copy = out - strm->avail_out;
2568     if (copy >= state->wsize) {
2569         zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
2570         state->write = 0;
2571         state->whave = state->wsize;
2572     }
2573     else {
2574         dist = state->wsize - state->write;
2575         if (dist > copy) dist = copy;
2576         zmemcpy(state->window + state->write, strm->next_out - copy, dist);
2577         copy -= dist;
2578         if (copy) {
2579             zmemcpy(state->window, strm->next_out - copy, copy);
2580             state->write = copy;
2581             state->whave = state->wsize;
2582         }
2583         else {
2584             state->write += dist;
2585             if (state->write == state->wsize) state->write = 0;
2586             if (state->whave < state->wsize) state->whave += dist;
2587         }
2588     }
2589     return 0;
2590 }
2591 
2592 /* Macros for inflate(): */
2593 
2594 /* check function to use adler32() for zlib or crc32() for gzip */
2595 #ifdef GUNZIP
2596 #  define UPDATE(check, buf, len) \
2597     (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
2598 #else
2599 #  define UPDATE(check, buf, len) adler32(check, buf, len)
2600 #endif
2601 
2602 /* check macros for header crc */
2603 #ifdef GUNZIP
2604 #  define CRC2(check, word) \
2605     do { \
2606         hbuf[0] = (unsigned char)(word); \
2607         hbuf[1] = (unsigned char)((word) >> 8); \
2608         check = crc32(check, hbuf, 2); \
2609     } while (0)
2610 
2611 #  define CRC4(check, word) \
2612     do { \
2613         hbuf[0] = (unsigned char)(word); \
2614         hbuf[1] = (unsigned char)((word) >> 8); \
2615         hbuf[2] = (unsigned char)((word) >> 16); \
2616         hbuf[3] = (unsigned char)((word) >> 24); \
2617         check = crc32(check, hbuf, 4); \
2618     } while (0)
2619 #endif
2620 
2621 /* Load registers with state in inflate() for speed */
2622 #define LOAD() \
2623     do { \
2624         put = strm->next_out; \
2625         left = strm->avail_out; \
2626         next = strm->next_in; \
2627         have = strm->avail_in; \
2628         hold = state->hold; \
2629         bits = state->bits; \
2630     } while (0)
2631 
2632 /* Restore state from registers in inflate() */
2633 #define RESTORE() \
2634     do { \
2635         strm->next_out = put; \
2636         strm->avail_out = left; \
2637         strm->next_in = next; \
2638         strm->avail_in = have; \
2639         state->hold = hold; \
2640         state->bits = bits; \
2641     } while (0)
2642 
2643 /* Clear the input bit accumulator */
2644 #define INITBITS() \
2645     do { \
2646         hold = 0; \
2647         bits = 0; \
2648     } while (0)
2649 
2650 /* Get a byte of input into the bit accumulator, or return from inflate()
2651    if there is no input available. */
2652 #define PULLBYTE() \
2653     do { \
2654         if (have == 0) goto inf_leave; \
2655         have--; \
2656         hold += (unsigned long)(*next++) << bits; \
2657         bits += 8; \
2658     } while (0)
2659 
2660 /* Assure that there are at least n bits in the bit accumulator.  If there is
2661    not enough available input to do that, then return from inflate(). */
2662 #define NEEDBITS(n) \
2663     do { \
2664         while (bits < (unsigned)(n)) \
2665             PULLBYTE(); \
2666     } while (0)
2667 
2668 /* Return the low n bits of the bit accumulator (n < 16) */
2669 #define BITS(n) \
2670     ((unsigned)hold & ((((unsigned int)1) << (n)) - 1))
2671 
2672 /* Remove n bits from the bit accumulator */
2673 #define DROPBITS(n) \
2674     do { \
2675         hold >>= (n); \
2676         bits -= (unsigned)(n); \
2677     } while (0)
2678 
2679 /* Remove zero to seven bits as needed to go to a byte boundary */
2680 #define BYTEBITS() \
2681     do { \
2682         hold >>= bits & 7; \
2683         bits -= bits & 7; \
2684     } while (0)
2685 
2686 /* Reverse the bytes in a 32-bit value */
2687 #define REVERSE(q) \
2688     ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
2689      (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
2690 
2691 /*
2692    inflate() uses a state machine to process as much input data and generate as
2693    much output data as possible before returning.  The state machine is
2694    structured roughly as follows:
2695 
2696     for (;;) switch (state) {
2697     ...
2698     case STATEn:
2699         if (not enough input data or output space to make progress)
2700             return;
2701         ... make progress ...
2702         state = STATEm;
2703         break;
2704     ...
2705     }
2706 
2707    so when inflate() is called again, the same case is attempted again, and
2708    if the appropriate resources are provided, the machine proceeds to the
2709    next state.  The NEEDBITS() macro is usually the way the state evaluates
2710    whether it can proceed or should return.  NEEDBITS() does the return if
2711    the requested bits are not available.  The typical use of the BITS macros
2712    is:
2713 
2714         NEEDBITS(n);
2715         ... do something with BITS(n) ...
2716         DROPBITS(n);
2717 
2718    where NEEDBITS(n) either returns from inflate() if there isn't enough
2719    input left to load n bits into the accumulator, or it continues.  BITS(n)
2720    gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
2721    the low n bits off the accumulator.  INITBITS() clears the accumulator
2722    and sets the number of available bits to zero.  BYTEBITS() discards just
2723    enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
2724    and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
2725 
2726    NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
2727    if there is no input available.  The decoding of variable length codes uses
2728    PULLBYTE() directly in order to pull just enough bytes to decode the next
2729    code, and no more.
2730 
2731    Some states loop until they get enough input, making sure that enough
2732    state information is maintained to continue the loop where it left off
2733    if NEEDBITS() returns in the loop.  For example, want, need, and keep
2734    would all have to actually be part of the saved state in case NEEDBITS()
2735    returns:
2736 
2737     case STATEw:
2738         while (want < need) {
2739             NEEDBITS(n);
2740             keep[want++] = BITS(n);
2741             DROPBITS(n);
2742         }
2743         state = STATEx;
2744     case STATEx:
2745 
2746    As shown above, if the next state is also the next case, then the break
2747    is omitted.
2748 
2749    A state may also return if there is not enough output space available to
2750    complete that state.  Those states are copying stored data, writing a
2751    literal byte, and copying a matching string.
2752 
2753    When returning, a "goto inf_leave" is used to update the total counters,
2754    update the check value, and determine whether any progress has been made
2755    during that inflate() call in order to return the proper return code.
2756    Progress is defined as a change in either strm->avail_in or strm->avail_out.
2757    When there is a window, goto inf_leave will update the window with the last
2758    output written.  If a goto inf_leave occurs in the middle of decompression
2759    and there is no window currently, goto inf_leave will create one and copy
2760    output to the window for the next call of inflate().
2761 
2762    In this implementation, the flush parameter of inflate() only affects the
2763    return code (per zlib.h).  inflate() always writes as much as possible to
2764    strm->next_out, given the space available and the provided input--the effect
2765    documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
2766    the allocation of and copying into a sliding window until necessary, which
2767    provides the effect documented in zlib.h for Z_FINISH when the entire input
2768    stream available.  So the only thing the flush parameter actually does is:
2769    when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
2770    will return Z_BUF_ERROR if it has not reached the end of the stream.
2771  */
2772 
2773 int ZEXPORT inflate(strm, flush)
2774 z_streamp strm;
2775 int flush;
2776 {
2777     struct inflate_state FAR *state;
2778     unsigned char FAR *next;    /* next input */
2779     unsigned char FAR *put;     /* next output */
2780     unsigned have, left;        /* available input and output */
2781     unsigned long hold;         /* bit buffer */
2782     unsigned bits;              /* bits in bit buffer */
2783     unsigned in, out;           /* save starting available input and output */
2784     unsigned copy;              /* number of stored or match bytes to copy */
2785     unsigned char FAR *from;    /* where to copy match bytes from */
2786     code this;                  /* current decoding table entry */
2787     code last;                  /* parent table entry */
2788     unsigned len;               /* length to copy for repeats, bits to drop */
2789     int ret;                    /* return code */
2790 #ifdef GUNZIP
2791     unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
2792 #endif
2793     static const unsigned short order[19] = /* permutation of code lengths */
2794         {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
2795 
2796     if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
2797         (strm->next_in == Z_NULL && strm->avail_in != 0))
2798         return Z_STREAM_ERROR;
2799 
2800     state = (struct inflate_state FAR *)strm->state;
2801     if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
2802     LOAD();
2803     in = have;
2804     out = left;
2805     ret = Z_OK;
2806     for (;;)
2807         switch (state->mode) {
2808         case HEAD:
2809             if (state->wrap == 0) {
2810                 state->mode = TYPEDO;
2811                 break;
2812             }
2813             NEEDBITS(16);
2814 #ifdef GUNZIP
2815             if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
2816                 state->check = crc32(0L, Z_NULL, 0);
2817                 CRC2(state->check, hold);
2818                 INITBITS();
2819                 state->mode = FLAGS;
2820                 break;
2821             }
2822             state->flags = 0;           /* expect zlib header */
2823             if (state->head != Z_NULL)
2824                 state->head->done = -1;
2825             if (!(state->wrap & 1) ||   /* check if zlib header allowed */
2826 #else
2827             if (
2828 #endif
2829                 ((BITS(8) << 8) + (hold >> 8)) % 31) {
2830                 strm->msg = (char *)"incorrect header check";
2831                 state->mode = BAD;
2832                 break;
2833             }
2834             if (BITS(4) != Z_DEFLATED) {
2835                 strm->msg = (char *)"unknown compression method";
2836                 state->mode = BAD;
2837                 break;
2838             }
2839             DROPBITS(4);
2840             len = BITS(4) + 8;
2841             if (len > state->wbits) {
2842                 strm->msg = (char *)"invalid window size";
2843                 state->mode = BAD;
2844                 break;
2845             }
2846             state->dmax = ((unsigned int)1) << len;
2847             Tracev((stderr, "inflate:   zlib header ok\n"));
2848             strm->adler = state->check = adler32(0L, Z_NULL, 0);
2849             state->mode = hold & 0x200 ? DICTID : TYPE;
2850             INITBITS();
2851             break;
2852 #ifdef GUNZIP
2853         case FLAGS:
2854             NEEDBITS(16);
2855             state->flags = (int)(hold);
2856             if ((state->flags & 0xff) != Z_DEFLATED) {
2857                 strm->msg = (char *)"unknown compression method";
2858                 state->mode = BAD;
2859                 break;
2860             }
2861             if (state->flags & 0xe000) {
2862                 strm->msg = (char *)"unknown header flags set";
2863                 state->mode = BAD;
2864                 break;
2865             }
2866             if (state->head != Z_NULL)
2867                 state->head->text = (int)((hold >> 8) & 1);
2868             if (state->flags & 0x0200) CRC2(state->check, hold);
2869             INITBITS();
2870             state->mode = TIME;
2871         case TIME:
2872             NEEDBITS(32);
2873             if (state->head != Z_NULL)
2874                 state->head->time = hold;
2875             if (state->flags & 0x0200) CRC4(state->check, hold);
2876             INITBITS();
2877             state->mode = OS;
2878         case OS:
2879             NEEDBITS(16);
2880             if (state->head != Z_NULL) {
2881                 state->head->xflags = (int)(hold & 0xff);
2882                 state->head->os = (int)(hold >> 8);
2883             }
2884             if (state->flags & 0x0200) CRC2(state->check, hold);
2885             INITBITS();
2886             state->mode = EXLEN;
2887         case EXLEN:
2888             if (state->flags & 0x0400) {
2889                 NEEDBITS(16);
2890                 state->length = (unsigned)(hold);
2891                 if (state->head != Z_NULL)
2892                     state->head->extra_len = (unsigned)hold;
2893                 if (state->flags & 0x0200) CRC2(state->check, hold);
2894                 INITBITS();
2895             }
2896             else if (state->head != Z_NULL)
2897                 state->head->extra = Z_NULL;
2898             state->mode = EXTRA;
2899         case EXTRA:
2900             if (state->flags & 0x0400) {
2901                 copy = state->length;
2902                 if (copy > have) copy = have;
2903                 if (copy) {
2904                     if (state->head != Z_NULL &&
2905                         state->head->extra != Z_NULL) {
2906                         len = state->head->extra_len - state->length;
2907                         zmemcpy(state->head->extra + len, next,
2908                                 len + copy > state->head->extra_max ?
2909                                 state->head->extra_max - len : copy);
2910                     }
2911                     if (state->flags & 0x0200)
2912                         state->check = crc32(state->check, next, copy);
2913                     have -= copy;
2914                     next += copy;
2915                     state->length -= copy;
2916                 }
2917                 if (state->length) goto inf_leave;
2918             }
2919             state->length = 0;
2920             state->mode = NAME;
2921         case NAME:
2922             if (state->flags & 0x0800) {
2923                 if (have == 0) goto inf_leave;
2924                 copy = 0;
2925                 do {
2926                     len = (unsigned)(next[copy++]);
2927                     if (state->head != Z_NULL &&
2928                             state->head->name != Z_NULL &&
2929                             state->length < state->head->name_max)
2930                         state->head->name[state->length++] = len;
2931                 } while (len && copy < have);
2932                 if (state->flags & 0x0200)
2933                     state->check = crc32(state->check, next, copy);
2934                 have -= copy;
2935                 next += copy;
2936                 if (len) goto inf_leave;
2937             }
2938             else if (state->head != Z_NULL)
2939                 state->head->name = Z_NULL;
2940             state->length = 0;
2941             state->mode = COMMENT;
2942         case COMMENT:
2943             if (state->flags & 0x1000) {
2944                 if (have == 0) goto inf_leave;
2945                 copy = 0;
2946                 do {
2947                     len = (unsigned)(next[copy++]);
2948                     if (state->head != Z_NULL &&
2949                             state->head->comment != Z_NULL &&
2950                             state->length < state->head->comm_max)
2951                         state->head->comment[state->length++] = len;
2952                 } while (len && copy < have);
2953                 if (state->flags & 0x0200)
2954                     state->check = crc32(state->check, next, copy);
2955                 have -= copy;
2956                 next += copy;
2957                 if (len) goto inf_leave;
2958             }
2959             else if (state->head != Z_NULL)
2960                 state->head->comment = Z_NULL;
2961             state->mode = HCRC;
2962         case HCRC:
2963             if (state->flags & 0x0200) {
2964                 NEEDBITS(16);
2965                 if (hold != (state->check & 0xffff)) {
2966                     strm->msg = (char *)"header crc mismatch";
2967                     state->mode = BAD;
2968                     break;
2969                 }
2970                 INITBITS();
2971             }
2972             if (state->head != Z_NULL) {
2973                 state->head->hcrc = (int)((state->flags >> 9) & 1);
2974                 state->head->done = 1;
2975             }
2976             strm->adler = state->check = crc32(0L, Z_NULL, 0);
2977             state->mode = TYPE;
2978             break;
2979 #endif
2980         case DICTID:
2981             NEEDBITS(32);
2982             strm->adler = state->check = REVERSE(hold);
2983             INITBITS();
2984             state->mode = DICT;
2985         case DICT:
2986             if (state->havedict == 0) {
2987                 RESTORE();
2988                 return Z_NEED_DICT;
2989             }
2990             strm->adler = state->check = adler32(0L, Z_NULL, 0);
2991             state->mode = TYPE;
2992         case TYPE:
2993             if (flush == Z_BLOCK) goto inf_leave;
2994         case TYPEDO:
2995             if (state->last) {
2996                 BYTEBITS();
2997                 state->mode = CHECK;
2998                 break;
2999             }
3000             NEEDBITS(3);
3001             state->last = BITS(1);
3002             DROPBITS(1);
3003             switch (BITS(2)) {
3004             case 0:                             /* stored block */
3005                 Tracev((stderr, "inflate:     stored block%s\n",
3006                         state->last ? " (last)" : ""));
3007                 state->mode = STORED;
3008                 break;
3009             case 1:                             /* fixed block */
3010                 fixedtables(state);
3011                 Tracev((stderr, "inflate:     fixed codes block%s\n",
3012                         state->last ? " (last)" : ""));
3013                 state->mode = LEN;              /* decode codes */
3014                 break;
3015             case 2:                             /* dynamic block */
3016                 Tracev((stderr, "inflate:     dynamic codes block%s\n",
3017                         state->last ? " (last)" : ""));
3018                 state->mode = TABLE;
3019                 break;
3020             case 3:
3021                 strm->msg = (char *)"invalid block type";
3022                 state->mode = BAD;
3023             }
3024             DROPBITS(2);
3025             break;
3026         case STORED:
3027             BYTEBITS();                         /* go to byte boundary */
3028             NEEDBITS(32);
3029             if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
3030                 strm->msg = (char *)"invalid stored block lengths";
3031                 state->mode = BAD;
3032                 break;
3033             }
3034             state->length = (unsigned)hold & 0xffff;
3035             Tracev((stderr, "inflate:       stored length %u\n",
3036                     state->length));
3037             INITBITS();
3038             state->mode = COPY;
3039         case COPY:
3040             copy = state->length;
3041             if (copy) {
3042                 if (copy > have) copy = have;
3043                 if (copy > left) copy = left;
3044                 if (copy == 0) goto inf_leave;
3045                 zmemcpy(put, next, copy);
3046                 have -= copy;
3047                 next += copy;
3048                 left -= copy;
3049                 put += copy;
3050                 state->length -= copy;
3051                 break;
3052             }
3053             Tracev((stderr, "inflate:       stored end\n"));
3054             state->mode = TYPE;
3055             break;
3056         case TABLE:
3057             NEEDBITS(14);
3058             state->nlen = BITS(5) + 257;
3059             DROPBITS(5);
3060             state->ndist = BITS(5) + 1;
3061             DROPBITS(5);
3062             state->ncode = BITS(4) + 4;
3063             DROPBITS(4);
3064 #ifndef PKZIP_BUG_WORKAROUND
3065             if (state->nlen > 286 || state->ndist > 30) {
3066                 strm->msg = (char *)"too many length or distance symbols";
3067                 state->mode = BAD;
3068                 break;
3069             }
3070 #endif
3071             Tracev((stderr, "inflate:       table sizes ok\n"));
3072             state->have = 0;
3073             state->mode = LENLENS;
3074         case LENLENS:
3075             while (state->have < state->ncode) {
3076                 NEEDBITS(3);
3077                 state->lens[order[state->have++]] = (unsigned short)BITS(3);
3078                 DROPBITS(3);
3079             }
3080             while (state->have < 19)
3081                 state->lens[order[state->have++]] = 0;
3082             state->next = state->codes;
3083             state->lencode = (code const FAR *)(state->next);
3084             state->lenbits = 7;
3085             ret = inflate_table(CODES, state->lens, 19, &(state->next),
3086                                 &(state->lenbits), state->work);
3087             if (ret) {
3088                 strm->msg = (char *)"invalid code lengths set";
3089                 state->mode = BAD;
3090                 break;
3091             }
3092             Tracev((stderr, "inflate:       code lengths ok\n"));
3093             state->have = 0;
3094             state->mode = CODELENS;
3095         case CODELENS:
3096             while (state->have < state->nlen + state->ndist) {
3097                 for (;;) {
3098                     this = state->lencode[BITS(state->lenbits)];
3099                     if ((unsigned)(this.bits) <= bits) break;
3100                     PULLBYTE();
3101                 }
3102                 if (this.val < 16) {
3103                     NEEDBITS(this.bits);
3104                     DROPBITS(this.bits);
3105                     state->lens[state->have++] = this.val;
3106                 }
3107                 else {
3108                     if (this.val == 16) {
3109                         NEEDBITS(this.bits + 2);
3110                         DROPBITS(this.bits);
3111                         if (state->have == 0) {
3112                             strm->msg = (char *)"invalid bit length repeat";
3113                             state->mode = BAD;
3114                             break;
3115                         }
3116                         len = state->lens[state->have - 1];
3117                         copy = 3 + BITS(2);
3118                         DROPBITS(2);
3119                     }
3120                     else if (this.val == 17) {
3121                         NEEDBITS(this.bits + 3);
3122                         DROPBITS(this.bits);
3123                         len = 0;
3124                         copy = 3 + BITS(3);
3125                         DROPBITS(3);
3126                     }
3127                     else {
3128                         NEEDBITS(this.bits + 7);
3129                         DROPBITS(this.bits);
3130                         len = 0;
3131                         copy = 11 + BITS(7);
3132                         DROPBITS(7);
3133                     }
3134                     if (state->have + copy > state->nlen + state->ndist) {
3135                         strm->msg = (char *)"invalid bit length repeat";
3136                         state->mode = BAD;
3137                         break;
3138                     }
3139                     while (copy--)
3140                         state->lens[state->have++] = (unsigned short)len;
3141                 }
3142             }
3143 
3144             /* handle error breaks in while */
3145             if (state->mode == BAD) break;
3146 
3147             /* build code tables */
3148             state->next = state->codes;
3149             state->lencode = (code const FAR *)(state->next);
3150             state->lenbits = 9;
3151             ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
3152                                 &(state->lenbits), state->work);
3153             if (ret) {
3154                 strm->msg = (char *)"invalid literal/lengths set";
3155                 state->mode = BAD;
3156                 break;
3157             }
3158             state->distcode = (code const FAR *)(state->next);
3159             state->distbits = 6;
3160             ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
3161                             &(state->next), &(state->distbits), state->work);
3162             if (ret) {
3163                 strm->msg = (char *)"invalid distances set";
3164                 state->mode = BAD;
3165                 break;
3166             }
3167             Tracev((stderr, "inflate:       codes ok\n"));
3168             state->mode = LEN;
3169         case LEN:
3170             if (have >= 6 && left >= 258) {
3171                 RESTORE();
3172                 inflate_fast(strm, out);
3173                 LOAD();
3174                 break;
3175             }
3176             for (;;) {
3177                 this = state->lencode[BITS(state->lenbits)];
3178                 if ((unsigned)(this.bits) <= bits) break;
3179                 PULLBYTE();
3180             }
3181             if (this.op && (this.op & 0xf0) == 0) {
3182                 last = this;
3183                 for (;;) {
3184                     this = state->lencode[last.val +
3185                             (BITS(last.bits + last.op) >> last.bits)];
3186                     if ((unsigned)(last.bits + this.bits) <= bits) break;
3187                     PULLBYTE();
3188                 }
3189                 DROPBITS(last.bits);
3190             }
3191             DROPBITS(this.bits);
3192             state->length = (unsigned)this.val;
3193             if ((int)(this.op) == 0) {
3194                 Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
3195                         "inflate:         literal '%c'\n" :
3196                         "inflate:         literal 0x%02x\n", this.val));
3197                 state->mode = LIT;
3198                 break;
3199             }
3200             if (this.op & 32) {
3201                 Tracevv((stderr, "inflate:         end of block\n"));
3202                 state->mode = TYPE;
3203                 break;
3204             }
3205             if (this.op & 64) {
3206                 strm->msg = (char *)"invalid literal/length code";
3207                 state->mode = BAD;
3208                 break;
3209             }
3210             state->extra = (unsigned)(this.op) & 15;
3211             state->mode = LENEXT;
3212         case LENEXT:
3213             if (state->extra) {
3214                 NEEDBITS(state->extra);
3215                 state->length += BITS(state->extra);
3216                 DROPBITS(state->extra);
3217             }
3218             Tracevv((stderr, "inflate:         length %u\n", state->length));
3219             state->mode = DIST;
3220         case DIST:
3221             for (;;) {
3222                 this = state->distcode[BITS(state->distbits)];
3223                 if ((unsigned)(this.bits) <= bits) break;
3224                 PULLBYTE();
3225             }
3226             if ((this.op & 0xf0) == 0) {
3227                 last = this;
3228                 for (;;) {
3229                     this = state->distcode[last.val +
3230                             (BITS(last.bits + last.op) >> last.bits)];
3231                     if ((unsigned)(last.bits + this.bits) <= bits) break;
3232                     PULLBYTE();
3233                 }
3234                 DROPBITS(last.bits);
3235             }
3236             DROPBITS(this.bits);
3237             if (this.op & 64) {
3238                 strm->msg = (char *)"invalid distance code";
3239                 state->mode = BAD;
3240                 break;
3241             }
3242             state->offset = (unsigned)this.val;
3243             state->extra = (unsigned)(this.op) & 15;
3244             state->mode = DISTEXT;
3245         case DISTEXT:
3246             if (state->extra) {
3247                 NEEDBITS(state->extra);
3248                 state->offset += BITS(state->extra);
3249                 DROPBITS(state->extra);
3250             }
3251 #ifdef INFLATE_STRICT
3252             if (state->offset > state->dmax) {
3253                 strm->msg = (char *)"invalid distance too far back";
3254                 state->mode = BAD;
3255                 break;
3256             }
3257 #endif
3258             if (state->offset > state->whave + out - left) {
3259                 strm->msg = (char *)"invalid distance too far back";
3260                 state->mode = BAD;
3261                 break;
3262             }
3263             Tracevv((stderr, "inflate:         distance %u\n", state->offset));
3264             state->mode = MATCH;
3265         case MATCH:
3266             if (left == 0) goto inf_leave;
3267             copy = out - left;
3268             if (state->offset > copy) {         /* copy from window */
3269                 copy = state->offset - copy;
3270                 if (copy > state->write) {
3271                     copy -= state->write;
3272                     from = state->window + (state->wsize - copy);
3273                 }
3274                 else
3275                     from = state->window + (state->write - copy);
3276                 if (copy > state->length) copy = state->length;
3277             }
3278             else {                              /* copy from output */
3279                 from = put - state->offset;
3280                 copy = state->length;
3281             }
3282             if (copy > left) copy = left;
3283             left -= copy;
3284             state->length -= copy;
3285             do {
3286                 *put++ = *from++;
3287             } while (--copy);
3288             if (state->length == 0) state->mode = LEN;
3289             break;
3290         case LIT:
3291             if (left == 0) goto inf_leave;
3292             *put++ = (unsigned char)(state->length);
3293             left--;
3294             state->mode = LEN;
3295             break;
3296         case CHECK:
3297             if (state->wrap) {
3298                 NEEDBITS(32);
3299                 out -= left;
3300                 strm->total_out += out;
3301                 state->total += out;
3302                 if (out)
3303                     strm->adler = state->check =
3304                         UPDATE(state->check, put - out, out);
3305                 out = left;
3306                 if ((
3307 #ifdef GUNZIP
3308                      state->flags ? hold :
3309 #endif
3310                      REVERSE(hold)) != state->check) {
3311                     strm->msg = (char *)"incorrect data check";
3312                     state->mode = BAD;
3313                     break;
3314                 }
3315                 INITBITS();
3316                 Tracev((stderr, "inflate:   check matches trailer\n"));
3317             }
3318 #ifdef GUNZIP
3319             state->mode = LENGTH;
3320         case LENGTH:
3321             if (state->wrap && state->flags) {
3322                 NEEDBITS(32);
3323                 if (hold != (state->total & 0xffffffff)) {
3324                     strm->msg = (char *)"incorrect length check";
3325                     state->mode = BAD;
3326                     break;
3327                 }
3328                 INITBITS();
3329                 Tracev((stderr, "inflate:   length matches trailer\n"));
3330             }
3331 #endif
3332             state->mode = DONE;
3333         case DONE:
3334             ret = Z_STREAM_END;
3335             goto inf_leave;
3336         case BAD:
3337             ret = Z_DATA_ERROR;
3338             goto inf_leave;
3339         case MEM:
3340             return Z_MEM_ERROR;
3341         case SYNC:
3342         default:
3343             return Z_STREAM_ERROR;
3344         }
3345 
3346     /*
3347        Return from inflate(), updating the total counts and the check value.
3348        If there was no progress during the inflate() call, return a buffer
3349        error.  Call updatewindow() to create and/or update the window state.
3350        Note: a memory error from inflate() is non-recoverable.
3351      */
3352   inf_leave:
3353     RESTORE();
3354     if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
3355         if (updatewindow(strm, out)) {
3356             state->mode = MEM;
3357             return Z_MEM_ERROR;
3358         }
3359     in -= strm->avail_in;
3360     out -= strm->avail_out;
3361     strm->total_in += in;
3362     strm->total_out += out;
3363     state->total += out;
3364     if (state->wrap && out)
3365         strm->adler = state->check =
3366             UPDATE(state->check, strm->next_out - out, out);
3367     strm->data_type = state->bits + (state->last ? 64 : 0) +
3368                       (state->mode == TYPE ? 128 : 0);
3369     if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
3370         ret = Z_BUF_ERROR;
3371     return ret;
3372 }
3373 
3374 int ZEXPORT inflateEnd(strm)
3375 z_streamp strm;
3376 {
3377     struct inflate_state FAR *state;
3378     if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
3379         return Z_STREAM_ERROR;
3380     state = (struct inflate_state FAR *)strm->state;
3381     if (state->window != Z_NULL) ZFREE(strm, state->window);
3382     ZFREE(strm, strm->state);
3383     strm->state = Z_NULL;
3384     Tracev((stderr, "inflate: end\n"));
3385     return Z_OK;
3386 }
3387 
3388 int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
3389 z_streamp strm;
3390 const Bytef *dictionary;
3391 uInt dictLength;
3392 {
3393     struct inflate_state FAR *state;
3394     unsigned long id;
3395 
3396     /* check state */
3397     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
3398     state = (struct inflate_state FAR *)strm->state;
3399     if (state->wrap != 0 && state->mode != DICT)
3400         return Z_STREAM_ERROR;
3401 
3402     /* check for correct dictionary id */
3403     if (state->mode == DICT) {
3404         id = adler32(0L, Z_NULL, 0);
3405         id = adler32(id, dictionary, dictLength);
3406         if (id != state->check)
3407             return Z_DATA_ERROR;
3408     }
3409 
3410     /* copy dictionary to window */
3411     if (updatewindow(strm, strm->avail_out)) {
3412         state->mode = MEM;
3413         return Z_MEM_ERROR;
3414     }
3415     if (dictLength > state->wsize) {
3416         zmemcpy(state->window, dictionary + dictLength - state->wsize,
3417                 state->wsize);
3418         state->whave = state->wsize;
3419     }
3420     else {
3421         zmemcpy(state->window + state->wsize - dictLength, dictionary,
3422                 dictLength);
3423         state->whave = dictLength;
3424     }
3425     state->havedict = 1;
3426     Tracev((stderr, "inflate:   dictionary set\n"));
3427     return Z_OK;
3428 }
3429 
3430 int ZEXPORT inflateGetHeader(strm, head)
3431 z_streamp strm;
3432 gz_headerp head;
3433 {
3434     struct inflate_state FAR *state;
3435 
3436     /* check state */
3437     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
3438     state = (struct inflate_state FAR *)strm->state;
3439     if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
3440 
3441     /* save header structure */
3442     state->head = head;
3443 #ifdef GUNZIP
3444     head->done = 0;
3445 #endif
3446     return Z_OK;
3447 }
3448 
3449 /*
3450    Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
3451    or when out of input.  When called, *have is the number of pattern bytes
3452    found in order so far, in 0..3.  On return *have is updated to the new
3453    state.  If on return *have equals four, then the pattern was found and the
3454    return value is how many bytes were read including the last byte of the
3455    pattern.  If *have is less than four, then the pattern has not been found
3456    yet and the return value is len.  In the latter case, syncsearch() can be
3457    called again with more data and the *have state.  *have is initialized to
3458    zero for the first call.
3459  */
3460 local unsigned syncsearch(have, buf, len)
3461 unsigned FAR *have;
3462 unsigned char FAR *buf;
3463 unsigned len;
3464 {
3465     unsigned got;
3466     unsigned next;
3467 
3468     got = *have;
3469     next = 0;
3470     while (next < len && got < 4) {
3471         if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
3472             got++;
3473         else if (buf[next])
3474             got = 0;
3475         else
3476             got = 4 - got;
3477         next++;
3478     }
3479     *have = got;
3480     return next;
3481 }
3482 
3483 int ZEXPORT inflateSync(strm)
3484 z_streamp strm;
3485 {
3486     unsigned len;               /* number of bytes to look at or looked at */
3487     unsigned long in, out;      /* temporary to save total_in and total_out */
3488     unsigned char buf[4];       /* to restore bit buffer to byte string */
3489     struct inflate_state FAR *state;
3490 
3491     /* check parameters */
3492     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
3493     state = (struct inflate_state FAR *)strm->state;
3494     if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
3495 
3496     /* if first time, start search in bit buffer */
3497     if (state->mode != SYNC) {
3498         state->mode = SYNC;
3499         state->hold <<= state->bits & 7;
3500         state->bits -= state->bits & 7;
3501         len = 0;
3502         while (state->bits >= 8) {
3503             buf[len++] = (unsigned char)(state->hold);
3504             state->hold >>= 8;
3505             state->bits -= 8;
3506         }
3507         state->have = 0;
3508         syncsearch(&(state->have), buf, len);
3509     }
3510 
3511     /* search available input */
3512     len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
3513     strm->avail_in -= len;
3514     strm->next_in += len;
3515     strm->total_in += len;
3516 
3517     /* return no joy or set up to restart inflate() on a new block */
3518     if (state->have != 4) return Z_DATA_ERROR;
3519     in = strm->total_in;  out = strm->total_out;
3520     inflateReset(strm);
3521     strm->total_in = in;  strm->total_out = out;
3522     state->mode = TYPE;
3523     return Z_OK;
3524 }
3525 
3526 /*
3527    Returns true if inflate is currently at the end of a block generated by
3528    Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
3529    implementation to provide an additional safety check. PPP uses
3530    Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
3531    block. When decompressing, PPP checks that at the end of input packet,
3532    inflate is waiting for these length bytes.
3533  */
3534 int ZEXPORT inflateSyncPoint(strm)
3535 z_streamp strm;
3536 {
3537     struct inflate_state FAR *state;
3538 
3539     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
3540     state = (struct inflate_state FAR *)strm->state;
3541     return state->mode == STORED && state->bits == 0;
3542 }
3543 
3544 int ZEXPORT inflateCopy(dest, source)
3545 z_streamp dest;
3546 z_streamp source;
3547 {
3548     struct inflate_state FAR *state;
3549     struct inflate_state FAR *copy;
3550     unsigned char FAR *window;
3551     unsigned wsize;
3552 
3553     /* check input */
3554     if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
3555         source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
3556         return Z_STREAM_ERROR;
3557     state = (struct inflate_state FAR *)source->state;
3558 
3559     /* allocate space */
3560     copy = (struct inflate_state FAR *)
3561            ZALLOC(source, 1, sizeof(struct inflate_state));
3562     if (copy == Z_NULL) return Z_MEM_ERROR;
3563     window = Z_NULL;
3564     if (state->window != Z_NULL) {
3565         window = (unsigned char FAR *)
3566                  ZALLOC(source, ((unsigned int)1) << state->wbits, sizeof(unsigned char));
3567         if (window == Z_NULL) {
3568             ZFREE(source, copy);
3569             return Z_MEM_ERROR;
3570         }
3571     }
3572 
3573     /* copy state */
3574     zmemcpy(dest, source, sizeof(z_stream));
3575     zmemcpy(copy, state, sizeof(struct inflate_state));
3576     if (state->lencode >= state->codes &&
3577         state->lencode <= state->codes + ENOUGH - 1) {
3578         copy->lencode = copy->codes + (state->lencode - state->codes);
3579         copy->distcode = copy->codes + (state->distcode - state->codes);
3580     }
3581     copy->next = copy->codes + (state->next - state->codes);
3582     if (window != Z_NULL) {
3583         wsize = ((unsigned int)1) << state->wbits;
3584         zmemcpy(window, state->window, wsize);
3585     }
3586     copy->window = window;
3587     dest->state = (struct internal_state FAR *)copy;
3588     return Z_OK;
3589 }
3590 
3591 #endif /* _INFLATE_C */
3592 
3593 #ifndef _GZIO_C
3594 #define _GZIO_C		1
3595 
3596 typedef voidp gzFile;
3597 
3598 #ifndef Z_BUFSIZE
3599 #  ifdef MAXSEG_64K
3600 #    define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
3601 #  else
3602 #    define Z_BUFSIZE 16384
3603 #  endif
3604 #endif
3605 #ifndef Z_PRINTF_BUFSIZE
3606 #  define Z_PRINTF_BUFSIZE 4096
3607 #endif
3608 
3609 #ifdef __MVS__
3610 #  pragma map (fdopen , "\174\174FDOPEN")
3611    FILE *fdopen(int, const char *);
3612 #endif
3613 
3614 #if 0 && !_PACKAGE_ast
3615 #ifndef STDC
3616 extern voidp  malloc OF((uInt size));
3617 extern void   free   OF((voidpf ptr));
3618 #endif
3619 #endif
3620 
3621 #define ALLOC(size) malloc(size)
3622 #define TRYFREE(p) {if (p) free(p);}
3623 
3624 static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
3625 
3626 /* gzip flag byte */
3627 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
3628 #define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
3629 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
3630 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
3631 #define COMMENT      0x10 /* bit 4 set: file comment present */
3632 #define RESERVED     0xE0 /* bits 5..7: reserved */
3633 
3634 typedef struct gz_stream {
3635     z_stream stream;
3636     int      z_err;   /* error code for last stream operation */
3637     int      z_eof;   /* set if end of input file */
3638     FILE     *file;   /* .gz file */
3639     Byte     *inbuf;  /* input buffer */
3640     Byte     *outbuf; /* output buffer */
3641     uLong    crc;     /* crc32 of uncompressed data */
3642     char     *msg;    /* error message */
3643     char     *path;   /* path name for debugging only */
3644     int      transparent; /* 1 if input file is not a .gz file */
3645 #if _PACKAGE_ast
3646     int      fatal;   /* fatal stream error => all other ops fail */
3647     int      nocrc;   /* 1 to skip 'r' crc checks */
3648     int      noclose; /* 1 to skip destroy fclose */
3649     int      verified;/* 2-byte magic read and verified ('v') */
3650 #endif
3651     char     mode;    /* 'w' or 'r' */
3652     z_off_t  start;   /* start of compressed data in file (header skipped) */
3653     z_off_t  in;      /* bytes into deflate or inflate */
3654     z_off_t  out;     /* bytes out of deflate or inflate */
3655     int      back;    /* one character push-back */
3656     int      last;    /* true if push-back is last character */
3657 } gz_stream;
3658 
3659 
3660 local gzFile gz_open      OF((const char *path, const char *mode, FILE* fp));
3661 local int    get_byte     OF((gz_stream *s));
3662 local void   check_header OF((gz_stream *s));
3663 local int    destroy      OF((gz_stream *s));
3664 local uLong  getLong      OF((gz_stream *s));
3665 
3666 /* ===========================================================================
3667      Opens a gzip (.gz) file for reading or writing. The mode parameter
3668    is as in fopen ("rb" or "wb"). The file is given either by FILE pointer
3669    or path name (if fp == 0).
3670      gz_open returns NULL if the file could not be opened or if there was
3671    insufficient memory to allocate the (de)compression state; errno
3672    can be checked to distinguish the two cases (if errno is zero, the
3673    zlib error is Z_MEM_ERROR).
3674 */
3675 local gzFile gz_open (path, mode, fp)
3676     const char *path;
3677     const char *mode;
3678     FILE       *fp;
3679 {
3680     int err;
3681     int level = Z_DEFAULT_COMPRESSION; /* compression level */
3682     int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
3683     char *p = (char*)mode;
3684     gz_stream *s;
3685     char fmode[80]; /* copy of mode, without the compression level */
3686     char *m = fmode;
3687 
3688     if (!path || !mode) return Z_NULL;
3689 
3690     s = (gz_stream *)ALLOC(sizeof(gz_stream));
3691     if (!s) return Z_NULL;
3692 
3693     s->stream.zalloc = (alloc_func)0;
3694     s->stream.zfree = (free_func)0;
3695     s->stream.opaque = (voidpf)0;
3696     s->stream.next_in = s->inbuf = Z_NULL;
3697     s->stream.next_out = s->outbuf = Z_NULL;
3698     s->stream.avail_in = s->stream.avail_out = 0;
3699     s->file = NULL;
3700     s->z_err = Z_OK;
3701     s->z_eof = 0;
3702     s->in = 0;
3703     s->out = 0;
3704     s->back = EOF;
3705     s->crc = crc32(0L, Z_NULL, 0);
3706 #if _PACKAGE_ast
3707     s->fatal = 0;
3708     s->nocrc = 0;
3709     s->verified = 0;
3710 #endif
3711     s->msg = NULL;
3712     s->transparent = 0;
3713 
3714     s->path = (char*)ALLOC(strlen(path)+1);
3715     if (s->path == NULL) {
3716         return destroy(s), (gzFile)Z_NULL;
3717     }
3718     strcpy(s->path, path); /* do this early for debugging */
3719 
3720     s->mode = '\0';
3721     do {
3722         if (*p == 'r') s->mode = 'r';
3723         if (*p == 'w' || *p == 'a') s->mode = 'w';
3724         if (*p >= '0' && *p <= '9') {
3725             level = *p - '0';
3726         } else if (*p == 'f') {
3727           strategy = Z_FILTERED;
3728         } else if (*p == 'h') {
3729           strategy = Z_HUFFMAN_ONLY;
3730         } else if (*p == 'R') {
3731           strategy = Z_RLE;
3732 #if _PACKAGE_ast
3733 	} else if (*p == 'n') {
3734 	  s->nocrc = 1;
3735 	} else if (*p == 'o') {
3736 	  s->noclose = 1;
3737 	} else if (*p == 'v') {
3738 	  s->verified = 1;
3739 #endif
3740         } else {
3741             *m++ = *p; /* copy the mode */
3742         }
3743     } while (*p++ && m != fmode + sizeof(fmode));
3744     if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
3745 
3746     if (s->mode == 'w') {
3747 #ifdef NO_GZCOMPRESS
3748         err = Z_STREAM_ERROR;
3749 #else
3750 #if _PACKAGE_ast
3751         s->nocrc = 0;
3752 #endif
3753         err = deflateInit2(&(s->stream), level,
3754                            Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
3755         /* windowBits is passed < 0 to suppress zlib header */
3756 
3757         s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
3758 #endif
3759         if (err != Z_OK || s->outbuf == Z_NULL) {
3760             return destroy(s), (gzFile)Z_NULL;
3761         }
3762     } else {
3763         s->stream.next_in  = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
3764 
3765         err = inflateInit2(&(s->stream), -MAX_WBITS);
3766         /* windowBits is passed < 0 to tell that there is no zlib header.
3767          * Note that in this case inflate *requires* an extra "dummy" byte
3768          * after the compressed stream in order to complete decompression and
3769          * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
3770          * present after the compressed stream.
3771          */
3772         if (err != Z_OK || s->inbuf == Z_NULL) {
3773             return destroy(s), (gzFile)Z_NULL;
3774         }
3775     }
3776     s->stream.avail_out = Z_BUFSIZE;
3777 
3778     errno = 0;
3779 
3780     if (!(s->file = fp) && !(s->file = F_OPEN(path, fmode))) {
3781         return destroy(s), (gzFile)Z_NULL;
3782     }
3783     if (s->mode == 'w') {
3784         /* Write a very simple .gz header:
3785          */
3786         fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
3787              Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
3788         s->start = 10L;
3789         /* We use 10L instead of ftell(s->file) to because ftell causes an
3790          * fflush on some systems. This version of the library doesn't use
3791          * start anyway in write mode, so this initialization is not
3792          * necessary.
3793          */
3794     } else {
3795 #if _PACKAGE_ast
3796 	sfsetbuf(s->file, (void*)s->file, SF_UNBOUND);
3797 #endif
3798         check_header(s); /* skip the .gz header */
3799         s->start = (z_off_t)(ftell(s->file) - s->stream.avail_in);
3800     }
3801 
3802     return (gzFile)s;
3803 }
3804 
3805 /* ===========================================================================
3806      Associate a gzFile with the stdio stream fp.
3807 */
3808 gzFile ZEXPORT gzfopen (fp, mode)
3809     FILE* fp;
3810     const char *mode;
3811 {
3812     FILE* sp = (FILE*)fp;
3813     char name[20];
3814 
3815     if (!sp)
3816        return (gzFile)Z_NULL;
3817     sprintf(name, "<fd:%d>", fileno(sp)); /* for debugging */
3818 
3819     return gz_open (name, mode, sp);
3820 }
3821 
3822 /* ===========================================================================
3823      Read a byte from a gz_stream; update next_in and avail_in. Return EOF
3824    for end of file.
3825    IN assertion: the stream s has been sucessfully opened for reading.
3826 */
3827 local int get_byte(s)
3828     gz_stream *s;
3829 {
3830     if (s->z_eof) return EOF;
3831     if (s->stream.avail_in == 0) {
3832         errno = 0;
3833         s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
3834         if (s->stream.avail_in == 0) {
3835             s->z_eof = 1;
3836             if (ferror(s->file)) s->z_err = Z_ERRNO;
3837             return EOF;
3838         }
3839         s->stream.next_in = s->inbuf;
3840     }
3841     s->stream.avail_in--;
3842     return *(s->stream.next_in)++;
3843 }
3844 
3845 /* ===========================================================================
3846       Check the gzip header of a gz_stream opened for reading. Set the stream
3847     mode to transparent if the gzip magic header is not present; set s->err
3848     to Z_DATA_ERROR if the magic header is present but the rest of the header
3849     is incorrect.
3850     IN assertion: the stream s has already been created sucessfully;
3851        s->stream.avail_in is zero for the first time, but may be non-zero
3852        for concatenated .gz files.
3853 */
3854 local void check_header(s)
3855     gz_stream *s;
3856 {
3857     int method; /* method byte */
3858     int flags;  /* flags byte */
3859     uInt len;
3860     int c;
3861 
3862 #if _PACKAGE_ast
3863     if (!s->verified)
3864         for (len = 0; len < 2; len++) {
3865 	    c = get_byte(s);
3866 	    if (c != gz_magic[len]) {
3867 	        if (len != 0) s->stream.avail_in++, s->stream.next_in--;
3868 	        if (c != EOF) {
3869 		    s->stream.avail_in++, s->stream.next_in--;
3870 		    s->transparent = 1;
3871 	        }
3872 	        s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END;
3873 	        return;
3874 	    }
3875         }
3876 #else
3877     /* Assure two bytes in the buffer so we can peek ahead -- handle case
3878        where first byte of header is at the end of the buffer after the last
3879        gzip segment */
3880     len = s->stream.avail_in;
3881     if (len < 2) {
3882         if (len) s->inbuf[0] = s->stream.next_in[0];
3883         errno = 0;
3884         len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
3885         if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
3886         s->stream.avail_in += len;
3887         s->stream.next_in = s->inbuf;
3888         if (s->stream.avail_in < 2) {
3889             s->transparent = s->stream.avail_in;
3890             return;
3891         }
3892     }
3893 
3894     /* Peek ahead to check the gzip magic header */
3895     if (s->stream.next_in[0] != gz_magic[0] ||
3896         s->stream.next_in[1] != gz_magic[1]) {
3897         s->transparent = 1;
3898         return;
3899     }
3900     s->stream.avail_in -= 2;
3901     s->stream.next_in += 2;
3902 #endif
3903 
3904     /* Check the rest of the gzip header */
3905     method = get_byte(s);
3906     flags = get_byte(s);
3907     if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
3908         s->z_err = Z_DATA_ERROR;
3909         return;
3910     }
3911 
3912     /* Discard time, xflags and OS code: */
3913     for (len = 0; len < 6; len++) (void)get_byte(s);
3914 
3915     if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
3916         len  =  (uInt)get_byte(s);
3917         len += ((uInt)get_byte(s))<<8;
3918         /* len is garbage if EOF but the loop below will quit anyway */
3919         while (len-- != 0 && get_byte(s) != EOF) ;
3920     }
3921     if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
3922         while ((c = get_byte(s)) != 0 && c != EOF) ;
3923     }
3924     if ((flags & COMMENT) != 0) {   /* skip the .gz file comment */
3925         while ((c = get_byte(s)) != 0 && c != EOF) ;
3926     }
3927     if ((flags & HEAD_CRC) != 0) {  /* skip the header crc */
3928         for (len = 0; len < 2; len++) (void)get_byte(s);
3929     }
3930     s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
3931 }
3932 
3933  /* ===========================================================================
3934  * Cleanup then free the given gz_stream. Return a zlib error code.
3935    Try freeing in the reverse order of allocations.
3936  */
3937 local int destroy (s)
3938     gz_stream *s;
3939 {
3940     int err = Z_OK;
3941 
3942     if (!s) return Z_STREAM_ERROR;
3943 
3944     TRYFREE(s->msg);
3945 
3946     if (s->stream.state != NULL) {
3947         if (s->mode == 'w') {
3948 #ifdef NO_GZCOMPRESS
3949             err = Z_STREAM_ERROR;
3950 #else
3951             err = deflateEnd(&(s->stream));
3952 #endif
3953         } else if (s->mode == 'r') {
3954             err = inflateEnd(&(s->stream));
3955         }
3956     }
3957 #if _PACKAGE_ast
3958     if (s->file != NULL && (s->noclose ? (s->mode == 'r' ? 0 : fflush(s->file)) : fclose(s->file))) {
3959 #else
3960     if (s->file != NULL && fclose(s->file)) {
3961 #endif
3962 #ifdef ESPIPE
3963         if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
3964 #endif
3965             err = Z_ERRNO;
3966     }
3967     if (s->z_err < 0) err = s->z_err;
3968 
3969     TRYFREE(s->inbuf);
3970     TRYFREE(s->outbuf);
3971     TRYFREE(s->path);
3972     TRYFREE(s);
3973     return err;
3974 }
3975 
3976 /* ===========================================================================
3977      Reads the given number of uncompressed bytes from the compressed file.
3978    gzread returns the number of bytes actually read (0 for end of file).
3979 */
3980 int ZEXPORT gzread (file, buf, len)
3981     gzFile file;
3982     voidp buf;
3983     unsigned len;
3984 {
3985     gz_stream *s = (gz_stream*)file;
3986     Bytef *start = (Bytef*)buf; /* starting point for crc computation */
3987     Byte  *next_out; /* == stream.next_out but not forced far (for MSDOS) */
3988 
3989     if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
3990 
3991     if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
3992     if (s->z_err == Z_STREAM_END) return 0;  /* EOF */
3993 
3994     next_out = (Byte*)buf;
3995     s->stream.next_out = (Bytef*)buf;
3996     s->stream.avail_out = len;
3997 
3998     if (s->stream.avail_out && s->back != EOF) {
3999         *next_out++ = s->back;
4000         s->stream.next_out++;
4001         s->stream.avail_out--;
4002         s->back = EOF;
4003         s->out++;
4004         start++;
4005         if (s->last) {
4006             s->z_err = Z_STREAM_END;
4007             return 1;
4008         }
4009     }
4010 
4011     while (s->stream.avail_out != 0) {
4012 
4013         if (s->transparent) {
4014             /* Copy first the lookahead bytes: */
4015             uInt n = s->stream.avail_in;
4016             if (n > s->stream.avail_out) n = s->stream.avail_out;
4017             if (n > 0) {
4018                 zmemcpy(s->stream.next_out, s->stream.next_in, n);
4019                 next_out += n;
4020                 s->stream.next_out = next_out;
4021                 s->stream.next_in   += n;
4022                 s->stream.avail_out -= n;
4023                 s->stream.avail_in  -= n;
4024             }
4025             if (s->stream.avail_out > 0) {
4026                 s->stream.avail_out -=
4027                     (uInt)fread(next_out, 1, s->stream.avail_out, s->file);
4028             }
4029             len -= s->stream.avail_out;
4030             s->in  += len;
4031             s->out += len;
4032             if (len == 0) s->z_eof = 1;
4033             return (int)len;
4034         }
4035         if (s->stream.avail_in == 0 && !s->z_eof) {
4036 
4037             errno = 0;
4038             s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
4039             if (s->stream.avail_in == 0) {
4040                 s->z_eof = 1;
4041                 if (ferror(s->file)) {
4042                     s->z_err = Z_ERRNO;
4043                     break;
4044                 }
4045             }
4046             s->stream.next_in = s->inbuf;
4047         }
4048         s->in += s->stream.avail_in;
4049         s->out += s->stream.avail_out;
4050         s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
4051         s->in -= s->stream.avail_in;
4052         s->out -= s->stream.avail_out;
4053 
4054         if (s->z_err == Z_STREAM_END) {
4055             /* Check CRC and original size */
4056 #if _PACKAGE_ast
4057 	    if (!s->nocrc)
4058 #endif
4059             s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
4060             start = s->stream.next_out;
4061 
4062 #if _PACKAGE_ast
4063 	    if (getLong(s) != s->crc && !s->nocrc) {
4064 #else
4065 	    if (getLong(s) != s->crc) {
4066 #endif
4067                 s->z_err = Z_DATA_ERROR;
4068             } else {
4069                 (void)getLong(s);
4070                 /* The uncompressed length returned by above getlong() may be
4071                  * different from s->out in case of concatenated .gz files.
4072                  * Check for such files:
4073                  */
4074                 check_header(s);
4075                 if (s->z_err == Z_OK) {
4076                     inflateReset(&(s->stream));
4077 #if _PACKAGE_ast
4078                     if (!s->nocrc)
4079 #endif
4080                     s->crc = crc32(0L, Z_NULL, 0);
4081 #if _PACKAGE_ast
4082                     else
4083 			s->z_err = Z_STREAM_END;
4084 #endif
4085                 }
4086             }
4087         }
4088         if (s->z_err != Z_OK || s->z_eof) break;
4089     }
4090 #if _PACKAGE_ast
4091     if (!s->nocrc)
4092 #endif
4093     s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
4094 
4095     if (len == s->stream.avail_out &&
4096         (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
4097         return -1;
4098     return (int)(len - s->stream.avail_out);
4099 }
4100 
4101 /* ===========================================================================
4102    Reads a long in LSB order from the given gz_stream. Sets z_err in case
4103    of error.
4104 */
4105 local uLong getLong (s)
4106     gz_stream *s;
4107 {
4108     uLong x = (uLong)get_byte(s);
4109     int c;
4110 
4111     x += ((uLong)get_byte(s))<<8;
4112     x += ((uLong)get_byte(s))<<16;
4113     c = get_byte(s);
4114     if (c == EOF) s->z_err = Z_DATA_ERROR;
4115     x += ((uLong)c)<<24;
4116     return x;
4117 }
4118 
4119 #endif /* _GZIO_C */
4120 
4121 #endif /* _GUNZIP_H */
4122 
4123 #undef	local
4124 
4125 #ifndef _RATZ_C
4126 #define _RATZ_C		1
4127 
4128 #include <sys/stat.h>
4129 
4130 #ifndef S_IRUSR
4131 #define S_IRUSR		0400
4132 #endif
4133 #ifndef S_IWUSR
4134 #define S_IWUSR		0200
4135 #endif
4136 #ifndef S_IXUSR
4137 #define S_IXUSR		0100
4138 #endif
4139 #ifndef S_IRGRP
4140 #define S_IRGRP		0040
4141 #endif
4142 #ifndef S_IWGRP
4143 #define S_IWGRP		0020
4144 #endif
4145 #ifndef S_IXGRP
4146 #define S_IXGRP		0010
4147 #endif
4148 #ifndef S_IROTH
4149 #define S_IROTH		0004
4150 #endif
4151 #ifndef S_IWOTH
4152 #define S_IWOTH		0002
4153 #endif
4154 #ifndef S_IXOTH
4155 #define S_IXOTH		0001
4156 #endif
4157 
4158 /*
4159  * Standard Archive Format
4160  * USTAR - Uniform Standard Tape ARchive
4161  */
4162 
4163 #define TBLOCK		512
4164 #define NAMSIZ		100
4165 #define PFXSIZ		155
4166 
4167 #define TMODLEN		8
4168 #define TUIDLEN		8
4169 #define TGIDLEN		8
4170 #define TSIZLEN		12
4171 #define TMTMLEN		12
4172 #define TCKSLEN		8
4173 
4174 #define TMAGIC		"ustar"		/* ustar and a null		*/
4175 #define TMAGLEN		6
4176 #define TVERSION	"00"		/* 00 and no null		*/
4177 #define TVERSLEN	2
4178 #define TUNMLEN		32
4179 #define TGNMLEN		32
4180 #define TDEVLEN		8
4181 #define TPADLEN		12
4182 
4183 /*
4184  * values used in typeflag field
4185  */
4186 
4187 #define REGTYPE		'0'		/* regular file			*/
4188 #define AREGTYPE	0		/* alternate REGTYPE		*/
4189 #define LNKTYPE		'1'		/* hard link			*/
4190 #define SYMTYPE		'2'		/* soft link			*/
4191 #define CHRTYPE		'3'		/* character special		*/
4192 #define BLKTYPE		'4'		/* block special		*/
4193 #define DIRTYPE		'5'		/* directory			*/
4194 #define FIFOTYPE	'6'		/* FIFO special			*/
4195 #define CONTTYPE	'7'		/* reserved			*/
4196 #define SOKTYPE		'8'		/* socket -- reserved		*/
4197 #define VERTYPE		'V'		/* version -- reserved		*/
4198 #define EXTTYPE		'x'		/* extended header -- reserved	*/
4199 
4200 /*
4201  * bits used in mode field
4202  */
4203 
4204 #define TSUID		04000		/* set uid on exec		*/
4205 #define TSGID		02000		/* set gid on exec		*/
4206 #define TSVTX		01000		/* sticky bit -- reserved	*/
4207 
4208 /*
4209  * file permissions
4210  */
4211 
4212 #define TUREAD		00400		/* read by owner		*/
4213 #define TUWRITE		00200		/* write by owner		*/
4214 #define TUEXEC		00100		/* execute by owner		*/
4215 #define TGREAD		00040		/* read by group		*/
4216 #define TGWRITE		00020		/* execute by group		*/
4217 #define TGEXEC		00010		/* write by group		*/
4218 #define TOREAD		00004		/* read by other		*/
4219 #define TOWRITE		00002		/* write by other		*/
4220 #define TOEXEC		00001		/* execute by other		*/
4221 
4222 #define TAR_SUMASK	((1L<<(TCKSLEN-1)*3)-1)
4223 
4224 typedef struct
4225 {
4226 	char		name[NAMSIZ];
4227 	char		mode[TMODLEN];
4228 	char		uid[TUIDLEN];
4229 	char		gid[TGIDLEN];
4230 	char		size[TSIZLEN];
4231 	char		mtime[TMTMLEN];
4232 	char		chksum[TCKSLEN];
4233 	char		typeflag;
4234 	char		linkname[NAMSIZ];
4235 	char		magic[TMAGLEN];
4236 	char		version[TVERSLEN];
4237 	char		uname[TUNMLEN];
4238 	char		gname[TGNMLEN];
4239 	char		devmajor[TDEVLEN];
4240 	char		devminor[TDEVLEN];
4241 	char		prefix[PFXSIZ];
4242 	char		pad[TPADLEN];
4243 } Header_t;
4244 
4245 static struct
4246 {
4247 	char*		id;
4248 	unsigned long	blocks;
4249 	unsigned long	files;
4250 } state;
4251 
4252 #if !_PACKAGE_ast
4253 
4254 static void
4255 usage()
4256 {
4257 #if defined(_SEAR_EXEC) || defined(_SEAR_SEEK)
4258 	fprintf(stderr, "Usage: %s [-ciklmntvV] [ [no]name[=value] ... ]\n", state.id);
4259 #else
4260 	fprintf(stderr, "Usage: %s [-clmntvV] < input.tgz\n", state.id);
4261 #endif
4262 	exit(2);
4263 }
4264 
4265 #endif
4266 
4267 /*
4268  * the X/Open dd EBCDIC table
4269  */
4270 
4271 static const unsigned char a2e[] =
4272 {
4273 	0000,0001,0002,0003,0067,0055,0056,0057,
4274 	0026,0005,0045,0013,0014,0015,0016,0017,
4275 	0020,0021,0022,0023,0074,0075,0062,0046,
4276 	0030,0031,0077,0047,0034,0035,0036,0037,
4277 	0100,0132,0177,0173,0133,0154,0120,0175,
4278 	0115,0135,0134,0116,0153,0140,0113,0141,
4279 	0360,0361,0362,0363,0364,0365,0366,0367,
4280 	0370,0371,0172,0136,0114,0176,0156,0157,
4281 	0174,0301,0302,0303,0304,0305,0306,0307,
4282 	0310,0311,0321,0322,0323,0324,0325,0326,
4283 	0327,0330,0331,0342,0343,0344,0345,0346,
4284 	0347,0350,0351,0255,0340,0275,0232,0155,
4285 	0171,0201,0202,0203,0204,0205,0206,0207,
4286 	0210,0211,0221,0222,0223,0224,0225,0226,
4287 	0227,0230,0231,0242,0243,0244,0245,0246,
4288 	0247,0250,0251,0300,0117,0320,0137,0007,
4289 	0040,0041,0042,0043,0044,0025,0006,0027,
4290 	0050,0051,0052,0053,0054,0011,0012,0033,
4291 	0060,0061,0032,0063,0064,0065,0066,0010,
4292 	0070,0071,0072,0073,0004,0024,0076,0341,
4293 	0101,0102,0103,0104,0105,0106,0107,0110,
4294 	0111,0121,0122,0123,0124,0125,0126,0127,
4295 	0130,0131,0142,0143,0144,0145,0146,0147,
4296 	0150,0151,0160,0161,0162,0163,0164,0165,
4297 	0166,0167,0170,0200,0212,0213,0214,0215,
4298 	0216,0217,0220,0152,0233,0234,0235,0236,
4299 	0237,0240,0252,0253,0254,0112,0256,0257,
4300 	0260,0261,0262,0263,0264,0265,0266,0267,
4301 	0270,0271,0272,0273,0274,0241,0276,0277,
4302 	0312,0313,0314,0315,0316,0317,0332,0333,
4303 	0334,0335,0336,0337,0352,0353,0354,0355,
4304 	0356,0357,0372,0373,0374,0375,0376,0377,
4305 };
4306 
4307 /*
4308  * the X/Open dd IBM table
4309  */
4310 
4311 static const unsigned char a2i[] =
4312 {
4313 	0000,0001,0002,0003,0067,0055,0056,0057,
4314 	0026,0005,0045,0013,0014,0015,0016,0017,
4315 	0020,0021,0022,0023,0074,0075,0062,0046,
4316 	0030,0031,0077,0047,0034,0035,0036,0037,
4317 	0100,0132,0177,0173,0133,0154,0120,0175,
4318 	0115,0135,0134,0116,0153,0140,0113,0141,
4319 	0360,0361,0362,0363,0364,0365,0366,0367,
4320 	0370,0371,0172,0136,0114,0176,0156,0157,
4321 	0174,0301,0302,0303,0304,0305,0306,0307,
4322 	0310,0311,0321,0322,0323,0324,0325,0326,
4323 	0327,0330,0331,0342,0343,0344,0345,0346,
4324 	0347,0350,0351,0255,0340,0275,0137,0155,
4325 	0171,0201,0202,0203,0204,0205,0206,0207,
4326 	0210,0211,0221,0222,0223,0224,0225,0226,
4327 	0227,0230,0231,0242,0243,0244,0245,0246,
4328 	0247,0250,0251,0300,0117,0320,0241,0007,
4329 	0040,0041,0042,0043,0044,0025,0006,0027,
4330 	0050,0051,0052,0053,0054,0011,0012,0033,
4331 	0060,0061,0032,0063,0064,0065,0066,0010,
4332 	0070,0071,0072,0073,0004,0024,0076,0341,
4333 	0101,0102,0103,0104,0105,0106,0107,0110,
4334 	0111,0121,0122,0123,0124,0125,0126,0127,
4335 	0130,0131,0142,0143,0144,0145,0146,0147,
4336 	0150,0151,0160,0161,0162,0163,0164,0165,
4337 	0166,0167,0170,0200,0212,0213,0214,0215,
4338 	0216,0217,0220,0232,0233,0234,0235,0236,
4339 	0237,0240,0252,0253,0254,0255,0256,0257,
4340 	0260,0261,0262,0263,0264,0265,0266,0267,
4341 	0270,0271,0272,0273,0274,0275,0276,0277,
4342 	0312,0313,0314,0315,0316,0317,0332,0333,
4343 	0334,0335,0336,0337,0352,0353,0354,0355,
4344 	0356,0357,0372,0373,0374,0375,0376,0377,
4345 };
4346 
4347 /*
4348  * the mvs OpenEdition EBCDIC table
4349  */
4350 
4351 static const unsigned char a2o[] =
4352 {
4353 	0000,0001,0002,0003,0067,0055,0056,0057,
4354 	0026,0005,0025,0013,0014,0015,0016,0017,
4355 	0020,0021,0022,0023,0074,0075,0062,0046,
4356 	0030,0031,0077,0047,0034,0035,0036,0037,
4357 	0100,0132,0177,0173,0133,0154,0120,0175,
4358 	0115,0135,0134,0116,0153,0140,0113,0141,
4359 	0360,0361,0362,0363,0364,0365,0366,0367,
4360 	0370,0371,0172,0136,0114,0176,0156,0157,
4361 	0174,0301,0302,0303,0304,0305,0306,0307,
4362 	0310,0311,0321,0322,0323,0324,0325,0326,
4363 	0327,0330,0331,0342,0343,0344,0345,0346,
4364 	0347,0350,0351,0255,0340,0275,0137,0155,
4365 	0171,0201,0202,0203,0204,0205,0206,0207,
4366 	0210,0211,0221,0222,0223,0224,0225,0226,
4367 	0227,0230,0231,0242,0243,0244,0245,0246,
4368 	0247,0250,0251,0300,0117,0320,0241,0007,
4369 	0040,0041,0042,0043,0044,0045,0006,0027,
4370 	0050,0051,0052,0053,0054,0011,0012,0033,
4371 	0060,0061,0032,0063,0064,0065,0066,0010,
4372 	0070,0071,0072,0073,0004,0024,0076,0377,
4373 	0101,0252,0112,0261,0237,0262,0152,0265,
4374 	0273,0264,0232,0212,0260,0312,0257,0274,
4375 	0220,0217,0352,0372,0276,0240,0266,0263,
4376 	0235,0332,0233,0213,0267,0270,0271,0253,
4377 	0144,0145,0142,0146,0143,0147,0236,0150,
4378 	0164,0161,0162,0163,0170,0165,0166,0167,
4379 	0254,0151,0355,0356,0353,0357,0354,0277,
4380 	0200,0375,0376,0373,0374,0272,0256,0131,
4381 	0104,0105,0102,0106,0103,0107,0234,0110,
4382 	0124,0121,0122,0123,0130,0125,0126,0127,
4383 	0214,0111,0315,0316,0313,0317,0314,0341,
4384 	0160,0335,0336,0333,0334,0215,0216,0337,
4385 };
4386 
4387 /*
4388  * ascii text vs. control
4389  */
4390 
4391 static const unsigned char ascii_text[] =
4392 {
4393 	0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,
4394 	1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
4395 	1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
4396 	1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
4397 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4398 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4399 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4400 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4401 };
4402 
4403 static int
4404 block(fp, gz, buf)
4405 FILE*	fp;
4406 gzFile	gz;
4407 char*	buf;
4408 {
4409 	int	r;
4410 
4411 	if (gz)
4412 		r = gzread(gz, buf, sizeof(Header_t)) == sizeof(Header_t);
4413 	else
4414 		r = fread(buf, sizeof(Header_t), 1, fp) == 1;
4415 	if (r)
4416 		state.blocks++;
4417 	return r;
4418 }
4419 
4420 static int
4421 skip(fp, gz, buf, n)
4422 FILE*		fp;
4423 gzFile		gz;
4424 char*		buf;
4425 unsigned long	n;
4426 {
4427 	while (n > 0)
4428 	{
4429 		if (!block(fp, gz, buf))
4430 		{
4431 			fprintf(stderr, "%s: unexpected EOF\n", state.id);
4432 			return 1;
4433 		}
4434 		if (n <= sizeof(Header_t))
4435 			break;
4436 		n -= sizeof(Header_t);
4437 	}
4438 	return 0;
4439 }
4440 
4441 static unsigned long
4442 number(s)
4443 register char*	s;
4444 {
4445 	unsigned long	n = 0;
4446 
4447 	while (*s == ' ')
4448 		s++;
4449 	while (*s >= '0' && *s <= '7')
4450 		n = (n << 3) + (*s++ - '0');
4451 	return n;
4452 }
4453 
4454 #if defined(_SEAR_EXEC) || defined(_SEAR_SEEK)
4455 
4456 #ifndef PATH_MAX
4457 #define PATH_MAX	256
4458 #endif
4459 
4460 #define EXIT(n)	return(sear_exec((char*)0,(char**)0,(char*)0,(n)))
4461 
4462 static int	sear_stdin;
4463 static char*	sear_tmp;
4464 static char	sear_buf[PATH_MAX];
4465 
4466 static int
4467 sear_seek(off_t offset, int tmp)
4468 {
4469 	int	n;
4470 	char	cmd[PATH_MAX];
4471 
4472 	GetModuleFileName(NULL, cmd, sizeof(cmd));
4473 	sear_stdin = dup(0);
4474 	close(0);
4475 	if (open(cmd, O_BINARY|O_RDONLY) || lseek(0, offset, 0) != offset)
4476 	{
4477 		fprintf(stderr, "%s: %s: cannot seek to data offset\n", state.id, cmd);
4478 		return -1;
4479 	}
4480 	if (tmp)
4481 	{
4482 		if ((n = GetTempPath(sizeof(cmd), cmd)) <= 0 || n > sizeof(cmd))
4483 		{
4484 			fprintf(stderr, "%s: cannot determine temporary directory path\n", state.id);
4485 			return -1;
4486 		}
4487 		if (!GetTempFileName(cmd, "SEA", 0, sear_buf))
4488 		{
4489 			fprintf(stderr, "%s: cannot determine temporary file path\n", state.id);
4490 			return -1;
4491 		}
4492 		sear_tmp = sear_buf;
4493 		if (!DeleteFile(sear_tmp))
4494 		{
4495 			fprintf(stderr, "%s: %s: cannot initialize temporary directory\n", state.id, sear_tmp);
4496 			return -1;
4497 		}
4498 		if (!CreateDirectory(sear_tmp, NULL))
4499 		{
4500 			fprintf(stderr, "%s: %s: cannot create temporary directory\n", state.id, sear_tmp);
4501 			return -1;
4502 		}
4503 		if (!SetCurrentDirectory(sear_tmp))
4504 		{
4505 			fprintf(stderr, "%s: %s: cannot cd to temporary directory\n", state.id, sear_tmp);
4506 			return -1;
4507 		}
4508 	}
4509 	return 0;
4510 }
4511 
4512 /*
4513  * remove dir and its subdirs
4514  */
4515 
4516 static void
4517 sear_rm_r(char* dir)
4518 {
4519 	WIN32_FIND_DATA	info;
4520 	HANDLE		hp;
4521 
4522 	if (!SetCurrentDirectory(dir))
4523 		return;
4524 	if ((hp = FindFirstFile("*.*", &info)) != INVALID_HANDLE_VALUE)
4525 	{
4526 		do
4527 		{
4528 			if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
4529 			{
4530 				if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
4531 					SetFileAttributes(info.cFileName, info.dwFileAttributes & ~FILE_ATTRIBUTE_READONLY);
4532 				DeleteFile(info.cFileName);
4533 			}
4534 			else if (info.cFileName[0] != '.' || info.cFileName[1] != 0 && (info.cFileName[1] != '.' || info.cFileName[2] != 0))
4535 				sear_rm_r(info.cFileName);
4536 		} while(FindNextFile(hp, &info));
4537 		FindClose(hp);
4538 	}
4539 	if (SetCurrentDirectory(".."))
4540 		RemoveDirectory(dir);
4541 }
4542 
4543 /*
4544  * system(3) without PATH search that should work on all windows variants
4545  */
4546 
4547 static int
4548 sear_system(const char* command, int nowindow)
4549 {
4550 	PROCESS_INFORMATION	pinfo;
4551 	STARTUPINFO		sinfo;
4552 	char*			cp;
4553 	char			path[PATH_MAX];
4554 	int			n = *command == '"';
4555 	DWORD			flags = NORMAL_PRIORITY_CLASS;
4556 
4557 	strncpy(path, &command[n], PATH_MAX - 4);
4558 	n = n ? '"' : ' ';
4559 	for (cp = path; *cp; *cp++)
4560 		if (*cp == n)
4561 			break;
4562 	*cp = 0;
4563 	if (GetFileAttributes(path) == 0xffffffff && GetLastError() == ERROR_FILE_NOT_FOUND)
4564 		strcpy(cp, ".exe");
4565 	ZeroMemory(&sinfo, sizeof(sinfo));
4566 	if (nowindow)
4567 		flags |= CREATE_NO_WINDOW;
4568 	if (!CreateProcess(path, (char*)command, 0, 0, TRUE, flags, NULL, NULL, &sinfo, &pinfo))
4569 		n = GetLastError() == ERROR_FILE_NOT_FOUND ? 127 : 126;
4570 	else
4571 	{
4572 		CloseHandle(pinfo.hThread);
4573 		WaitForSingleObject(pinfo.hProcess, INFINITE);
4574 		if (!GetExitCodeProcess(pinfo.hProcess, &n))
4575 			n = 1;
4576 		CloseHandle(pinfo.hProcess);
4577 		Sleep(2 * 1000);
4578 	}
4579 	return n;
4580 }
4581 
4582 /*
4583  * copy t to f but no farther than e
4584  * next t returned
4585  */
4586 
4587 static char*
4588 copy(char* t, const char* f, char* e)
4589 {
4590 	while (t < e && *f)
4591 		*t++ = *f++;
4592 	return t;
4593 }
4594 
4595 /*
4596  * execute cmd, chdir .., and remove sear_tmp
4597  */
4598 
4599 static int
4600 sear_exec(const char* cmd, char* const* arg, char* operands, int code)
4601 {
4602 	const char*	a;
4603 	char*		b;
4604 	char*		e;
4605 	int		r;
4606 	int		sh;
4607 	int		nowindow;
4608 	char		buf[1024];
4609 
4610 	fflush(stdout);
4611 	fflush(stderr);
4612 	if (sear_tmp)
4613 	{
4614 		close(0);
4615 		dup(sear_stdin);
4616 		close(sear_stdin);
4617 		nowindow = 0;
4618 		if (cmd)
4619 		{
4620 			if (arg)
4621 				for (r = 0; arg[r]; r++)
4622 					if (!strcmp(arg[r], "remote"))
4623 					{
4624 						nowindow = 1;
4625 						break;
4626 					}
4627 			sh = 0;
4628 			for (a = cmd; *a && *a != ' '; a++)
4629 				if (a[0] == '.' && a[1] == 's' && a[2] == 'h' && (!a[3] || a[3] == ' '))
4630 				{
4631 					sh = 1;
4632 					break;
4633 				}
4634 			b = buf;
4635 			e = buf + sizeof(buf) - 1;
4636 			if (sh || arg)
4637 			{
4638 				if (sh)
4639 				{
4640 					b = copy(b, "ksh.exe ", e);
4641 					if (*cmd && *cmd != '/')
4642 						b = copy(b, "./", e);
4643 				}
4644 				b = copy(b, cmd, e);
4645 				while (a = *arg++)
4646 				{
4647 					if ((e - b) < 3)
4648 						break;
4649 					b = copy(b, " \"", e);
4650 					b = copy(b, a, e);
4651 					b = copy(b, "\"", e);
4652 				}
4653 			}
4654 			if (operands)
4655 			{
4656 				if (b == buf)
4657 					b = copy(b, cmd, e);
4658 				b = copy(b, " -- ", e);
4659 				b = copy(b, operands, e);
4660 			}
4661 			if (b > buf)
4662 			{
4663 				*b = 0;
4664 				cmd = (const char*)buf;
4665 			}
4666 			r = sear_system(cmd, nowindow);
4667 		}
4668 		else
4669 			r = code;
4670 		if (code >= 0)
4671 			sear_rm_r(sear_tmp);
4672 	}
4673 	else
4674 		r = cmd ? 0 : code;
4675 	return r;
4676 }
4677 
4678 #else
4679 
4680 #define EXIT(n)	return(n)
4681 
4682 #endif
4683 
4684 int
4685 main(argc, argv)
4686 int	argc;
4687 char**	argv;
4688 {
4689 	register int		c;
4690 	register char*		s;
4691 	register char*		t;
4692 	register char*		e;
4693 	unsigned long		n;
4694 	unsigned long		m;
4695 	const unsigned char*	a2x;
4696 	int			clear;
4697 	int			list;
4698 	int			local;
4699 	int			meter;
4700 	int			unzip;
4701 	int			verbose;
4702 	unsigned int		mode;
4703 	unsigned long		total;
4704 	off_t			pos;
4705 	gzFile			gz;
4706 	FILE*			fp;
4707 	Header_t		header;
4708 	unsigned char		num[4];
4709 	char			path[sizeof(header.prefix) + sizeof(header.name) + 4];
4710 	char			buf[sizeof(header)];
4711 #if defined(_SEAR_OPTS)
4712 	char*			opts[4];
4713 #endif
4714 
4715 #if defined(_SEAR_EXEC) || defined(_SEAR_SEEK)
4716 	int			install = 1;
4717 #endif
4718 
4719 	setmode(0, O_BINARY);
4720 	setmode(1, O_BINARY);
4721 	clear = 0;
4722 	list = 0;
4723 	local = 0;
4724 	meter = 0;
4725 	unzip = 0;
4726 	verbose = 0;
4727 	if (s = *argv)
4728 	{
4729 		t = s;
4730 		while (*s)
4731 			if (*s++ == '/')
4732 				t = s;
4733 		if (!strcmp(t, "gunzip"))
4734 			unzip = 1;
4735 		state.id = t;
4736 	}
4737 	else
4738 		state.id = "ratz";
4739 	switch ('~')
4740 	{
4741 	case 0241:
4742 		switch ('\n')
4743 		{
4744 		case 0025:
4745 			a2x = a2o;
4746 			break;
4747 		default:
4748 			a2x = a2e;
4749 			break;
4750 		}
4751 		break;
4752 	case 0137:
4753 		a2x = a2i;
4754 		break;
4755 	default:
4756 		a2x = 0;
4757 		break;
4758 	}
4759 #if defined(_SEAR_OPTS)
4760 	opts[0] = argv[0];
4761 	opts[1] = _SEAR_OPTS;
4762 	opts[2] = argv[1];
4763 	opts[3] = 0;
4764 	argv = opts;
4765 #endif
4766 #if _PACKAGE_ast
4767 	error_info.id = state.id;
4768 	for (;;)
4769 	{
4770 		switch (optget(argv, usage))
4771 		{
4772 		case 'c':
4773 			unzip = 1;
4774 			continue;
4775 #if defined(_SEAR_EXEC) || defined(_SEAR_SEEK)
4776 		case 'i':
4777 			install = 0;
4778 			continue;
4779 		case 'k':
4780 			install = -1;
4781 			continue;
4782 #endif
4783 		case 'l':
4784 			local = 1;
4785 			continue;
4786 		case 'm':
4787 			meter = 1;
4788 			continue;
4789 		case 'n':
4790 			a2x = 0;
4791 			continue;
4792 		case 't':
4793 			list = 1;
4794 			continue;
4795 		case 'v':
4796 			verbose = 1;
4797 			continue;
4798 		case 'V':
4799 			sfprintf(sfstdout, "%s\n", id + 10);
4800 			return 0;
4801 		case '?':
4802 			error(ERROR_USAGE|4, "%s", opt_info.arg);
4803 			continue;
4804 		case ':':
4805 			error(2, "%s", opt_info.arg);
4806 			continue;
4807 		}
4808 		break;
4809 	}
4810 	if (error_info.errors)
4811 		error(ERROR_USAGE|4, "%s", optusage(NiL));
4812 	argv += opt_info.index;
4813 #else
4814 	while ((s = *++argv) && *s == '-' && *(s + 1))
4815 	{
4816 		if (*(s + 1) == '-')
4817 		{
4818 			if (!*(s + 2))
4819 			{
4820 				argv++;
4821 				break;
4822 			}
4823 			usage();
4824 			break;
4825 		}
4826 		for (;;)
4827 		{
4828 			switch (c = *++s)
4829 			{
4830 			case 0:
4831 				break;
4832 			case 'c':
4833 				unzip = 1;
4834 				continue;
4835 #if defined(_SEAR_EXEC) || defined(_SEAR_SEEK)
4836 			case 'i':
4837 				install = 0;
4838 				continue;
4839 			case 'k':
4840 				install = -1;
4841 				continue;
4842 #endif
4843 			case 'l':
4844 				local = 1;
4845 				continue;
4846 			case 'm':
4847 				meter = 1;
4848 				continue;
4849 			case 'n':
4850 				a2x = 0;
4851 				continue;
4852 			case 't':
4853 				list = 1;
4854 				continue;
4855 			case 'v':
4856 				verbose = 1;
4857 				continue;
4858 			case 'V':
4859 				fprintf(stdout, "%s\n", id + 10);
4860 				return 0;
4861 			default:
4862 				fprintf(stderr, "%s: -%c: unknown option\n", state.id, c);
4863 				/*FALLTHROUGH*/
4864 			case '?':
4865 				usage();
4866 				break;
4867 			}
4868 			break;
4869 		}
4870 	}
4871 #endif
4872 
4873 #if defined(_SEAR_SEEK)
4874 	if (sear_seek((off_t)_SEAR_SEEK, install && !list))
4875 	{
4876 		Sleep(2 * 1000);
4877 		return 1;
4878 	}
4879 #endif
4880 
4881 	/*
4882 	 * commit on the first gzip magic char
4883 	 */
4884 
4885 	if ((c = getchar()) == EOF)
4886 		EXIT(0);
4887 	ungetc(c, stdin);
4888 	if (c != gz_magic[0])
4889 		gz = 0;
4890 	else if (!(gz = gzfopen(stdin, FOPEN_READ)))
4891 	{
4892 		fprintf(stderr, "%s: gunzip open error\n", state.id);
4893 		EXIT(1);
4894 	}
4895 	if (unzip)
4896 	{
4897 		if (!gz)
4898 		{
4899 			fprintf(stderr, "%s: not a gzip file\n", state.id);
4900 			EXIT(1);
4901 		}
4902 		while ((c = gzread(gz, buf, sizeof(buf))) > 0)
4903 			if (fwrite(buf, c, 1, stdout) != 1)
4904 			{
4905 				fprintf(stderr, "%s: write error\n", state.id);
4906 				EXIT(1);
4907 			}
4908 		if (c < 0)
4909 		{
4910 			fprintf(stderr, "%s: read error\n", state.id);
4911 			EXIT(1);
4912 		}
4913 		if (fflush(stdout))
4914 		{
4915 			fprintf(stderr, "%s: flush error\n", state.id);
4916 			EXIT(1);
4917 		}
4918 		EXIT(0);
4919 	}
4920 	if (meter)
4921 	{
4922 		if ((pos = lseek(0, (off_t)0, SEEK_CUR)) < 0)
4923 			meter = 0;
4924 		else
4925 		{
4926 			if (lseek(0, (off_t)(-4), SEEK_END) < 0 || read(0, num, 4) != 4)
4927 				meter = 0;
4928 			else if (!(total = ((num[0]|(num[1]<<8)|(num[2]<<16)|(num[3]<<24)) + sizeof(Header_t) - 1) / sizeof(Header_t)))
4929 				total = 1;
4930 			lseek(0, pos, SEEK_SET);
4931 		}
4932 	}
4933 
4934 	/*
4935 	 * loop on all the header blocks
4936 	 */
4937 
4938 	while (block(stdin, gz, (char*)&header))
4939 	{
4940 		/*
4941 		 * last 2 blocks are NUL
4942 		 */
4943 
4944 		if (!*header.name)
4945 			break;
4946 
4947 		/*
4948 		 * verify the checksum
4949 		 */
4950 
4951 		s = header.chksum;
4952 		e = header.chksum + sizeof(header.chksum);
4953 		if (a2x)
4954 		{
4955 			for (; s < e; s++)
4956 				*s = a2x[*(unsigned char*)s];
4957 			s = header.chksum;
4958 		}
4959 		n = number(s) & TAR_SUMASK;
4960 		while (s < e)
4961 			*s++ = 040;
4962 		m = 0;
4963 		s = (char*)&header;
4964 		e = (char*)&header + sizeof(header);
4965 		while (s < e)
4966 			m += *(unsigned char*)s++;
4967 		m &= TAR_SUMASK;
4968 		if (m != n)
4969 		{
4970 			if (state.files)
4971 				fprintf(stderr, "%s: archive corrupted\n", state.id);
4972 			else
4973 				fprintf(stderr, "%s: not a tar archive\n", state.id);
4974 			fprintf(stderr, "check sum %lu != %lu\n", m, n);
4975 			EXIT(1);
4976 		}
4977 
4978 		/*
4979 		 * convert to the native charset
4980 		 */
4981 
4982 		if (a2x)
4983 			for (e = (s = (char*)&header) + sizeof(header); s < e; s++)
4984 				*s = a2x[*(unsigned char*)s];
4985 
4986 		/*
4987 		 * get the pathname, type and size
4988 		 */
4989 
4990 		state.files++;
4991 		t = path;
4992 		if (!strncmp(header.magic, TMAGIC, sizeof(header.magic)) && *header.prefix)
4993 		{
4994 			s = header.prefix;
4995 			e = header.prefix + sizeof(header.prefix);
4996 			while (s < e && (c = *s++))
4997 				*t++ = c;
4998 			*t++ = '/';
4999 		}
5000 		s = header.name;
5001 		e = header.name + sizeof(header.name);
5002 		while (s < e && (c = *s++))
5003 			*t++ = c;
5004 		*t = 0;
5005 
5006 		/*
5007 		 * verify the dir prefix
5008 		 */
5009 
5010 		t = 0;
5011 		s = path;
5012 		while (*s)
5013 			if (*s++ == '/')
5014 				t = s;
5015 		if (t)
5016 		{
5017 			*--t = 0;
5018 			if (!list && access(path, 0))
5019 			{
5020 				s = path;
5021 				do
5022 				{
5023 					if (!(c = *s) || c == '/')
5024 					{
5025 						*s = 0;
5026 						if (access(path, 0) && mkdir(path, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH))
5027 						{
5028 							fprintf(stderr, "%s: %s: cannot create directory\n", state.id, path);
5029 							EXIT(1);
5030 						}
5031 						*s = c;
5032 					}
5033 				} while (*s++);
5034 			}
5035 			if (*(t + 1))
5036 				*t = '/';
5037 			else
5038 				header.typeflag = DIRTYPE;
5039 		}
5040 
5041 		/*
5042 		 * check for non-local paths
5043 		 */
5044 
5045 		if (local && (path[0] == '/' || path[0] == '.' && path[1] == '.' && (!path[2] || path[2] == '/')))
5046 		{
5047 			fprintf(stderr, "%s: %s: non-local path rejected", state.id, path);
5048 			if ((header.typeflag == REGTYPE || header.typeflag == AREGTYPE) && (n = number(header.size)))
5049 				while (n > 0)
5050 				{
5051 					if (!block(stdin, gz, buf))
5052 					{
5053 						fprintf(stderr, "%s: unexpected EOF\n", state.id);
5054 						EXIT(1);
5055 					}
5056 					if (n <= sizeof(header))
5057 						break;
5058 					n -= sizeof(header);
5059 				}
5060 			continue;
5061 		}
5062 
5063 		/*
5064 		 * create and grab the data
5065 		 */
5066 
5067 		n = number(header.mode);
5068 		mode = 0;
5069 		if (n & TUREAD)
5070 			mode |= S_IRUSR;
5071 		if (n & TUWRITE)
5072 			mode |= S_IWUSR;
5073 		if (n & TUEXEC)
5074 			mode |= S_IXUSR;
5075 		if (n & TGREAD)
5076 			mode |= S_IRGRP;
5077 		if (n & TGWRITE)
5078 			mode |= S_IWGRP;
5079 		if (n & TGEXEC)
5080 			mode |= S_IXGRP;
5081 		if (n & TOREAD)
5082 			mode |= S_IROTH;
5083 		if (n & TOWRITE)
5084 			mode |= S_IWOTH;
5085 		if (n & TOEXEC)
5086 			mode |= S_IXOTH;
5087 		if (list || meter)
5088 		{
5089 			if (meter)
5090 			{
5091 				int	i;
5092 				int	j;
5093 				int	k;
5094 				int	n;
5095 				int	p;
5096 				char	bar[METER_parts + 1];
5097 
5098 				for (s = path; *s; s++)
5099 					if (s[0] == ' ' && s[1] == '-' && s[2] == '-' && s[3] == ' ')
5100 						break;
5101 				if (*s)
5102 				{
5103 					if (clear)
5104 					{
5105 						fprintf(stderr, "%*s", clear, "\r");
5106 						clear = 0;
5107 					}
5108 					fprintf(stderr, "\n%s\n\n", path);
5109 				}
5110 				else
5111 				{
5112 					n = (int)strlen(s = path);
5113 					p = (state.blocks * 100) / total;
5114 					if (n > (METER_width - METER_parts - 1))
5115 					{
5116 						s += n - (METER_width - METER_parts - 1);
5117 						n = METER_width - METER_parts - 1;
5118 					}
5119 					j = n + METER_parts + 2;
5120 					if (!clear)
5121 						clear = j + 5;
5122 					if ((k = clear - j - 5) < 0)
5123 						k = 0;
5124 					if ((i = (p / (100 / METER_parts))) >= sizeof(bar))
5125 						i = sizeof(bar) - 1;
5126 					n = 0;
5127 					while (n < i)
5128 						bar[n++] = '*';
5129 					while (n < sizeof(bar) - 1)
5130 						bar[n++] = ' ';
5131 					bar[n] = 0;
5132 					clear = fprintf(stderr, "%02d%% |%s| %s%*s", p, bar, s, k, "\r");
5133 				}
5134 			}
5135 			else
5136 			{
5137 				if (verbose)
5138 				{
5139 					switch (header.typeflag)
5140 					{
5141 					case REGTYPE:
5142 					case AREGTYPE:
5143 						c = '-';
5144 						break;
5145 					case DIRTYPE:
5146 						c = 'd';
5147 						break;
5148 					case LNKTYPE:
5149 						c = 'h';
5150 						break;
5151 					case SYMTYPE:
5152 						c = 'l';
5153 						break;
5154 					default:
5155 						c = '?';
5156 						break;
5157 					}
5158 					printf("%c", c);
5159 					m = 0400;
5160 					while (m)
5161 					{
5162 						printf("%c", (n & m) ? 'r' : '-');
5163 						m >>= 1;
5164 						printf("%c", (n & m) ? 'w' : '-');
5165 						m >>= 1;
5166 						printf("%c", (n & m) ? 'x' : '-');
5167 						m >>= 1;
5168 					}
5169 					printf(" %10lu ", number(header.size));
5170 				}
5171 				switch (header.typeflag)
5172 				{
5173 				case LNKTYPE:
5174 					printf("%s == %s\n", path, header.linkname);
5175 					break;
5176 				case SYMTYPE:
5177 					printf("%s => %s\n", path, header.linkname);
5178 					break;
5179 				default:
5180 					printf("%s\n", path);
5181 					break;
5182 				}
5183 			}
5184 			if (list)
5185 			{
5186 				if (skip(stdin, gz, buf, number(header.size)))
5187 					EXIT(1);
5188 				continue;
5189 			}
5190 		}
5191 		else if (verbose)
5192 			printf("%s\n", path);
5193 		switch (header.typeflag)
5194 		{
5195 		case REGTYPE:
5196 		case AREGTYPE:
5197 			while (!(fp = fopen(path, FOPEN_WRITE)))
5198 				if (unlink(path))
5199 				{
5200 					fprintf(stderr, "%s: warning: %s: cannot create file\n", state.id, path);
5201 					break;
5202 				}
5203 			n = number(header.size);
5204 			c = a2x ? 0 : -1;
5205 			while (n > 0)
5206 			{
5207 				if (!block(stdin, gz, buf))
5208 				{
5209 					fprintf(stderr, "%s: unexpected EOF\n", state.id);
5210 					EXIT(1);
5211 				}
5212 				switch (c)
5213 				{
5214 				case 0:
5215 					if ((m = n) < 4)
5216 					{
5217 						for (e = (s = buf) + m; s < e; s++)
5218 							if (a2x[*(unsigned char*)s] != '\n')
5219 								break;
5220 					}
5221 					else
5222 					{
5223 						if (m > 256)
5224 							m = 256;
5225 						for (e = (s = buf) + m; s < e; s++)
5226 							if (!ascii_text[*(unsigned char*)s])
5227 								break;
5228 					}
5229 					if (s < e)
5230 					{
5231 						c = -1;
5232 						break;
5233 					}
5234 					c = 1;
5235 					/*FALLTHROUGH*/
5236 				case 1:
5237 					for (e = (s = buf) + sizeof(header); s < e; s++)
5238 						*s = a2x[*(unsigned char*)s];
5239 					break;
5240 				}
5241 				if (fp && fwrite(buf, n > sizeof(header) ? sizeof(header) : n, 1, fp) != 1)
5242 				{
5243 					fprintf(stderr, "%s: %s: write error\n", state.id, path);
5244 					EXIT(1);
5245 				}
5246 				if (n <= sizeof(header))
5247 					break;
5248 				n -= sizeof(header);
5249 			}
5250 			if (fp && fclose(fp))
5251 			{
5252 				fprintf(stderr, "%s: %s: write error\n", state.id, path);
5253 				EXIT(1);
5254 			}
5255 			break;
5256 		case DIRTYPE:
5257 			if (access(path, 0) && mkdir(path, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH))
5258 			{
5259 				fprintf(stderr, "%s: %s: cannot create directory\n", state.id, path);
5260 				EXIT(1);
5261 			}
5262 			break;
5263 		case SYMTYPE:
5264 #if defined(S_IFLNK) || defined(S_ISLNK)
5265 			while (symlink(header.linkname, path))
5266 				if (unlink(path))
5267 				{
5268 					fprintf(stderr, "%s: %s: cannot symlink to %s\n", state.id, path, header.linkname);
5269 					EXIT(1);
5270 				}
5271 			continue;
5272 #endif
5273 #if !_WIN32 || _WINIX
5274 		case LNKTYPE:
5275 			while (link(header.linkname, path))
5276 				if (unlink(path))
5277 				{
5278 					fprintf(stderr, "%s: %s: cannot link to %s\n", state.id, path, header.linkname);
5279 					EXIT(1);
5280 				}
5281 			continue;
5282 #endif
5283 		default:
5284 			fprintf(stderr, "%s: %s: file type %c ignored\n", state.id, path, header.typeflag);
5285 			if (skip(stdin, gz, buf, number(header.size)))
5286 				EXIT(1);
5287 			continue;
5288 		}
5289 		if (chmod(path, mode))
5290 			fprintf(stderr, "%s: %s: cannot change mode to %03o\n", state.id, path, mode);
5291 	}
5292 	if (clear)
5293 		fprintf(stderr, "%*s", clear, "\r");
5294 	if (!state.files)
5295 		fprintf(stderr, "%s: warning: empty archive\n", state.id);
5296 	else if (verbose)
5297 		fprintf(stderr, "%lu file%s, %lu block%s\n", state.files, state.files == 1 ? "" : "s", state.blocks, state.blocks == 1 ? "" : "s");
5298 #if defined(_SEAR_EXEC)
5299 #if !defined(_SEAR_ARGS)
5300 #define _SEAR_ARGS	0
5301 #endif
5302 	if (install && sear_exec(_SEAR_EXEC, argv, _SEAR_ARGS, install))
5303 	{
5304 		Sleep(2 * 1000);
5305 		return 1;
5306 	}
5307 #endif
5308 	return 0;
5309 }
5310 
5311 #endif /* _RATZ_C */
5312