Transformator

zip

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