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