Transformator

zip

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