root/OpenSceneGraph/branches/OpenSceneGraph-3.2/src/osgPlugins/zip/unzip.cpp @ 14038

Revision 14038, 148.3 kB (checked in by robert, 4 weeks ago)

Moved widgets from VolumeEditorWidget? to TransferFunctionWidget?, and widget utilities into WidgetUtils?.

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