Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3034 lines
111 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //=============================================================================//
  8. // XZip.cpp Version 1.1
  9. //
  10. // Authors: Mark Adler et al. (see below)
  11. //
  12. // Modified by: Lucian Wischik
  13. // [email protected]
  14. //
  15. // Version 1.0 - Turned C files into just a single CPP file
  16. // - Made them compile cleanly as C++ files
  17. // - Gave them simpler APIs
  18. // - Added the ability to zip/unzip directly in memory without
  19. // any intermediate files
  20. //
  21. // Modified by: Hans Dietrich
  22. // [email protected]
  23. //
  24. // Version 1.1: - Added Unicode support to CreateZip() and ZipAdd()
  25. // - Changed file names to avoid conflicts with Lucian's files
  26. //
  27. ///////////////////////////////////////////////////////////////////////////////
  28. //
  29. // Lucian Wischik's comments:
  30. // --------------------------
  31. // THIS FILE is almost entirely based upon code by Info-ZIP.
  32. // It has been modified by Lucian Wischik.
  33. // The original code may be found at http://www.info-zip.org
  34. // The original copyright text follows.
  35. //
  36. ///////////////////////////////////////////////////////////////////////////////
  37. //
  38. // Original authors' comments:
  39. // ---------------------------
  40. // This is version 2002-Feb-16 of the Info-ZIP copyright and license. The
  41. // definitive version of this document should be available at
  42. // ftp://ftp.info-zip.org/pub/infozip/license.html indefinitely.
  43. //
  44. // Copyright (c) 1990-2002 Info-ZIP. All rights reserved.
  45. //
  46. // For the purposes of this copyright and license, "Info-ZIP" is defined as
  47. // the following set of individuals:
  48. //
  49. // Mark Adler, John Bush, Karl Davis, Harald Denker, Jean-Michel Dubois,
  50. // Jean-loup Gailly, Hunter Goatley, Ian Gorman, Chris Herborth, Dirk Haase,
  51. // Greg Hartwig, Robert Heath, Jonathan Hudson, Paul Kienitz,
  52. // David Kirschbaum, Johnny Lee, Onno van der Linden, Igor Mandrichenko,
  53. // Steve P. Miller, Sergio Monesi, Keith Owens, George Petrov, Greg Roelofs,
  54. // Kai Uwe Rommel, Steve Salisbury, Dave Smith, Christian Spieler,
  55. // Antoine Verheijen, Paul von Behren, Rich Wales, Mike White
  56. //
  57. // This software is provided "as is", without warranty of any kind, express
  58. // or implied. In no event shall Info-ZIP or its contributors be held liable
  59. // for any direct, indirect, incidental, special or consequential damages
  60. // arising out of the use of or inability to use this software.
  61. //
  62. // Permission is granted to anyone to use this software for any purpose,
  63. // including commercial applications, and to alter it and redistribute it
  64. // freely, subject to the following restrictions:
  65. //
  66. // 1. Redistributions of source code must retain the above copyright notice,
  67. // definition, disclaimer, and this list of conditions.
  68. //
  69. // 2. Redistributions in binary form (compiled executables) must reproduce
  70. // the above copyright notice, definition, disclaimer, and this list of
  71. // conditions in documentation and/or other materials provided with the
  72. // distribution. The sole exception to this condition is redistribution
  73. // of a standard UnZipSFX binary as part of a self-extracting archive;
  74. // that is permitted without inclusion of this license, as long as the
  75. // normal UnZipSFX banner has not been removed from the binary or disabled.
  76. //
  77. // 3. Altered versions--including, but not limited to, ports to new
  78. // operating systems, existing ports with new graphical interfaces, and
  79. // dynamic, shared, or static library versions--must be plainly marked
  80. // as such and must not be misrepresented as being the original source.
  81. // Such altered versions also must not be misrepresented as being
  82. // Info-ZIP releases--including, but not limited to, labeling of the
  83. // altered versions with the names "Info-ZIP" (or any variation thereof,
  84. // including, but not limited to, different capitalizations),
  85. // "Pocket UnZip", "WiZ" or "MacZip" without the explicit permission of
  86. // Info-ZIP. Such altered versions are further prohibited from
  87. // misrepresentative use of the Zip-Bugs or Info-ZIP e-mail addresses or
  88. // of the Info-ZIP URL(s).
  89. //
  90. // 4. Info-ZIP retains the right to use the names "Info-ZIP", "Zip", "UnZip",
  91. // "UnZipSFX", "WiZ", "Pocket UnZip", "Pocket Zip", and "MacZip" for its
  92. // own source and binary releases.
  93. //
  94. ///////////////////////////////////////////////////////////////////////////////
  95. #if defined( WIN32) && !defined( _X360 )
  96. #define STRICT
  97. #define WIN32_LEAN_AND_MEAN
  98. #include <windows.h>
  99. #elif !defined(_X360)
  100. #define far
  101. #define near
  102. #define INVALID_HANDLE_VALUE (void*)-1
  103. #define _tzset tzset
  104. #endif
  105. #if defined( _X360 )
  106. #include "xbox/xbox_win32stubs.h"
  107. #endif
  108. #include <time.h>
  109. #include "zip/XZip.h"
  110. #ifdef __clang__
  111. // These clang 3.1 warnings don't seem very useful, and cannot easily be
  112. // avoided in this file.
  113. #pragma GCC diagnostic ignored "-Wdangling-else" // warning: add explicit braces to avoid dangling else [-Wdangling-else]
  114. #endif
  115. #ifdef OSX
  116. #define MAP_ANONYMOUS MAP_ANON
  117. #endif
  118. #ifdef XZIP_NOT_THREAD_SAFE
  119. static ZRESULT lasterrorZ=ZR_OK;
  120. #else
  121. #include "tier0/threadtools.h"
  122. static CThreadLocalInt<ZRESULT> lasterrorZ;
  123. #endif
  124. typedef unsigned char uch; // unsigned 8-bit value
  125. typedef unsigned short ush; // unsigned 16-bit value
  126. typedef unsigned long ulg; // unsigned 32-bit value
  127. typedef size_t extent; // file size
  128. typedef unsigned Pos; // must be at least 32 bits
  129. typedef unsigned IPos; // A Pos is an index in the character window. Pos is used only for parameter passing
  130. #ifndef EOF
  131. #define EOF (-1)
  132. #endif
  133. // Error return values. The values 0..4 and 12..18 follow the conventions
  134. // of PKZIP. The values 4..10 are all assigned to "insufficient memory"
  135. // by PKZIP, so the codes 5..10 are used here for other purposes.
  136. #define ZE_MISS -1 // used by procname(), zipbare()
  137. #define ZE_OK 0 // success
  138. #define ZE_EOF 2 // unexpected end of zip file
  139. #define ZE_FORM 3 // zip file structure error
  140. #define ZE_MEM 4 // out of memory
  141. #define ZE_LOGIC 5 // internal logic error
  142. #define ZE_BIG 6 // entry too large to split
  143. #define ZE_NOTE 7 // invalid comment format
  144. #define ZE_TEST 8 // zip test (-T) failed or out of memory
  145. #define ZE_ABORT 9 // user interrupt or termination
  146. #define ZE_TEMP 10 // error using a temp file
  147. #define ZE_READ 11 // read or seek error
  148. #define ZE_NONE 12 // nothing to do
  149. #define ZE_NAME 13 // missing or empty zip file
  150. #define ZE_WRITE 14 // error writing to a file
  151. #define ZE_CREAT 15 // couldn't open to write
  152. #define ZE_PARMS 16 // bad command line
  153. #define ZE_OPEN 18 // could not open a specified file to read
  154. #define ZE_MAXERR 18 // the highest error number
  155. // internal file attribute
  156. #define UNKNOWN (-1)
  157. #define BINARY 0
  158. #define ASCII 1
  159. #define BEST -1 // Use best method (deflation or store)
  160. #define STORE 0 // Store method
  161. #define DEFLATE 8 // Deflation method
  162. #define CRCVAL_INITIAL 0L
  163. // MSDOS file or directory attributes
  164. #define MSDOS_HIDDEN_ATTR 0x02
  165. #define MSDOS_DIR_ATTR 0x10
  166. // Lengths of headers after signatures in bytes
  167. #define LOCHEAD 26
  168. #define CENHEAD 42
  169. #define ENDHEAD 18
  170. // Definitions for extra field handling:
  171. #define EB_HEADSIZE 4 /* length of a extra field block header */
  172. #define EB_LEN 2 /* offset of data length field in header */
  173. #define EB_UT_MINLEN 1 /* minimal UT field contains Flags byte */
  174. #define EB_UT_FLAGS 0 /* byte offset of Flags field */
  175. #define EB_UT_TIME1 1 /* byte offset of 1st time value */
  176. #define EB_UT_FL_MTIME (1 << 0) /* mtime present */
  177. #define EB_UT_FL_ATIME (1 << 1) /* atime present */
  178. #define EB_UT_FL_CTIME (1 << 2) /* ctime present */
  179. #define EB_UT_LEN(n) (EB_UT_MINLEN + 4 * (n))
  180. #define EB_L_UT_SIZE (EB_HEADSIZE + EB_UT_LEN(3))
  181. #define EB_C_UT_SIZE (EB_HEADSIZE + EB_UT_LEN(1))
  182. // Macros for writing machine integers to little-endian format
  183. #define PUTSH(a,f) {char _putsh_c=(char)((a)&0xff); wfunc(param,&_putsh_c,1); _putsh_c=(char)((a)>>8); wfunc(param,&_putsh_c,1);}
  184. #define PUTLG(a,f) {PUTSH((a) & 0xffff,(f)) PUTSH((a) >> 16,(f))}
  185. // -- Structure of a ZIP file --
  186. // Signatures for zip file information headers
  187. #define LOCSIG 0x04034b50L
  188. #define CENSIG 0x02014b50L
  189. #define ENDSIG 0x06054b50L
  190. #define EXTLOCSIG 0x08074b50L
  191. #define MIN_MATCH 3
  192. #define MAX_MATCH 258
  193. // The minimum and maximum match lengths
  194. #define WSIZE (0x8000)
  195. // Maximum window size = 32K. If you are really short of memory, compile
  196. // with a smaller WSIZE but this reduces the compression ratio for files
  197. // of size > WSIZE. WSIZE must be a power of two in the current implementation.
  198. //
  199. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  200. // Minimum amount of lookahead, except at the end of the input file.
  201. // See deflate.c for comments about the MIN_MATCH+1.
  202. //
  203. #define MAX_DIST (WSIZE-MIN_LOOKAHEAD)
  204. // In order to simplify the code, particularly on 16 bit machines, match
  205. // distances are limited to MAX_DIST instead of WSIZE.
  206. //
  207. // ===========================================================================
  208. // Constants
  209. //
  210. #define MAX_BITS 15
  211. // All codes must not exceed MAX_BITS bits
  212. #define MAX_BL_BITS 7
  213. // Bit length codes must not exceed MAX_BL_BITS bits
  214. #define LENGTH_CODES 29
  215. // number of length codes, not counting the special END_BLOCK code
  216. #define LITERALS 256
  217. // number of literal bytes 0..255
  218. #define END_BLOCK 256
  219. // end of block literal code
  220. #define L_CODES (LITERALS+1+LENGTH_CODES)
  221. // number of Literal or Length codes, including the END_BLOCK code
  222. #define D_CODES 30
  223. // number of distance codes
  224. #define BL_CODES 19
  225. // number of codes used to transfer the bit lengths
  226. #define STORED_BLOCK 0
  227. #define STATIC_TREES 1
  228. #define DYN_TREES 2
  229. // The three kinds of block type
  230. #define LIT_BUFSIZE 0x8000
  231. #define DIST_BUFSIZE LIT_BUFSIZE
  232. // Sizes of match buffers for literals/lengths and distances. There are
  233. // 4 reasons for limiting LIT_BUFSIZE to 64K:
  234. // - frequencies can be kept in 16 bit counters
  235. // - if compression is not successful for the first block, all input data is
  236. // still in the window so we can still emit a stored block even when input
  237. // comes from standard input. (This can also be done for all blocks if
  238. // LIT_BUFSIZE is not greater than 32K.)
  239. // - if compression is not successful for a file smaller than 64K, we can
  240. // even emit a stored file instead of a stored block (saving 5 bytes).
  241. // - creating new Huffman trees less frequently may not provide fast
  242. // adaptation to changes in the input data statistics. (Take for
  243. // example a binary file with poorly compressible code followed by
  244. // a highly compressible string table.) Smaller buffer sizes give
  245. // fast adaptation but have of course the overhead of transmitting trees
  246. // more frequently.
  247. // - I can't count above 4
  248. // The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
  249. // memory at the expense of compression). Some optimizations would be possible
  250. // if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
  251. //
  252. #define REP_3_6 16
  253. // repeat previous bit length 3-6 times (2 bits of repeat count)
  254. #define REPZ_3_10 17
  255. // repeat a zero length 3-10 times (3 bits of repeat count)
  256. #define REPZ_11_138 18
  257. // repeat a zero length 11-138 times (7 bits of repeat count)
  258. #define HEAP_SIZE (2*L_CODES+1)
  259. // maximum heap size
  260. // ===========================================================================
  261. // Local data used by the "bit string" routines.
  262. //
  263. #define Buf_size (8 * 2*sizeof(char))
  264. // Number of bits used within bi_buf. (bi_buf may be implemented on
  265. // more than 16 bits on some systems.)
  266. // Output a 16 bit value to the bit stream, lower (oldest) byte first
  267. #define PUTSHORT(state,w) \
  268. { if (state.bs.out_offset >= state.bs.out_size-1) \
  269. state.flush_outbuf(state.param,state.bs.out_buf, &state.bs.out_offset); \
  270. /* flush may fail, so only write into the buffer if there's actually room (same below) */ \
  271. if (state.bs.out_offset < state.bs.out_size-1) { \
  272. state.bs.out_buf[state.bs.out_offset++] = (char) ((w) & 0xff); \
  273. state.bs.out_buf[state.bs.out_offset++] = (char) ((ush)(w) >> 8); \
  274. } \
  275. }
  276. #define PUTBYTE(state,b) \
  277. { if (state.bs.out_offset >= state.bs.out_size) \
  278. state.flush_outbuf(state.param,state.bs.out_buf, &state.bs.out_offset); \
  279. if (state.bs.out_offset < state.bs.out_size) \
  280. state.bs.out_buf[state.bs.out_offset++] = (char) (b); \
  281. }
  282. // DEFLATE.CPP HEADER
  283. #define HASH_BITS 15
  284. // For portability to 16 bit machines, do not use values above 15.
  285. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  286. #define HASH_MASK (HASH_SIZE-1)
  287. #define WMASK (WSIZE-1)
  288. // HASH_SIZE and WSIZE must be powers of two
  289. #define NIL 0
  290. // Tail of hash chains
  291. #define FAST 4
  292. #define SLOW 2
  293. // speed options for the general purpose bit flag
  294. #define TOO_FAR 4096
  295. // Matches of length 3 are discarded if their distance exceeds TOO_FAR
  296. #define EQUAL 0
  297. // result of memcmp for equal strings
  298. // ===========================================================================
  299. // Local data used by the "longest match" routines.
  300. #define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  301. // Number of bits by which ins_h and del_h must be shifted at each
  302. // input step. It must be such that after MIN_MATCH steps, the oldest
  303. // byte no longer takes part in the hash key, that is:
  304. // H_SHIFT * MIN_MATCH >= HASH_BITS
  305. #define max_insert_length max_lazy_match
  306. // Insert new strings in the hash table only if the match length
  307. // is not greater than this length. This saves time but degrades compression.
  308. // max_insert_length is used only for compression levels <= 3.
  309. const int extra_lbits[LENGTH_CODES] // extra bits for each length code
  310. = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
  311. const int extra_dbits[D_CODES] // extra bits for each distance code
  312. = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  313. const int extra_blbits[BL_CODES]// extra bits for each bit length code
  314. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  315. const uch bl_order[BL_CODES] = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  316. // The lengths of the bit length codes are sent in order of decreasing
  317. // probability, to avoid transmitting the lengths for unused bit length codes.
  318. typedef struct config {
  319. ush good_length; // reduce lazy search above this match length
  320. ush max_lazy; // do not perform lazy search above this match length
  321. ush nice_length; // quit search above this match length
  322. ush max_chain;
  323. } config;
  324. // Values for max_lazy_match, good_match, nice_match and max_chain_length,
  325. // depending on the desired pack level (0..9). The values given below have
  326. // been tuned to exclude worst case performance for pathological files.
  327. // Better values may be found for specific files.
  328. //
  329. const config configuration_table[10] = {
  330. // good lazy nice chain
  331. {0, 0, 0, 0}, // 0 store only
  332. {4, 4, 8, 4}, // 1 maximum speed, no lazy matches
  333. {4, 5, 16, 8}, // 2
  334. {4, 6, 32, 32}, // 3
  335. {4, 4, 16, 16}, // 4 lazy matches */
  336. {8, 16, 32, 32}, // 5
  337. {8, 16, 128, 128}, // 6
  338. {8, 32, 128, 256}, // 7
  339. {32, 128, 258, 1024}, // 8
  340. {32, 258, 258, 4096}};// 9 maximum compression */
  341. // Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  342. // For deflate_fast() (levels <= 3) good is ignored and lazy has a different meaning.
  343. // Data structure describing a single value and its code string.
  344. typedef struct ct_data {
  345. union {
  346. ush freq; // frequency count
  347. ush code; // bit string
  348. } fc;
  349. union {
  350. ush dad; // father node in Huffman tree
  351. ush len; // length of bit string
  352. } dl;
  353. } ct_data;
  354. typedef struct tree_desc {
  355. ct_data *dyn_tree; // the dynamic tree
  356. ct_data *static_tree; // corresponding static tree or NULL
  357. const int *extra_bits; // extra bits for each code or NULL
  358. int extra_base; // base index for extra_bits
  359. int elems; // max number of elements in the tree
  360. int max_length; // max bit length for the codes
  361. int max_code; // largest code with non zero frequency
  362. } tree_desc;
  363. class TTreeState
  364. { public:
  365. TTreeState();
  366. ct_data dyn_ltree[HEAP_SIZE]; // literal and length tree
  367. ct_data dyn_dtree[2*D_CODES+1]; // distance tree
  368. ct_data static_ltree[L_CODES+2]; // the static literal tree...
  369. // ... Since the bit lengths are imposed, there is no need for the L_CODES
  370. // extra codes used during heap construction. However the codes 286 and 287
  371. // are needed to build a canonical tree (see ct_init below).
  372. ct_data static_dtree[D_CODES]; // the static distance tree...
  373. // ... (Actually a trivial tree since all codes use 5 bits.)
  374. ct_data bl_tree[2*BL_CODES+1]; // Huffman tree for the bit lengths
  375. tree_desc l_desc;
  376. tree_desc d_desc;
  377. tree_desc bl_desc;
  378. ush bl_count[MAX_BITS+1]; // number of codes at each bit length for an optimal tree
  379. int heap[2*L_CODES+1]; // heap used to build the Huffman trees
  380. int heap_len; // number of elements in the heap
  381. int heap_max; // element of largest frequency
  382. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  383. // The same heap array is used to build all trees.
  384. uch depth[2*L_CODES+1];
  385. // Depth of each subtree used as tie breaker for trees of equal frequency
  386. uch length_code[MAX_MATCH-MIN_MATCH+1];
  387. // length code for each normalized match length (0 == MIN_MATCH)
  388. uch dist_code[512];
  389. // distance codes. The first 256 values correspond to the distances
  390. // 3 .. 258, the last 256 values correspond to the top 8 bits of
  391. // the 15 bit distances.
  392. int base_length[LENGTH_CODES];
  393. // First normalized length for each code (0 = MIN_MATCH)
  394. int base_dist[D_CODES];
  395. // First normalized distance for each code (0 = distance of 1)
  396. uch far l_buf[LIT_BUFSIZE]; // buffer for literals/lengths
  397. ush far d_buf[DIST_BUFSIZE]; // buffer for distances
  398. uch flag_buf[(LIT_BUFSIZE/8)];
  399. // flag_buf is a bit array distinguishing literals from lengths in
  400. // l_buf, and thus indicating the presence or absence of a distance.
  401. unsigned last_lit; // running index in l_buf
  402. unsigned last_dist; // running index in d_buf
  403. unsigned last_flags; // running index in flag_buf
  404. uch flags; // current flags not yet saved in flag_buf
  405. uch flag_bit; // current bit used in flags
  406. // bits are filled in flags starting at bit 0 (least significant).
  407. // Note: these flags are overkill in the current code since we don't
  408. // take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
  409. ulg opt_len; // bit length of current block with optimal trees
  410. ulg static_len; // bit length of current block with static trees
  411. ulg cmpr_bytelen; // total byte length of compressed file
  412. ulg cmpr_len_bits; // number of bits past 'cmpr_bytelen'
  413. ulg input_len; // total byte length of input file
  414. // input_len is for debugging only since we can get it by other means.
  415. ush *file_type; // pointer to UNKNOWN, BINARY or ASCII
  416. // int *file_method; // pointer to DEFLATE or STORE
  417. };
  418. TTreeState::TTreeState()
  419. { tree_desc a = {dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0}; l_desc = a;
  420. tree_desc b = {dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0}; d_desc = b;
  421. tree_desc c = {bl_tree, NULL, extra_blbits, 0, BL_CODES, MAX_BL_BITS, 0}; bl_desc = c;
  422. last_lit=0;
  423. last_dist=0;
  424. last_flags=0;
  425. }
  426. class TBitState
  427. { public:
  428. int flush_flg;
  429. //
  430. unsigned bi_buf;
  431. // Output buffer. bits are inserted starting at the bottom (least significant
  432. // bits). The width of bi_buf must be at least 16 bits.
  433. int bi_valid;
  434. // Number of valid bits in bi_buf. All bits above the last valid bit
  435. // are always zero.
  436. char *out_buf;
  437. // Current output buffer.
  438. unsigned out_offset;
  439. // Current offset in output buffer.
  440. // On 16 bit machines, the buffer is limited to 64K.
  441. unsigned out_size;
  442. // Size of current output buffer
  443. ulg bits_sent; // bit length of the compressed data only needed for debugging???
  444. };
  445. class TDeflateState
  446. { public:
  447. TDeflateState() {window_size=0;}
  448. uch window[2L*WSIZE];
  449. // Sliding window. Input bytes are read into the second half of the window,
  450. // and move to the first half later to keep a dictionary of at least WSIZE
  451. // bytes. With this organization, matches are limited to a distance of
  452. // WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  453. // performed with a length multiple of the block size. Also, it limits
  454. // the window size to 64K, which is quite useful on MSDOS.
  455. // To do: limit the window size to WSIZE+CBSZ if SMALL_MEM (the code would
  456. // be less efficient since the data would have to be copied WSIZE/CBSZ times)
  457. Pos prev[WSIZE];
  458. // Link to older string with same hash index. To limit the size of this
  459. // array to 64K, this link is maintained only for the last 32K strings.
  460. // An index in this array is thus a window index modulo 32K.
  461. Pos head[HASH_SIZE];
  462. // Heads of the hash chains or NIL. If your compiler thinks that
  463. // HASH_SIZE is a dynamic value, recompile with -DDYN_ALLOC.
  464. ulg window_size;
  465. // window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  466. // input file length plus MIN_LOOKAHEAD.
  467. long block_start;
  468. // window position at the beginning of the current output block. Gets
  469. // negative when the window is moved backwards.
  470. int sliding;
  471. // Set to false when the input file is already in memory
  472. unsigned ins_h; // hash index of string to be inserted
  473. unsigned int prev_length;
  474. // Length of the best match at previous step. Matches not greater than this
  475. // are discarded. This is used in the lazy match evaluation.
  476. unsigned strstart; // start of string to insert
  477. unsigned match_start; // start of matching string
  478. int eofile; // flag set at end of input file
  479. unsigned lookahead; // number of valid bytes ahead in window
  480. unsigned max_chain_length;
  481. // To speed up deflation, hash chains are never searched beyond this length.
  482. // A higher limit improves compression ratio but degrades the speed.
  483. unsigned int max_lazy_match;
  484. // Attempt to find a better match only when the current match is strictly
  485. // smaller than this value. This mechanism is used only for compression
  486. // levels >= 4.
  487. unsigned good_match;
  488. // Use a faster search when the previous match is longer than this
  489. int nice_match; // Stop searching when current match exceeds this
  490. };
  491. typedef struct iztimes {
  492. time_t atime,mtime,ctime;
  493. } iztimes; // access, modify, create times
  494. typedef struct zlist {
  495. ush vem, ver, flg, how; // See central header in zipfile.c for what vem..off are
  496. ulg tim, crc, siz, len;
  497. extent nam, ext, cext, com; // offset of ext must be >= LOCHEAD
  498. ush dsk, att, lflg; // offset of lflg must be >= LOCHEAD
  499. ulg atx, off;
  500. char name[MAX_PATH]; // File name in zip file
  501. char *extra; // Extra field (set only if ext != 0)
  502. char *cextra; // Extra in central (set only if cext != 0)
  503. char *comment; // Comment (set only if com != 0)
  504. char iname[MAX_PATH]; // Internal file name after cleanup
  505. char zname[MAX_PATH]; // External version of internal name
  506. int mark; // Marker for files to operate on
  507. int trash; // Marker for files to delete
  508. int dosflag; // Set to force MSDOS file attributes
  509. struct zlist far *nxt; // Pointer to next header in list
  510. } TZipFileInfo;
  511. class TState;
  512. typedef unsigned (*READFUNC)(TState &state, char *buf,unsigned size);
  513. typedef unsigned (*FLUSHFUNC)(void *param, const char *buf, unsigned *size);
  514. typedef unsigned (*WRITEFUNC)(void *param, const char *buf, unsigned size);
  515. class TState
  516. { public: TState() {err=0;}
  517. //
  518. void *param;
  519. int level; bool seekable;
  520. READFUNC readfunc; FLUSHFUNC flush_outbuf;
  521. TTreeState ts; TBitState bs; TDeflateState ds;
  522. const char *err;
  523. };
  524. #undef Assert
  525. void Assert(TState &state,bool cond, const char *msg)
  526. { if (cond) return;
  527. state.err=msg;
  528. }
  529. void __cdecl Trace(const char *x, ...) {va_list paramList; va_start(paramList, x); paramList; va_end(paramList);}
  530. void __cdecl Tracec(bool ,const char *x, ...) {va_list paramList; va_start(paramList, x); paramList; va_end(paramList);}
  531. // ===========================================================================
  532. // Local (static) routines in this file.
  533. //
  534. void init_block (TState &);
  535. void pqdownheap (TState &,ct_data *tree, int k);
  536. void gen_bitlen (TState &,tree_desc *desc);
  537. void gen_codes (TState &state,ct_data *tree, int max_code);
  538. void build_tree (TState &,tree_desc *desc);
  539. void scan_tree (TState &,ct_data *tree, int max_code);
  540. void send_tree (TState &state,ct_data *tree, int max_code);
  541. int build_bl_tree (TState &);
  542. void send_all_trees (TState &state,int lcodes, int dcodes, int blcodes);
  543. void compress_block (TState &state,ct_data *ltree, ct_data *dtree);
  544. void set_file_type (TState &);
  545. void send_bits (TState &state, int value, int length);
  546. unsigned bi_reverse (unsigned code, int len);
  547. void bi_windup (TState &state);
  548. void copy_block (TState &state,char *buf, unsigned len, int header);
  549. #define send_code(state, c, tree) send_bits(state, tree[c].fc.code, tree[c].dl.len)
  550. // Send a code of the given tree. c and tree must not have side effects
  551. // alternatively...
  552. //#define send_code(state, c, tree)
  553. // { if (state.verbose>1) fprintf(stderr,"\ncd %3d ",(c));
  554. // send_bits(state, tree[c].fc.code, tree[c].dl.len); }
  555. #define d_code(dist) ((dist) < 256 ? state.ts.dist_code[dist] : state.ts.dist_code[256+((dist)>>7)])
  556. // Mapping from a distance to a distance code. dist is the distance - 1 and
  557. // must not have side effects. dist_code[256] and dist_code[257] are never used.
  558. #define Max(a,b) (a >= b ? a : b)
  559. /* the arguments must not have side effects */
  560. /* ===========================================================================
  561. * Allocate the match buffer, initialize the various tables and save the
  562. * location of the internal file attribute (ascii/binary) and method
  563. * (DEFLATE/STORE).
  564. */
  565. void ct_init(TState &state, ush *attr)
  566. {
  567. int n; /* iterates over tree elements */
  568. int bits; /* bit counter */
  569. int length; /* length value */
  570. int code; /* code value */
  571. int dist; /* distance index */
  572. state.ts.file_type = attr;
  573. //state.ts.file_method = method;
  574. state.ts.cmpr_bytelen = state.ts.cmpr_len_bits = 0L;
  575. state.ts.input_len = 0L;
  576. if (state.ts.static_dtree[0].dl.len != 0) return; /* ct_init already called */
  577. /* Initialize the mapping length (0..255) -> length code (0..28) */
  578. length = 0;
  579. for (code = 0; code < LENGTH_CODES-1; code++) {
  580. state.ts.base_length[code] = length;
  581. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  582. state.ts.length_code[length++] = (uch)code;
  583. }
  584. }
  585. Assert(state,length == 256, "ct_init: length != 256");
  586. /* Note that the length 255 (match length 258) can be represented
  587. * in two different ways: code 284 + 5 bits or code 285, so we
  588. * overwrite length_code[255] to use the best encoding:
  589. */
  590. state.ts.length_code[length-1] = (uch)code;
  591. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  592. dist = 0;
  593. for (code = 0 ; code < 16; code++) {
  594. state.ts.base_dist[code] = dist;
  595. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  596. state.ts.dist_code[dist++] = (uch)code;
  597. }
  598. }
  599. Assert(state,dist == 256, "ct_init: dist != 256");
  600. dist >>= 7; /* from now on, all distances are divided by 128 */
  601. for ( ; code < D_CODES; code++) {
  602. state.ts.base_dist[code] = dist << 7;
  603. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  604. state.ts.dist_code[256 + dist++] = (uch)code;
  605. }
  606. }
  607. Assert(state,dist == 256, "ct_init: 256+dist != 512");
  608. /* Construct the codes of the static literal tree */
  609. for (bits = 0; bits <= MAX_BITS; bits++) state.ts.bl_count[bits] = 0;
  610. n = 0;
  611. while (n <= 143) state.ts.static_ltree[n++].dl.len = 8, state.ts.bl_count[8]++;
  612. while (n <= 255) state.ts.static_ltree[n++].dl.len = 9, state.ts.bl_count[9]++;
  613. while (n <= 279) state.ts.static_ltree[n++].dl.len = 7, state.ts.bl_count[7]++;
  614. while (n <= 287) state.ts.static_ltree[n++].dl.len = 8, state.ts.bl_count[8]++;
  615. /* fc.codes 286 and 287 do not exist, but we must include them in the
  616. * tree construction to get a canonical Huffman tree (longest code
  617. * all ones)
  618. */
  619. gen_codes(state,(ct_data *)state.ts.static_ltree, L_CODES+1);
  620. /* The static distance tree is trivial: */
  621. for (n = 0; n < D_CODES; n++) {
  622. state.ts.static_dtree[n].dl.len = 5;
  623. state.ts.static_dtree[n].fc.code = (ush)bi_reverse(n, 5);
  624. }
  625. /* Initialize the first block of the first file: */
  626. init_block(state);
  627. }
  628. /* ===========================================================================
  629. * Initialize a new block.
  630. */
  631. void init_block(TState &state)
  632. {
  633. int n; /* iterates over tree elements */
  634. /* Initialize the trees. */
  635. for (n = 0; n < L_CODES; n++) state.ts.dyn_ltree[n].fc.freq = 0;
  636. for (n = 0; n < D_CODES; n++) state.ts.dyn_dtree[n].fc.freq = 0;
  637. for (n = 0; n < BL_CODES; n++) state.ts.bl_tree[n].fc.freq = 0;
  638. state.ts.dyn_ltree[END_BLOCK].fc.freq = 1;
  639. state.ts.opt_len = state.ts.static_len = 0L;
  640. state.ts.last_lit = state.ts.last_dist = state.ts.last_flags = 0;
  641. state.ts.flags = 0; state.ts.flag_bit = 1;
  642. }
  643. #define SMALLEST 1
  644. /* Index within the heap array of least frequent node in the Huffman tree */
  645. /* ===========================================================================
  646. * Remove the smallest element from the heap and recreate the heap with
  647. * one less element. Updates heap and heap_len.
  648. */
  649. #define pqremove(tree, top) \
  650. {\
  651. top = state.ts.heap[SMALLEST]; \
  652. state.ts.heap[SMALLEST] = state.ts.heap[state.ts.heap_len--]; \
  653. pqdownheap(state,tree, SMALLEST); \
  654. }
  655. /* ===========================================================================
  656. * Compares to subtrees, using the tree depth as tie breaker when
  657. * the subtrees have equal frequency. This minimizes the worst case length.
  658. */
  659. #define smaller(tree, n, m) \
  660. (tree[n].fc.freq < tree[m].fc.freq || \
  661. (tree[n].fc.freq == tree[m].fc.freq && state.ts.depth[n] <= state.ts.depth[m]))
  662. /* ===========================================================================
  663. * Restore the heap property by moving down the tree starting at node k,
  664. * exchanging a node with the smallest of its two sons if necessary, stopping
  665. * when the heap property is re-established (each father smaller than its
  666. * two sons).
  667. */
  668. void pqdownheap(TState &state,ct_data *tree, int k)
  669. {
  670. int v = state.ts.heap[k];
  671. int j = k << 1; /* left son of k */
  672. int htemp; /* required because of bug in SASC compiler */
  673. while (j <= state.ts.heap_len) {
  674. /* Set j to the smallest of the two sons: */
  675. if (j < state.ts.heap_len && smaller(tree, state.ts.heap[j+1], state.ts.heap[j])) j++;
  676. /* Exit if v is smaller than both sons */
  677. htemp = state.ts.heap[j];
  678. if (smaller(tree, v, htemp)) break;
  679. /* Exchange v with the smallest son */
  680. state.ts.heap[k] = htemp;
  681. k = j;
  682. /* And continue down the tree, setting j to the left son of k */
  683. j <<= 1;
  684. }
  685. state.ts.heap[k] = v;
  686. }
  687. /* ===========================================================================
  688. * Compute the optimal bit lengths for a tree and update the total bit length
  689. * for the current block.
  690. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  691. * above are the tree nodes sorted by increasing frequency.
  692. * OUT assertions: the field len is set to the optimal bit length, the
  693. * array bl_count contains the frequencies for each bit length.
  694. * The length opt_len is updated; static_len is also updated if stree is
  695. * not null.
  696. */
  697. void gen_bitlen(TState &state,tree_desc *desc)
  698. {
  699. ct_data *tree = desc->dyn_tree;
  700. const int *extra = desc->extra_bits;
  701. int base = desc->extra_base;
  702. int max_code = desc->max_code;
  703. int max_length = desc->max_length;
  704. ct_data *stree = desc->static_tree;
  705. int h; /* heap index */
  706. int n, m; /* iterate over the tree elements */
  707. int bits; /* bit length */
  708. int xbits; /* extra bits */
  709. ush f; /* frequency */
  710. int overflow = 0; /* number of elements with bit length too large */
  711. for (bits = 0; bits <= MAX_BITS; bits++) state.ts.bl_count[bits] = 0;
  712. /* In a first pass, compute the optimal bit lengths (which may
  713. * overflow in the case of the bit length tree).
  714. */
  715. tree[state.ts.heap[state.ts.heap_max]].dl.len = 0; /* root of the heap */
  716. for (h = state.ts.heap_max+1; h < HEAP_SIZE; h++) {
  717. n = state.ts.heap[h];
  718. bits = tree[tree[n].dl.dad].dl.len + 1;
  719. if (bits > max_length) bits = max_length, overflow++;
  720. tree[n].dl.len = (ush)bits;
  721. /* We overwrite tree[n].dl.dad which is no longer needed */
  722. if (n > max_code) continue; /* not a leaf node */
  723. state.ts.bl_count[bits]++;
  724. xbits = 0;
  725. if (n >= base) xbits = extra[n-base];
  726. f = tree[n].fc.freq;
  727. state.ts.opt_len += (ulg)f * (bits + xbits);
  728. if (stree) state.ts.static_len += (ulg)f * (stree[n].dl.len + xbits);
  729. }
  730. if (overflow == 0) return;
  731. Trace("\nbit length overflow\n");
  732. /* This happens for example on obj2 and pic of the Calgary corpus */
  733. /* Find the first bit length which could increase: */
  734. do {
  735. bits = max_length-1;
  736. while (state.ts.bl_count[bits] == 0) bits--;
  737. state.ts.bl_count[bits]--; /* move one leaf down the tree */
  738. state.ts.bl_count[bits+1] += (ush)2; /* move one overflow item as its brother */
  739. state.ts.bl_count[max_length]--;
  740. /* The brother of the overflow item also moves one step up,
  741. * but this does not affect bl_count[max_length]
  742. */
  743. overflow -= 2;
  744. } while (overflow > 0);
  745. /* Now recompute all bit lengths, scanning in increasing frequency.
  746. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  747. * lengths instead of fixing only the wrong ones. This idea is taken
  748. * from 'ar' written by Haruhiko Okumura.)
  749. */
  750. for (bits = max_length; bits != 0; bits--) {
  751. n = state.ts.bl_count[bits];
  752. while (n != 0) {
  753. m = state.ts.heap[--h];
  754. if (m > max_code) continue;
  755. if (tree[m].dl.len != (ush)bits) {
  756. Trace("code %d bits %d->%d\n", m, tree[m].dl.len, bits);
  757. state.ts.opt_len += ((long)bits-(long)tree[m].dl.len)*(long)tree[m].fc.freq;
  758. tree[m].dl.len = (ush)bits;
  759. }
  760. n--;
  761. }
  762. }
  763. }
  764. /* ===========================================================================
  765. * Generate the codes for a given tree and bit counts (which need not be
  766. * optimal).
  767. * IN assertion: the array bl_count contains the bit length statistics for
  768. * the given tree and the field len is set for all tree elements.
  769. * OUT assertion: the field code is set for all tree elements of non
  770. * zero code length.
  771. */
  772. void gen_codes (TState &state, ct_data *tree, int max_code)
  773. {
  774. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  775. ush code = 0; /* running code value */
  776. int bits; /* bit index */
  777. int n; /* code index */
  778. /* The distribution counts are first used to generate the code values
  779. * without bit reversal.
  780. */
  781. for (bits = 1; bits <= MAX_BITS; bits++) {
  782. next_code[bits] = code = (ush)((code + state.ts.bl_count[bits-1]) << 1);
  783. }
  784. /* Check that the bit counts in bl_count are consistent. The last code
  785. * must be all ones.
  786. */
  787. Assert(state,code + state.ts.bl_count[MAX_BITS]-1 == (1<< ((ush) MAX_BITS)) - 1,
  788. "inconsistent bit counts");
  789. Trace("\ngen_codes: max_code %d ", max_code);
  790. for (n = 0; n <= max_code; n++) {
  791. int len = tree[n].dl.len;
  792. if (len == 0) continue;
  793. /* Now reverse the bits */
  794. tree[n].fc.code = (ush)bi_reverse(next_code[len]++, len);
  795. //Tracec(tree != state.ts.static_ltree, "\nn %3d %c l %2d c %4x (%x) ", n, (isgraph(n) ? n : ' '), len, tree[n].fc.code, next_code[len]-1);
  796. }
  797. }
  798. /* ===========================================================================
  799. * Construct one Huffman tree and assigns the code bit strings and lengths.
  800. * Update the total bit length for the current block.
  801. * IN assertion: the field freq is set for all tree elements.
  802. * OUT assertions: the fields len and code are set to the optimal bit length
  803. * and corresponding code. The length opt_len is updated; static_len is
  804. * also updated if stree is not null. The field max_code is set.
  805. */
  806. void build_tree(TState &state,tree_desc *desc)
  807. {
  808. ct_data *tree = desc->dyn_tree;
  809. ct_data *stree = desc->static_tree;
  810. int elems = desc->elems;
  811. int n, m; /* iterate over heap elements */
  812. int max_code = -1; /* largest code with non zero frequency */
  813. int node = elems; /* next internal node of the tree */
  814. /* Construct the initial heap, with least frequent element in
  815. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  816. * heap[0] is not used.
  817. */
  818. state.ts.heap_len = 0, state.ts.heap_max = HEAP_SIZE;
  819. for (n = 0; n < elems; n++) {
  820. if (tree[n].fc.freq != 0) {
  821. state.ts.heap[++state.ts.heap_len] = max_code = n;
  822. state.ts.depth[n] = 0;
  823. } else {
  824. tree[n].dl.len = 0;
  825. }
  826. }
  827. /* The pkzip format requires that at least one distance code exists,
  828. * and that at least one bit should be sent even if there is only one
  829. * possible code. So to avoid special checks later on we force at least
  830. * two codes of non zero frequency.
  831. */
  832. while (state.ts.heap_len < 2) {
  833. int newcp = state.ts.heap[++state.ts.heap_len] = (max_code < 2 ? ++max_code : 0);
  834. tree[newcp].fc.freq = 1;
  835. state.ts.depth[newcp] = 0;
  836. state.ts.opt_len--; if (stree) state.ts.static_len -= stree[newcp].dl.len;
  837. /* new is 0 or 1 so it does not have extra bits */
  838. }
  839. desc->max_code = max_code;
  840. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  841. * establish sub-heaps of increasing lengths:
  842. */
  843. for (n = state.ts.heap_len/2; n >= 1; n--) pqdownheap(state,tree, n);
  844. /* Construct the Huffman tree by repeatedly combining the least two
  845. * frequent nodes.
  846. */
  847. do {
  848. pqremove(tree, n); /* n = node of least frequency */
  849. m = state.ts.heap[SMALLEST]; /* m = node of next least frequency */
  850. state.ts.heap[--state.ts.heap_max] = n; /* keep the nodes sorted by frequency */
  851. state.ts.heap[--state.ts.heap_max] = m;
  852. /* Create a new node father of n and m */
  853. tree[node].fc.freq = (ush)(tree[n].fc.freq + tree[m].fc.freq);
  854. state.ts.depth[node] = (uch) (Max(state.ts.depth[n], state.ts.depth[m]) + 1);
  855. tree[n].dl.dad = tree[m].dl.dad = (ush)node;
  856. /* and insert the new node in the heap */
  857. state.ts.heap[SMALLEST] = node++;
  858. pqdownheap(state,tree, SMALLEST);
  859. } while (state.ts.heap_len >= 2);
  860. state.ts.heap[--state.ts.heap_max] = state.ts.heap[SMALLEST];
  861. /* At this point, the fields freq and dad are set. We can now
  862. * generate the bit lengths.
  863. */
  864. gen_bitlen(state,(tree_desc *)desc);
  865. /* The field len is now set, we can generate the bit codes */
  866. gen_codes (state,(ct_data *)tree, max_code);
  867. }
  868. /* ===========================================================================
  869. * Scan a literal or distance tree to determine the frequencies of the codes
  870. * in the bit length tree. Updates opt_len to take into account the repeat
  871. * counts. (The contribution of the bit length codes will be added later
  872. * during the construction of bl_tree.)
  873. */
  874. void scan_tree (TState &state,ct_data *tree, int max_code)
  875. {
  876. int n; /* iterates over all tree elements */
  877. int prevlen = -1; /* last emitted length */
  878. int curlen; /* length of current code */
  879. int nextlen = tree[0].dl.len; /* length of next code */
  880. int count = 0; /* repeat count of the current code */
  881. int max_count = 7; /* max repeat count */
  882. int min_count = 4; /* min repeat count */
  883. if (nextlen == 0) max_count = 138, min_count = 3;
  884. tree[max_code+1].dl.len = (ush)-1; /* guard */
  885. for (n = 0; n <= max_code; n++) {
  886. curlen = nextlen; nextlen = tree[n+1].dl.len;
  887. if (++count < max_count && curlen == nextlen) {
  888. continue;
  889. } else if (count < min_count) {
  890. state.ts.bl_tree[curlen].fc.freq = (ush)(state.ts.bl_tree[curlen].fc.freq + count);
  891. } else if (curlen != 0) {
  892. if (curlen != prevlen) state.ts.bl_tree[curlen].fc.freq++;
  893. state.ts.bl_tree[REP_3_6].fc.freq++;
  894. } else if (count <= 10) {
  895. state.ts.bl_tree[REPZ_3_10].fc.freq++;
  896. } else {
  897. state.ts.bl_tree[REPZ_11_138].fc.freq++;
  898. }
  899. count = 0; prevlen = curlen;
  900. if (nextlen == 0) {
  901. max_count = 138, min_count = 3;
  902. } else if (curlen == nextlen) {
  903. max_count = 6, min_count = 3;
  904. } else {
  905. max_count = 7, min_count = 4;
  906. }
  907. }
  908. }
  909. /* ===========================================================================
  910. * Send a literal or distance tree in compressed form, using the codes in
  911. * bl_tree.
  912. */
  913. void send_tree (TState &state, ct_data *tree, int max_code)
  914. {
  915. int n; /* iterates over all tree elements */
  916. int prevlen = -1; /* last emitted length */
  917. int curlen; /* length of current code */
  918. int nextlen = tree[0].dl.len; /* length of next code */
  919. int count = 0; /* repeat count of the current code */
  920. int max_count = 7; /* max repeat count */
  921. int min_count = 4; /* min repeat count */
  922. /* tree[max_code+1].dl.len = -1; */ /* guard already set */
  923. if (nextlen == 0) max_count = 138, min_count = 3;
  924. for (n = 0; n <= max_code; n++) {
  925. curlen = nextlen; nextlen = tree[n+1].dl.len;
  926. if (++count < max_count && curlen == nextlen) {
  927. continue;
  928. } else if (count < min_count) {
  929. do { send_code(state, curlen, state.ts.bl_tree); } while (--count != 0);
  930. } else if (curlen != 0) {
  931. if (curlen != prevlen) {
  932. send_code(state, curlen, state.ts.bl_tree); count--;
  933. }
  934. Assert(state,count >= 3 && count <= 6, " 3_6?");
  935. send_code(state,REP_3_6, state.ts.bl_tree); send_bits(state,count-3, 2);
  936. } else if (count <= 10) {
  937. send_code(state,REPZ_3_10, state.ts.bl_tree); send_bits(state,count-3, 3);
  938. } else {
  939. send_code(state,REPZ_11_138, state.ts.bl_tree); send_bits(state,count-11, 7);
  940. }
  941. count = 0; prevlen = curlen;
  942. if (nextlen == 0) {
  943. max_count = 138, min_count = 3;
  944. } else if (curlen == nextlen) {
  945. max_count = 6, min_count = 3;
  946. } else {
  947. max_count = 7, min_count = 4;
  948. }
  949. }
  950. }
  951. /* ===========================================================================
  952. * Construct the Huffman tree for the bit lengths and return the index in
  953. * bl_order of the last bit length code to send.
  954. */
  955. int build_bl_tree(TState &state)
  956. {
  957. int max_blindex; /* index of last bit length code of non zero freq */
  958. /* Determine the bit length frequencies for literal and distance trees */
  959. scan_tree(state,(ct_data *)state.ts.dyn_ltree, state.ts.l_desc.max_code);
  960. scan_tree(state,(ct_data *)state.ts.dyn_dtree, state.ts.d_desc.max_code);
  961. /* Build the bit length tree: */
  962. build_tree(state,(tree_desc *)(&state.ts.bl_desc));
  963. /* opt_len now includes the length of the tree representations, except
  964. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  965. */
  966. /* Determine the number of bit length codes to send. The pkzip format
  967. * requires that at least 4 bit length codes be sent. (appnote.txt says
  968. * 3 but the actual value used is 4.)
  969. */
  970. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  971. if (state.ts.bl_tree[bl_order[max_blindex]].dl.len != 0) break;
  972. }
  973. /* Update opt_len to include the bit length tree and counts */
  974. state.ts.opt_len += 3*(max_blindex+1) + 5+5+4;
  975. Trace("\ndyn trees: dyn %ld, stat %ld", state.ts.opt_len, state.ts.static_len);
  976. return max_blindex;
  977. }
  978. /* ===========================================================================
  979. * Send the header for a block using dynamic Huffman trees: the counts, the
  980. * lengths of the bit length codes, the literal tree and the distance tree.
  981. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  982. */
  983. void send_all_trees(TState &state,int lcodes, int dcodes, int blcodes)
  984. {
  985. int rank; /* index in bl_order */
  986. Assert(state,lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  987. Assert(state,lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  988. "too many codes");
  989. Trace("\nbl counts: ");
  990. send_bits(state,lcodes-257, 5);
  991. /* not +255 as stated in appnote.txt 1.93a or -256 in 2.04c */
  992. send_bits(state,dcodes-1, 5);
  993. send_bits(state,blcodes-4, 4); /* not -3 as stated in appnote.txt */
  994. for (rank = 0; rank < blcodes; rank++) {
  995. Trace("\nbl code %2d ", bl_order[rank]);
  996. send_bits(state,state.ts.bl_tree[bl_order[rank]].dl.len, 3);
  997. }
  998. Trace("\nbl tree: sent %ld", state.bs.bits_sent);
  999. send_tree(state,(ct_data *)state.ts.dyn_ltree, lcodes-1); /* send the literal tree */
  1000. Trace("\nlit tree: sent %ld", state.bs.bits_sent);
  1001. send_tree(state,(ct_data *)state.ts.dyn_dtree, dcodes-1); /* send the distance tree */
  1002. Trace("\ndist tree: sent %ld", state.bs.bits_sent);
  1003. }
  1004. /* ===========================================================================
  1005. * Determine the best encoding for the current block: dynamic trees, static
  1006. * trees or store, and output the encoded block to the zip file. This function
  1007. * returns the total compressed length (in bytes) for the file so far.
  1008. */
  1009. ulg flush_block(TState &state,char *buf, ulg stored_len, int eof)
  1010. {
  1011. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  1012. int max_blindex; /* index of last bit length code of non zero freq */
  1013. state.ts.flag_buf[state.ts.last_flags] = state.ts.flags; /* Save the flags for the last 8 items */
  1014. /* Check if the file is ascii or binary */
  1015. if (*state.ts.file_type == (ush)UNKNOWN) set_file_type(state);
  1016. /* Construct the literal and distance trees */
  1017. build_tree(state,(tree_desc *)(&state.ts.l_desc));
  1018. Trace("\nlit data: dyn %ld, stat %ld", state.ts.opt_len, state.ts.static_len);
  1019. build_tree(state,(tree_desc *)(&state.ts.d_desc));
  1020. Trace("\ndist data: dyn %ld, stat %ld", state.ts.opt_len, state.ts.static_len);
  1021. /* At this point, opt_len and static_len are the total bit lengths of
  1022. * the compressed block data, excluding the tree representations.
  1023. */
  1024. /* Build the bit length tree for the above two trees, and get the index
  1025. * in bl_order of the last bit length code to send.
  1026. */
  1027. max_blindex = build_bl_tree(state);
  1028. /* Determine the best encoding. Compute first the block length in bytes */
  1029. opt_lenb = (state.ts.opt_len+3+7)>>3;
  1030. static_lenb = (state.ts.static_len+3+7)>>3;
  1031. state.ts.input_len += stored_len; /* for debugging only */
  1032. Trace("\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
  1033. opt_lenb, state.ts.opt_len, static_lenb, state.ts.static_len, stored_len,
  1034. state.ts.last_lit, state.ts.last_dist);
  1035. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  1036. // Originally, zip allowed the file to be transformed from a compressed
  1037. // into a stored file in the case where compression failed, there
  1038. // was only one block, and it was allowed to change. I've removed this
  1039. // possibility since the code's cleaner if no changes are allowed.
  1040. //if (stored_len <= opt_lenb && eof && state.ts.cmpr_bytelen == 0L
  1041. // && state.ts.cmpr_len_bits == 0L && state.seekable)
  1042. //{ // && state.ts.file_method != NULL
  1043. // // Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there:
  1044. // Assert(state,buf!=NULL,"block vanished");
  1045. // copy_block(state,buf, (unsigned)stored_len, 0); // without header
  1046. // state.ts.cmpr_bytelen = stored_len;
  1047. // Assert(state,false,"unimplemented *state.ts.file_method = STORE;");
  1048. // //*state.ts.file_method = STORE;
  1049. //}
  1050. //else
  1051. if (stored_len+4 <= opt_lenb && buf != (char*)NULL) {
  1052. /* 4: two words for the lengths */
  1053. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  1054. * Otherwise we can't have processed more than WSIZE input bytes since
  1055. * the last block flush, because compression would have been
  1056. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  1057. * transform a block into a stored block.
  1058. */
  1059. send_bits(state,(STORED_BLOCK<<1)+eof, 3); /* send block type */
  1060. state.ts.cmpr_bytelen += ((state.ts.cmpr_len_bits + 3 + 7) >> 3) + stored_len + 4;
  1061. state.ts.cmpr_len_bits = 0L;
  1062. copy_block(state,buf, (unsigned)stored_len, 1); /* with header */
  1063. }
  1064. else if (static_lenb == opt_lenb) {
  1065. send_bits(state,(STATIC_TREES<<1)+eof, 3);
  1066. compress_block(state,(ct_data *)state.ts.static_ltree, (ct_data *)state.ts.static_dtree);
  1067. state.ts.cmpr_len_bits += 3 + state.ts.static_len;
  1068. state.ts.cmpr_bytelen += state.ts.cmpr_len_bits >> 3;
  1069. state.ts.cmpr_len_bits &= 7L;
  1070. }
  1071. else {
  1072. send_bits(state,(DYN_TREES<<1)+eof, 3);
  1073. send_all_trees(state,state.ts.l_desc.max_code+1, state.ts.d_desc.max_code+1, max_blindex+1);
  1074. compress_block(state,(ct_data *)state.ts.dyn_ltree, (ct_data *)state.ts.dyn_dtree);
  1075. state.ts.cmpr_len_bits += 3 + state.ts.opt_len;
  1076. state.ts.cmpr_bytelen += state.ts.cmpr_len_bits >> 3;
  1077. state.ts.cmpr_len_bits &= 7L;
  1078. }
  1079. Assert(state,((state.ts.cmpr_bytelen << 3) + state.ts.cmpr_len_bits) == state.bs.bits_sent, "bad compressed size");
  1080. init_block(state);
  1081. if (eof) {
  1082. // Assert(state,input_len == isize, "bad input size");
  1083. bi_windup(state);
  1084. state.ts.cmpr_len_bits += 7; /* align on byte boundary */
  1085. }
  1086. Trace("\n");
  1087. return state.ts.cmpr_bytelen + (state.ts.cmpr_len_bits >> 3);
  1088. }
  1089. /* ===========================================================================
  1090. * Save the match info and tally the frequency counts. Return true if
  1091. * the current block must be flushed.
  1092. */
  1093. int ct_tally (TState &state,int dist, int lc)
  1094. {
  1095. state.ts.l_buf[state.ts.last_lit++] = (uch)lc;
  1096. if (dist == 0) {
  1097. /* lc is the unmatched char */
  1098. state.ts.dyn_ltree[lc].fc.freq++;
  1099. } else {
  1100. /* Here, lc is the match length - MIN_MATCH */
  1101. dist--; /* dist = match distance - 1 */
  1102. Assert(state,(ush)dist < (ush)MAX_DIST &&
  1103. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  1104. (ush)d_code(dist) < (ush)D_CODES, "ct_tally: bad match");
  1105. state.ts.dyn_ltree[state.ts.length_code[lc]+LITERALS+1].fc.freq++;
  1106. state.ts.dyn_dtree[d_code(dist)].fc.freq++;
  1107. state.ts.d_buf[state.ts.last_dist++] = (ush)dist;
  1108. state.ts.flags |= state.ts.flag_bit;
  1109. }
  1110. state.ts.flag_bit <<= 1;
  1111. /* Output the flags if they fill a byte: */
  1112. if ((state.ts.last_lit & 7) == 0) {
  1113. state.ts.flag_buf[state.ts.last_flags++] = state.ts.flags;
  1114. state.ts.flags = 0, state.ts.flag_bit = 1;
  1115. }
  1116. /* Try to guess if it is profitable to stop the current block here */
  1117. if (state.level > 2 && (state.ts.last_lit & 0xfff) == 0) {
  1118. /* Compute an upper bound for the compressed length */
  1119. ulg out_length = (ulg)state.ts.last_lit*8L;
  1120. ulg in_length = (ulg)state.ds.strstart-state.ds.block_start;
  1121. int dcode;
  1122. for (dcode = 0; dcode < D_CODES; dcode++) {
  1123. out_length += (ulg)state.ts.dyn_dtree[dcode].fc.freq*(5L+extra_dbits[dcode]);
  1124. }
  1125. out_length >>= 3;
  1126. Trace("\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
  1127. state.ts.last_lit, state.ts.last_dist, in_length, out_length,
  1128. 100L - out_length*100L/in_length);
  1129. if (state.ts.last_dist < state.ts.last_lit/2 && out_length < in_length/2) return 1;
  1130. }
  1131. return (state.ts.last_lit == LIT_BUFSIZE-1 || state.ts.last_dist == DIST_BUFSIZE);
  1132. /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  1133. * on 16 bit machines and because stored blocks are restricted to
  1134. * 64K-1 bytes.
  1135. */
  1136. }
  1137. /* ===========================================================================
  1138. * Send the block data compressed using the given Huffman trees
  1139. */
  1140. void compress_block(TState &state,ct_data *ltree, ct_data *dtree)
  1141. {
  1142. unsigned dist; /* distance of matched string */
  1143. int lc; /* match length or unmatched char (if dist == 0) */
  1144. unsigned lx = 0; /* running index in l_buf */
  1145. unsigned dx = 0; /* running index in d_buf */
  1146. unsigned fx = 0; /* running index in flag_buf */
  1147. uch flag = 0; /* current flags */
  1148. unsigned code; /* the code to send */
  1149. int extra; /* number of extra bits to send */
  1150. if (state.ts.last_lit != 0) do {
  1151. if ((lx & 7) == 0) flag = state.ts.flag_buf[fx++];
  1152. lc = state.ts.l_buf[lx++];
  1153. if ((flag & 1) == 0) {
  1154. send_code(state,lc, ltree); /* send a literal byte */
  1155. } else {
  1156. /* Here, lc is the match length - MIN_MATCH */
  1157. code = state.ts.length_code[lc];
  1158. send_code(state,code+LITERALS+1, ltree); /* send the length code */
  1159. extra = extra_lbits[code];
  1160. if (extra != 0) {
  1161. lc -= state.ts.base_length[code];
  1162. send_bits(state,lc, extra); /* send the extra length bits */
  1163. }
  1164. dist = state.ts.d_buf[dx++];
  1165. /* Here, dist is the match distance - 1 */
  1166. code = d_code(dist);
  1167. Assert(state,code < D_CODES, "bad d_code");
  1168. send_code(state,code, dtree); /* send the distance code */
  1169. extra = extra_dbits[code];
  1170. if (extra != 0) {
  1171. dist -= state.ts.base_dist[code];
  1172. send_bits(state,dist, extra); /* send the extra distance bits */
  1173. }
  1174. } /* literal or match pair ? */
  1175. flag >>= 1;
  1176. } while (lx < state.ts.last_lit);
  1177. send_code(state,END_BLOCK, ltree);
  1178. }
  1179. /* ===========================================================================
  1180. * Set the file type to ASCII or BINARY, using a crude approximation:
  1181. * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  1182. * IN assertion: the fields freq of dyn_ltree are set and the total of all
  1183. * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  1184. */
  1185. void set_file_type(TState &state)
  1186. {
  1187. int n = 0;
  1188. unsigned ascii_freq = 0;
  1189. unsigned bin_freq = 0;
  1190. while (n < 7) bin_freq += state.ts.dyn_ltree[n++].fc.freq;
  1191. while (n < 128) ascii_freq += state.ts.dyn_ltree[n++].fc.freq;
  1192. while (n < LITERALS) bin_freq += state.ts.dyn_ltree[n++].fc.freq;
  1193. *state.ts.file_type = (ush)(bin_freq > (ascii_freq >> 2) ? BINARY : ASCII);
  1194. }
  1195. /* ===========================================================================
  1196. * Initialize the bit string routines.
  1197. */
  1198. void bi_init (TState &state,char *tgt_buf, unsigned tgt_size, int flsh_allowed)
  1199. {
  1200. state.bs.out_buf = tgt_buf;
  1201. state.bs.out_size = tgt_size;
  1202. state.bs.out_offset = 0;
  1203. state.bs.flush_flg = flsh_allowed;
  1204. state.bs.bi_buf = 0;
  1205. state.bs.bi_valid = 0;
  1206. state.bs.bits_sent = 0L;
  1207. }
  1208. /* ===========================================================================
  1209. * Send a value on a given number of bits.
  1210. * IN assertion: length <= 16 and value fits in length bits.
  1211. */
  1212. void send_bits(TState &state,int value, int length)
  1213. {
  1214. Assert(state,length > 0 && length <= 15, "invalid length");
  1215. state.bs.bits_sent += (ulg)length;
  1216. /* If not enough room in bi_buf, use (bi_valid) bits from bi_buf and
  1217. * (Buf_size - bi_valid) bits from value to flush the filled bi_buf,
  1218. * then fill in the rest of (value), leaving (length - (Buf_size-bi_valid))
  1219. * unused bits in bi_buf.
  1220. */
  1221. state.bs.bi_buf |= (value << state.bs.bi_valid);
  1222. state.bs.bi_valid += length;
  1223. if (state.bs.bi_valid > (int)Buf_size) {
  1224. PUTSHORT(state,state.bs.bi_buf);
  1225. state.bs.bi_valid -= Buf_size;
  1226. state.bs.bi_buf = (unsigned)value >> (length - state.bs.bi_valid);
  1227. }
  1228. }
  1229. /* ===========================================================================
  1230. * Reverse the first len bits of a code, using straightforward code (a faster
  1231. * method would use a table)
  1232. * IN assertion: 1 <= len <= 15
  1233. */
  1234. unsigned bi_reverse(unsigned code, int len)
  1235. {
  1236. unsigned res = 0;
  1237. do {
  1238. res |= code & 1;
  1239. code >>= 1, res <<= 1;
  1240. } while (--len > 0);
  1241. return res >> 1;
  1242. }
  1243. /* ===========================================================================
  1244. * Write out any remaining bits in an incomplete byte.
  1245. */
  1246. void bi_windup(TState &state)
  1247. {
  1248. if (state.bs.bi_valid > 8) {
  1249. PUTSHORT(state,state.bs.bi_buf);
  1250. } else if (state.bs.bi_valid > 0) {
  1251. PUTBYTE(state,state.bs.bi_buf);
  1252. }
  1253. if (state.bs.flush_flg) {
  1254. state.flush_outbuf(state.param, state.bs.out_buf, &state.bs.out_offset);
  1255. }
  1256. state.bs.bi_buf = 0;
  1257. state.bs.bi_valid = 0;
  1258. state.bs.bits_sent = (state.bs.bits_sent+7) & ~7;
  1259. }
  1260. /* ===========================================================================
  1261. * Copy a stored block to the zip file, storing first the length and its
  1262. * one's complement if requested.
  1263. */
  1264. void copy_block(TState &state, char *block, unsigned len, int header)
  1265. {
  1266. bi_windup(state); /* align on byte boundary */
  1267. if (header) {
  1268. PUTSHORT(state,(ush)len);
  1269. PUTSHORT(state,(ush)~len);
  1270. state.bs.bits_sent += 2*16;
  1271. }
  1272. if (state.bs.flush_flg) {
  1273. state.flush_outbuf(state.param, state.bs.out_buf, &state.bs.out_offset);
  1274. state.bs.out_offset = len;
  1275. state.flush_outbuf(state.param, block, &state.bs.out_offset);
  1276. } else if (state.bs.out_offset + len > state.bs.out_size) {
  1277. Assert(state,false,"output buffer too small for in-memory compression");
  1278. } else {
  1279. memcpy(state.bs.out_buf + state.bs.out_offset, block, len);
  1280. state.bs.out_offset += len;
  1281. }
  1282. state.bs.bits_sent += (ulg)len<<3;
  1283. }
  1284. /* ===========================================================================
  1285. * Prototypes for functions.
  1286. */
  1287. void fill_window (TState &state);
  1288. ulg deflate_fast (TState &state);
  1289. int longest_match (TState &state,IPos cur_match);
  1290. /* ===========================================================================
  1291. * Update a hash value with the given input byte
  1292. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  1293. * input characters, so that a running hash key can be computed from the
  1294. * previous key instead of complete recalculation each time.
  1295. */
  1296. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  1297. /* ===========================================================================
  1298. * Insert string s in the dictionary and set match_head to the previous head
  1299. * of the hash chain (the most recent string with same hash key). Return
  1300. * the previous length of the hash chain.
  1301. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  1302. * input characters and the first MIN_MATCH bytes of s are valid
  1303. * (except for the last MIN_MATCH-1 bytes of the input file).
  1304. */
  1305. #define INSERT_STRING(s, match_head) \
  1306. (UPDATE_HASH(state.ds.ins_h, state.ds.window[(s) + (MIN_MATCH-1)]), \
  1307. state.ds.prev[(s) & WMASK] = match_head = state.ds.head[state.ds.ins_h], \
  1308. state.ds.head[state.ds.ins_h] = (s))
  1309. /* ===========================================================================
  1310. * Initialize the "longest match" routines for a new file
  1311. *
  1312. * IN assertion: window_size is > 0 if the input file is already read or
  1313. * mmap'ed in the window[] array, 0 otherwise. In the first case,
  1314. * window_size is sufficient to contain the whole input file plus
  1315. * MIN_LOOKAHEAD bytes (to avoid referencing memory beyond the end
  1316. * of window[] when looking for matches towards the end).
  1317. */
  1318. void lm_init (TState &state, int pack_level, ush *flags)
  1319. {
  1320. unsigned j;
  1321. Assert(state,pack_level>=1 && pack_level<=8,"bad pack level");
  1322. /* Do not slide the window if the whole input is already in memory
  1323. * (window_size > 0)
  1324. */
  1325. state.ds.sliding = 0;
  1326. if (state.ds.window_size == 0L) {
  1327. state.ds.sliding = 1;
  1328. state.ds.window_size = (ulg)2L*WSIZE;
  1329. }
  1330. /* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  1331. * prev[] will be initialized on the fly.
  1332. */
  1333. state.ds.head[HASH_SIZE-1] = NIL;
  1334. memset((char*)state.ds.head, NIL, (unsigned)(HASH_SIZE-1)*sizeof(*state.ds.head));
  1335. /* Set the default configuration parameters:
  1336. */
  1337. state.ds.max_lazy_match = configuration_table[pack_level].max_lazy;
  1338. state.ds.good_match = configuration_table[pack_level].good_length;
  1339. state.ds.nice_match = configuration_table[pack_level].nice_length;
  1340. state.ds.max_chain_length = configuration_table[pack_level].max_chain;
  1341. if (pack_level <= 2) {
  1342. *flags |= FAST;
  1343. } else if (pack_level >= 8) {
  1344. *flags |= SLOW;
  1345. }
  1346. /* ??? reduce max_chain_length for binary files */
  1347. state.ds.strstart = 0;
  1348. state.ds.block_start = 0L;
  1349. j = WSIZE;
  1350. j <<= 1; // Can read 64K in one step
  1351. state.ds.lookahead = state.readfunc(state, (char*)state.ds.window, j);
  1352. if (state.ds.lookahead == 0 || state.ds.lookahead == (unsigned)EOF) {
  1353. state.ds.eofile = 1, state.ds.lookahead = 0;
  1354. return;
  1355. }
  1356. state.ds.eofile = 0;
  1357. /* Make sure that we always have enough lookahead. This is important
  1358. * if input comes from a device such as a tty.
  1359. */
  1360. if (state.ds.lookahead < MIN_LOOKAHEAD) fill_window(state);
  1361. state.ds.ins_h = 0;
  1362. for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(state.ds.ins_h, state.ds.window[j]);
  1363. /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  1364. * not important since only literal bytes will be emitted.
  1365. */
  1366. }
  1367. /* ===========================================================================
  1368. * Set match_start to the longest match starting at the given string and
  1369. * return its length. Matches shorter or equal to prev_length are discarded,
  1370. * in which case the result is equal to prev_length and match_start is
  1371. * garbage.
  1372. * IN assertions: cur_match is the head of the hash chain for the current
  1373. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1374. */
  1375. // For 80x86 and 680x0 and ARM, an optimized version is in match.asm or
  1376. // match.S. The code is functionally equivalent, so you can use the C version
  1377. // if desired. Which I do so desire!
  1378. int longest_match(TState &state,IPos cur_match)
  1379. {
  1380. unsigned chain_length = state.ds.max_chain_length; /* max hash chain length */
  1381. uch far *scan = state.ds.window + state.ds.strstart; /* current string */
  1382. uch far *match; /* matched string */
  1383. int len; /* length of current match */
  1384. int best_len = state.ds.prev_length; /* best match length so far */
  1385. IPos limit = state.ds.strstart > (IPos)MAX_DIST ? state.ds.strstart - (IPos)MAX_DIST : NIL;
  1386. /* Stop when cur_match becomes <= limit. To simplify the code,
  1387. * we prevent matches with the string of window index 0.
  1388. */
  1389. // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1390. // It is easy to get rid of this optimization if necessary.
  1391. Assert(state,HASH_BITS>=8 && MAX_MATCH==258,"Code too clever");
  1392. uch far *strend = state.ds.window + state.ds.strstart + MAX_MATCH;
  1393. uch scan_end1 = scan[best_len-1];
  1394. uch scan_end = scan[best_len];
  1395. /* Do not waste too much time if we already have a good match: */
  1396. if (state.ds.prev_length >= state.ds.good_match) {
  1397. chain_length >>= 2;
  1398. }
  1399. Assert(state,state.ds.strstart <= state.ds.window_size-MIN_LOOKAHEAD, "insufficient lookahead");
  1400. do {
  1401. Assert(state,cur_match < state.ds.strstart, "no future");
  1402. match = state.ds.window + cur_match;
  1403. /* Skip to next match if the match length cannot increase
  1404. * or if the match length is less than 2:
  1405. */
  1406. if (match[best_len] != scan_end ||
  1407. match[best_len-1] != scan_end1 ||
  1408. *match != *scan ||
  1409. *++match != scan[1]) continue;
  1410. /* The check at best_len-1 can be removed because it will be made
  1411. * again later. (This heuristic is not always a win.)
  1412. * It is not necessary to compare scan[2] and match[2] since they
  1413. * are always equal when the other bytes match, given that
  1414. * the hash keys are equal and that HASH_BITS >= 8.
  1415. */
  1416. scan += 2, match++;
  1417. /* We check for insufficient lookahead only every 8th comparison;
  1418. * the 256th check will be made at strstart+258.
  1419. */
  1420. do {
  1421. } while (*++scan == *++match && *++scan == *++match &&
  1422. *++scan == *++match && *++scan == *++match &&
  1423. *++scan == *++match && *++scan == *++match &&
  1424. *++scan == *++match && *++scan == *++match &&
  1425. scan < strend);
  1426. Assert(state,scan <= state.ds.window+(unsigned)(state.ds.window_size-1), "wild scan");
  1427. len = MAX_MATCH - (int)(strend - scan);
  1428. scan = strend - MAX_MATCH;
  1429. if (len > best_len) {
  1430. state.ds.match_start = cur_match;
  1431. best_len = len;
  1432. if (len >= state.ds.nice_match) break;
  1433. scan_end1 = scan[best_len-1];
  1434. scan_end = scan[best_len];
  1435. }
  1436. } while ((cur_match = state.ds.prev[cur_match & WMASK]) > limit
  1437. && --chain_length != 0);
  1438. return best_len;
  1439. }
  1440. #define check_match(state,start, match, length)
  1441. // or alternatively...
  1442. //void check_match(TState &state,IPos start, IPos match, int length)
  1443. //{ // check that the match is indeed a match
  1444. // if (memcmp((char*)state.ds.window + match,
  1445. // (char*)state.ds.window + start, length) != EQUAL) {
  1446. // fprintf(stderr,
  1447. // " start %d, match %d, length %d\n",
  1448. // start, match, length);
  1449. // error("invalid match");
  1450. // }
  1451. // if (state.verbose > 1) {
  1452. // fprintf(stderr,"\\[%d,%d]", start-match, length);
  1453. // do { fprintf(stdout,"%c",state.ds.window[start++]); } while (--length != 0);
  1454. // }
  1455. //}
  1456. /* ===========================================================================
  1457. * Fill the window when the lookahead becomes insufficient.
  1458. * Updates strstart and lookahead, and sets eofile if end of input file.
  1459. *
  1460. * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  1461. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1462. * At least one byte has been read, or eofile is set; file reads are
  1463. * performed for at least two bytes (required for the translate_eol option).
  1464. */
  1465. void fill_window(TState &state)
  1466. {
  1467. unsigned n, m;
  1468. unsigned more; /* Amount of free space at the end of the window. */
  1469. do {
  1470. more = (unsigned)(state.ds.window_size - (ulg)state.ds.lookahead - (ulg)state.ds.strstart);
  1471. /* If the window is almost full and there is insufficient lookahead,
  1472. * move the upper half to the lower one to make room in the upper half.
  1473. */
  1474. if (more == (unsigned)EOF) {
  1475. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  1476. * and lookahead == 1 (input done one byte at time)
  1477. */
  1478. more--;
  1479. /* For MMAP or BIG_MEM, the whole input file is already in memory so
  1480. * we must not perform sliding. We must however call (*read_buf)() in
  1481. * order to compute the crc, update lookahead and possibly set eofile.
  1482. */
  1483. } else if (state.ds.strstart >= WSIZE+MAX_DIST && state.ds.sliding) {
  1484. /* By the IN assertion, the window is not empty so we can't confuse
  1485. * more == 0 with more == 64K on a 16 bit machine.
  1486. */
  1487. memcpy((char*)state.ds.window, (char*)state.ds.window+WSIZE, (unsigned)WSIZE);
  1488. state.ds.match_start -= WSIZE;
  1489. state.ds.strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
  1490. state.ds.block_start -= (long) WSIZE;
  1491. for (n = 0; n < HASH_SIZE; n++) {
  1492. m = state.ds.head[n];
  1493. state.ds.head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  1494. }
  1495. for (n = 0; n < WSIZE; n++) {
  1496. m = state.ds.prev[n];
  1497. state.ds.prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  1498. /* If n is not on any hash chain, prev[n] is garbage but
  1499. * its value will never be used.
  1500. */
  1501. }
  1502. more += WSIZE;
  1503. }
  1504. if (state.ds.eofile) return;
  1505. /* If there was no sliding:
  1506. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1507. * more == window_size - lookahead - strstart
  1508. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1509. * => more >= window_size - 2*WSIZE + 2
  1510. * In the MMAP or BIG_MEM case (not yet supported in gzip),
  1511. * window_size == input_size + MIN_LOOKAHEAD &&
  1512. * strstart + lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1513. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1514. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1515. */
  1516. Assert(state,more >= 2, "more < 2");
  1517. n = state.readfunc(state, (char*)state.ds.window+state.ds.strstart+state.ds.lookahead, more);
  1518. if (n == 0 || n == (unsigned)EOF) {
  1519. state.ds.eofile = 1;
  1520. } else {
  1521. state.ds.lookahead += n;
  1522. }
  1523. } while (state.ds.lookahead < MIN_LOOKAHEAD && !state.ds.eofile);
  1524. }
  1525. /* ===========================================================================
  1526. * Flush the current block, with given end-of-file flag.
  1527. * IN assertion: strstart is set to the end of the current match.
  1528. */
  1529. #define FLUSH_BLOCK(state,eof) \
  1530. flush_block(state,state.ds.block_start >= 0L ? (char*)&state.ds.window[(unsigned)state.ds.block_start] : \
  1531. (char*)NULL, (long)state.ds.strstart - state.ds.block_start, (eof))
  1532. /* ===========================================================================
  1533. * Processes a new input file and return its compressed length. This
  1534. * function does not perform lazy evaluation of matches and inserts
  1535. * new strings in the dictionary only for unmatched strings or for short
  1536. * matches. It is used only for the fast compression options.
  1537. */
  1538. ulg deflate_fast(TState &state)
  1539. {
  1540. IPos hash_head = NIL; /* head of the hash chain */
  1541. int flush; /* set if current block must be flushed */
  1542. unsigned match_length = 0; /* length of best match */
  1543. state.ds.prev_length = MIN_MATCH-1;
  1544. while (state.ds.lookahead != 0) {
  1545. /* Insert the string window[strstart .. strstart+2] in the
  1546. * dictionary, and set hash_head to the head of the hash chain:
  1547. */
  1548. if (state.ds.lookahead >= MIN_MATCH)
  1549. INSERT_STRING(state.ds.strstart, hash_head);
  1550. /* Find the longest match, discarding those <= prev_length.
  1551. * At this point we have always match_length < MIN_MATCH
  1552. */
  1553. if (hash_head != NIL && state.ds.strstart - hash_head <= MAX_DIST) {
  1554. /* To simplify the code, we prevent matches with the string
  1555. * of window index 0 (in particular we have to avoid a match
  1556. * of the string with itself at the start of the input file).
  1557. */
  1558. /* Do not look for matches beyond the end of the input.
  1559. * This is necessary to make deflate deterministic.
  1560. */
  1561. if ((unsigned)state.ds.nice_match > state.ds.lookahead) state.ds.nice_match = (int)state.ds.lookahead;
  1562. match_length = longest_match (state,hash_head);
  1563. /* longest_match() sets match_start */
  1564. if (match_length > state.ds.lookahead) match_length = state.ds.lookahead;
  1565. }
  1566. if (match_length >= MIN_MATCH) {
  1567. check_match(state,state.ds.strstart, state.ds.match_start, match_length);
  1568. flush = ct_tally(state,state.ds.strstart-state.ds.match_start, match_length - MIN_MATCH);
  1569. state.ds.lookahead -= match_length;
  1570. /* Insert new strings in the hash table only if the match length
  1571. * is not too large. This saves time but degrades compression.
  1572. */
  1573. if (match_length <= state.ds.max_insert_length
  1574. && state.ds.lookahead >= MIN_MATCH) {
  1575. match_length--; /* string at strstart already in hash table */
  1576. do {
  1577. state.ds.strstart++;
  1578. INSERT_STRING(state.ds.strstart, hash_head);
  1579. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1580. * always MIN_MATCH bytes ahead.
  1581. */
  1582. } while (--match_length != 0);
  1583. state.ds.strstart++;
  1584. } else {
  1585. state.ds.strstart += match_length;
  1586. match_length = 0;
  1587. state.ds.ins_h = state.ds.window[state.ds.strstart];
  1588. UPDATE_HASH(state.ds.ins_h, state.ds.window[state.ds.strstart+1]);
  1589. Assert(state,MIN_MATCH==3,"Call UPDATE_HASH() MIN_MATCH-3 more times");
  1590. }
  1591. } else {
  1592. /* No match, output a literal byte */
  1593. flush = ct_tally (state,0, state.ds.window[state.ds.strstart]);
  1594. state.ds.lookahead--;
  1595. state.ds.strstart++;
  1596. }
  1597. if (flush) FLUSH_BLOCK(state,0), state.ds.block_start = state.ds.strstart;
  1598. /* Make sure that we always have enough lookahead, except
  1599. * at the end of the input file. We need MAX_MATCH bytes
  1600. * for the next match, plus MIN_MATCH bytes to insert the
  1601. * string following the next match.
  1602. */
  1603. if (state.ds.lookahead < MIN_LOOKAHEAD) fill_window(state);
  1604. }
  1605. return FLUSH_BLOCK(state,1); /* eof */
  1606. }
  1607. /* ===========================================================================
  1608. * Same as above, but achieves better compression. We use a lazy
  1609. * evaluation for matches: a match is finally adopted only if there is
  1610. * no better match at the next window position.
  1611. */
  1612. ulg deflate(TState &state)
  1613. {
  1614. IPos hash_head = NIL; /* head of hash chain */
  1615. IPos prev_match; /* previous match */
  1616. int flush; /* set if current block must be flushed */
  1617. int match_available = 0; /* set if previous match exists */
  1618. unsigned match_length = MIN_MATCH-1; /* length of best match */
  1619. if (state.level <= 3) return deflate_fast(state); /* optimized for speed */
  1620. /* Process the input block. */
  1621. while (state.ds.lookahead != 0) {
  1622. /* Insert the string window[strstart .. strstart+2] in the
  1623. * dictionary, and set hash_head to the head of the hash chain:
  1624. */
  1625. if (state.ds.lookahead >= MIN_MATCH)
  1626. INSERT_STRING(state.ds.strstart, hash_head);
  1627. /* Find the longest match, discarding those <= prev_length.
  1628. */
  1629. state.ds.prev_length = match_length, prev_match = state.ds.match_start;
  1630. match_length = MIN_MATCH-1;
  1631. if (hash_head != NIL && state.ds.prev_length < state.ds.max_lazy_match &&
  1632. state.ds.strstart - hash_head <= MAX_DIST) {
  1633. /* To simplify the code, we prevent matches with the string
  1634. * of window index 0 (in particular we have to avoid a match
  1635. * of the string with itself at the start of the input file).
  1636. */
  1637. /* Do not look for matches beyond the end of the input.
  1638. * This is necessary to make deflate deterministic.
  1639. */
  1640. if ((unsigned)state.ds.nice_match > state.ds.lookahead) state.ds.nice_match = (int)state.ds.lookahead;
  1641. match_length = longest_match (state,hash_head);
  1642. /* longest_match() sets match_start */
  1643. if (match_length > state.ds.lookahead) match_length = state.ds.lookahead;
  1644. /* Ignore a length 3 match if it is too distant: */
  1645. if (match_length == MIN_MATCH && state.ds.strstart-state.ds.match_start > TOO_FAR){
  1646. /* If prev_match is also MIN_MATCH, match_start is garbage
  1647. * but we will ignore the current match anyway.
  1648. */
  1649. match_length = MIN_MATCH-1;
  1650. }
  1651. }
  1652. /* If there was a match at the previous step and the current
  1653. * match is not better, output the previous match:
  1654. */
  1655. if (state.ds.prev_length >= MIN_MATCH && match_length <= state.ds.prev_length) {
  1656. unsigned max_insert = state.ds.strstart + state.ds.lookahead - MIN_MATCH;
  1657. check_match(state,state.ds.strstart-1, prev_match, state.ds.prev_length);
  1658. flush = ct_tally(state,state.ds.strstart-1-prev_match, state.ds.prev_length - MIN_MATCH);
  1659. /* Insert in hash table all strings up to the end of the match.
  1660. * strstart-1 and strstart are already inserted.
  1661. */
  1662. state.ds.lookahead -= state.ds.prev_length-1;
  1663. state.ds.prev_length -= 2;
  1664. do {
  1665. if (++state.ds.strstart <= max_insert) {
  1666. INSERT_STRING(state.ds.strstart, hash_head);
  1667. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1668. * always MIN_MATCH bytes ahead.
  1669. */
  1670. }
  1671. } while (--state.ds.prev_length != 0);
  1672. state.ds.strstart++;
  1673. match_available = 0;
  1674. match_length = MIN_MATCH-1;
  1675. if (flush) FLUSH_BLOCK(state,0), state.ds.block_start = state.ds.strstart;
  1676. } else if (match_available) {
  1677. /* If there was no match at the previous position, output a
  1678. * single literal. If there was a match but the current match
  1679. * is longer, truncate the previous match to a single literal.
  1680. */
  1681. if (ct_tally (state,0, state.ds.window[state.ds.strstart-1])) {
  1682. FLUSH_BLOCK(state,0), state.ds.block_start = state.ds.strstart;
  1683. }
  1684. state.ds.strstart++;
  1685. state.ds.lookahead--;
  1686. } else {
  1687. /* There is no previous match to compare with, wait for
  1688. * the next step to decide.
  1689. */
  1690. match_available = 1;
  1691. state.ds.strstart++;
  1692. state.ds.lookahead--;
  1693. }
  1694. // Assert(state,strstart <= isize && lookahead <= isize, "a bit too far");
  1695. /* Make sure that we always have enough lookahead, except
  1696. * at the end of the input file. We need MAX_MATCH bytes
  1697. * for the next match, plus MIN_MATCH bytes to insert the
  1698. * string following the next match.
  1699. */
  1700. if (state.ds.lookahead < MIN_LOOKAHEAD) fill_window(state);
  1701. }
  1702. if (match_available) ct_tally (state,0, state.ds.window[state.ds.strstart-1]);
  1703. return FLUSH_BLOCK(state,1); /* eof */
  1704. }
  1705. int putlocal(struct zlist far *z, WRITEFUNC wfunc,void *param)
  1706. { // Write a local header described by *z to file *f. Return a ZE_ error code.
  1707. PUTLG(LOCSIG, f);
  1708. PUTSH(z->ver, f);
  1709. PUTSH(z->lflg, f);
  1710. PUTSH(z->how, f);
  1711. PUTLG(z->tim, f);
  1712. PUTLG(z->crc, f);
  1713. PUTLG(z->siz, f);
  1714. PUTLG(z->len, f);
  1715. PUTSH(z->nam, f);
  1716. PUTSH(z->ext, f);
  1717. size_t res = (size_t)wfunc(param, z->iname, (unsigned int)z->nam);
  1718. if (res!=z->nam) return ZE_TEMP;
  1719. if (z->ext)
  1720. { res = (size_t)wfunc(param, z->extra, (unsigned int)z->ext);
  1721. if (res!=z->ext) return ZE_TEMP;
  1722. }
  1723. return ZE_OK;
  1724. }
  1725. int putextended(struct zlist far *z, WRITEFUNC wfunc, void *param)
  1726. { // Write an extended local header described by *z to file *f. Returns a ZE_ code
  1727. PUTLG(EXTLOCSIG, f);
  1728. PUTLG(z->crc, f);
  1729. PUTLG(z->siz, f);
  1730. PUTLG(z->len, f);
  1731. return ZE_OK;
  1732. }
  1733. int putcentral(struct zlist far *z, WRITEFUNC wfunc, void *param)
  1734. { // Write a central header entry of *z to file *f. Returns a ZE_ code.
  1735. PUTLG(CENSIG, f);
  1736. PUTSH(z->vem, f);
  1737. PUTSH(z->ver, f);
  1738. PUTSH(z->flg, f);
  1739. PUTSH(z->how, f);
  1740. PUTLG(z->tim, f);
  1741. PUTLG(z->crc, f);
  1742. PUTLG(z->siz, f);
  1743. PUTLG(z->len, f);
  1744. PUTSH(z->nam, f);
  1745. PUTSH(z->cext, f);
  1746. PUTSH(z->com, f);
  1747. PUTSH(z->dsk, f);
  1748. PUTSH(z->att, f);
  1749. PUTLG(z->atx, f);
  1750. PUTLG(z->off, f);
  1751. if ((size_t)wfunc(param, z->iname, (unsigned int)z->nam) != z->nam ||
  1752. (z->cext && (size_t)wfunc(param, z->cextra, (unsigned int)z->cext) != z->cext) ||
  1753. (z->com && (size_t)wfunc(param, z->comment, (unsigned int)z->com) != z->com))
  1754. return ZE_TEMP;
  1755. return ZE_OK;
  1756. }
  1757. int putend(int n, ulg s, ulg c, extent m, char *z, WRITEFUNC wfunc, void *param)
  1758. { // write the end of the central-directory-data to file *f.
  1759. PUTLG(ENDSIG, f);
  1760. PUTSH(0, f);
  1761. PUTSH(0, f);
  1762. PUTSH(n, f);
  1763. PUTSH(n, f);
  1764. PUTLG(s, f);
  1765. PUTLG(c, f);
  1766. PUTSH(m, f);
  1767. // Write the comment, if any
  1768. if (m && wfunc(param, z, (unsigned int)m) != m) return ZE_TEMP;
  1769. return ZE_OK;
  1770. }
  1771. const ulg crc_table[256] = {
  1772. 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
  1773. 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
  1774. 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
  1775. 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
  1776. 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
  1777. 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
  1778. 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
  1779. 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
  1780. 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
  1781. 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
  1782. 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
  1783. 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
  1784. 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
  1785. 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
  1786. 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
  1787. 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
  1788. 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
  1789. 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
  1790. 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
  1791. 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
  1792. 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
  1793. 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
  1794. 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
  1795. 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
  1796. 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
  1797. 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
  1798. 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
  1799. 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
  1800. 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
  1801. 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
  1802. 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
  1803. 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
  1804. 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
  1805. 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
  1806. 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
  1807. 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
  1808. 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
  1809. 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
  1810. 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
  1811. 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
  1812. 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
  1813. 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
  1814. 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
  1815. 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
  1816. 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
  1817. 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
  1818. 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
  1819. 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
  1820. 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
  1821. 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
  1822. 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
  1823. 0x2d02ef8dL
  1824. };
  1825. #define CRC32(c, b) (crc_table[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
  1826. #define DO1(buf) crc = CRC32(crc, *buf++)
  1827. #define DO2(buf) DO1(buf); DO1(buf)
  1828. #define DO4(buf) DO2(buf); DO2(buf)
  1829. #define DO8(buf) DO4(buf); DO4(buf)
  1830. ulg crc32(ulg crc, const uch *buf, extent len)
  1831. { if (buf==NULL) return 0L;
  1832. crc = crc ^ 0xffffffffL;
  1833. while (len >= 8) {DO8(buf); len -= 8;}
  1834. if (len) do {DO1(buf);} while (--len);
  1835. return crc ^ 0xffffffffL; // (instead of ~c for 64-bit machines)
  1836. }
  1837. bool HasZipSuffix(const char *fn)
  1838. { const char *ext = fn+strlen(fn);
  1839. while (ext>fn && *ext!='.') ext--;
  1840. if (ext==fn && *ext!='.') return false;
  1841. if (_stricmp(ext,".Z")==0) return true;
  1842. if (_stricmp(ext,".zip")==0) return true;
  1843. if (_stricmp(ext,".zoo")==0) return true;
  1844. if (_stricmp(ext,".arc")==0) return true;
  1845. if (_stricmp(ext,".lzh")==0) return true;
  1846. if (_stricmp(ext,".arj")==0) return true;
  1847. if (_stricmp(ext,".gz")==0) return true;
  1848. if (_stricmp(ext,".tgz")==0) return true;
  1849. return false;
  1850. }
  1851. #ifdef _WIN32
  1852. time_t filetime2timet(const FILETIME ft)
  1853. { SYSTEMTIME st; FileTimeToSystemTime(&ft,&st);
  1854. if (st.wYear<1970) {st.wYear=1970; st.wMonth=1; st.wDay=1;}
  1855. if (st.wYear>=2038) {st.wYear=2037; st.wMonth=12; st.wDay=31;}
  1856. struct tm tm;
  1857. tm.tm_sec = st.wSecond;
  1858. tm.tm_min = st.wMinute;
  1859. tm.tm_hour = st.wHour;
  1860. tm.tm_mday = st.wDay;
  1861. tm.tm_mon = st.wMonth-1;
  1862. tm.tm_year = st.wYear-1900;
  1863. tm.tm_isdst = 0;
  1864. time_t t = mktime(&tm);
  1865. return t;
  1866. }
  1867. ZRESULT GetFileInfo(HANDLE hf, ulg *attr, long *size, iztimes *times, ulg *timestamp)
  1868. {
  1869. DWORD type=GetFileType(hf);
  1870. if (type!=FILE_TYPE_DISK)
  1871. return ZR_NOTINITED;
  1872. // The handle must be a handle to a file
  1873. // The date and time is returned in a long with the date most significant to allow
  1874. // unsigned integer comparison of absolute times. The attributes have two
  1875. // high bytes unix attr, and two low bytes a mapping of that to DOS attr.
  1876. //struct stat s; int res=stat(fn,&s); if (res!=0) return false;
  1877. // translate windows file attributes into zip ones.
  1878. BY_HANDLE_FILE_INFORMATION bhi;
  1879. BOOL res=GetFileInformationByHandle(hf,&bhi);
  1880. if (!res)
  1881. return ZR_NOFILE;
  1882. FileTimeToLocalFileTime( &bhi.ftLastAccessTime, &bhi.ftLastAccessTime );
  1883. FileTimeToLocalFileTime( &bhi.ftLastWriteTime, &bhi.ftLastWriteTime );
  1884. FileTimeToLocalFileTime( &bhi.ftCreationTime, &bhi.ftCreationTime );
  1885. DWORD fa=bhi.dwFileAttributes;
  1886. ulg a=0;
  1887. // Zip uses the lower word for its interpretation of windows stuff
  1888. if (fa&FILE_ATTRIBUTE_READONLY) a|=0x01;
  1889. if (fa&FILE_ATTRIBUTE_HIDDEN) a|=0x02;
  1890. if (fa&FILE_ATTRIBUTE_SYSTEM) a|=0x04;
  1891. if (fa&FILE_ATTRIBUTE_DIRECTORY)a|=0x10;
  1892. if (fa&FILE_ATTRIBUTE_ARCHIVE) a|=0x20;
  1893. // It uses the upper word for standard unix attr, which we must manually construct
  1894. if (fa&FILE_ATTRIBUTE_DIRECTORY)a|=0x40000000; // directory
  1895. else a|=0x80000000; // normal file
  1896. a|=0x01000000; // readable
  1897. if (fa&FILE_ATTRIBUTE_READONLY) {}
  1898. else a|=0x00800000; // writeable
  1899. // now just a small heuristic to check if it's an executable:
  1900. DWORD red, hsize=GetFileSize(hf,NULL); if (hsize>40)
  1901. { SetFilePointer(hf,0,NULL,FILE_BEGIN); unsigned short magic; ReadFile(hf,&magic,sizeof(magic),&red,NULL);
  1902. SetFilePointer(hf,36,NULL,FILE_BEGIN); unsigned long hpos; ReadFile(hf,&hpos,sizeof(hpos),&red,NULL);
  1903. if (magic==0x54AD && hsize>hpos+4+20+28)
  1904. { SetFilePointer(hf,hpos,NULL,FILE_BEGIN); unsigned long signature; ReadFile(hf,&signature,sizeof(signature),&red,NULL);
  1905. if (signature==IMAGE_DOS_SIGNATURE || signature==IMAGE_OS2_SIGNATURE
  1906. || signature==IMAGE_OS2_SIGNATURE_LE || signature==IMAGE_NT_SIGNATURE)
  1907. { a |= 0x00400000; // executable
  1908. }
  1909. }
  1910. }
  1911. //
  1912. if (attr!=NULL) *attr = a;
  1913. if (size!=NULL) *size = hsize;
  1914. if (times!=NULL)
  1915. { // time_t is 32bit number of seconds elapsed since 0:0:0GMT, Jan1, 1970.
  1916. // but FILETIME is 64bit number of 100-nanosecs since Jan1, 1601
  1917. times->atime = filetime2timet(bhi.ftLastAccessTime);
  1918. times->mtime = filetime2timet(bhi.ftLastWriteTime);
  1919. times->ctime = filetime2timet(bhi.ftCreationTime);
  1920. }
  1921. if (timestamp!=NULL)
  1922. { WORD dosdate,dostime;
  1923. FileTimeToDosDateTime(&bhi.ftLastWriteTime,&dosdate,&dostime);
  1924. *timestamp = (WORD)dostime | (((DWORD)dosdate)<<16);
  1925. }
  1926. return ZR_OK;
  1927. }
  1928. #endif
  1929. #ifndef _WIN32
  1930. int timet_to_timestamp( time_t time )
  1931. {
  1932. struct tm *tm;
  1933. tm = localtime( &time );
  1934. if ( !tm )
  1935. return 0;
  1936. int date = 0;
  1937. date |= ( ( ( tm->tm_year & 0x7f ) + ( 1900 - 1980 ) ) << 9 );
  1938. date |= ( ( ( tm->tm_mon & 0x0f ) + 1 ) << 5 );
  1939. date |= ( ( ( tm->tm_mday & 0x1f ) ) );
  1940. int timepart = 0;
  1941. timepart |= ( ( ( tm->tm_hour & 0x1f ) ) << 11 );
  1942. timepart |= ( ( ( tm->tm_min & 0x3f ) ) << 5 );
  1943. timepart |= ( ( ( tm->tm_sec & 0x3e ) ) >> 1 );
  1944. return time | (date << 16 );
  1945. }
  1946. #endif
  1947. ///////////////////////////////////////////////////////////////////////////////
  1948. ///////////////////////////////////////////////////////////////////////////////
  1949. ///////////////////////////////////////////////////////////////////////////////
  1950. class TZip
  1951. { public:
  1952. TZip() : hfout(0),hmapout(0),zfis(0),obuf(0),hfin(0),writ(0),oerr(false),hasputcen(false),ooffset(0) {}
  1953. ~TZip() {}
  1954. // These variables say about the file we're writing into
  1955. // We can write to pipe, file-by-handle, file-by-name, memory-to-memmapfile
  1956. HANDLE hfout; // if valid, we'll write here (for files or pipes)
  1957. HANDLE hmapout; // otherwise, we'll write here (for memmap)
  1958. unsigned ooffset; // for hfout, this is where the pointer was initially
  1959. ZRESULT oerr; // did a write operation give rise to an error?
  1960. unsigned writ; // how far have we written. This is maintained by Add, not write(), to avoid confusion over seeks
  1961. bool ocanseek; // can we seek?
  1962. char *obuf; // this is where we've locked mmap to view.
  1963. unsigned int opos; // current pos in the mmap
  1964. unsigned int mapsize; // the size of the map we created
  1965. bool hasputcen; // have we yet placed the central directory?
  1966. //
  1967. TZipFileInfo *zfis; // each file gets added onto this list, for writing the table at the end
  1968. ZRESULT Create(void *z,unsigned int len,DWORD flags);
  1969. static unsigned sflush(void *param,const char *buf, unsigned *size);
  1970. static unsigned swrite(void *param,const char *buf, unsigned size);
  1971. unsigned int write(const char *buf,unsigned int size);
  1972. bool oseek(unsigned int pos);
  1973. ZRESULT GetMemory(void **pbuf, unsigned long *plen);
  1974. ZRESULT Close();
  1975. // some variables to do with the file currently being read:
  1976. // I haven't done it object-orientedly here, just put them all
  1977. // together, since OO didn't seem to make the design any clearer.
  1978. ulg attr; iztimes times; ulg timestamp; // all open_* methods set these
  1979. bool iseekable; long isize,ired; // size is not set until close() on pips
  1980. ulg crc; // crc is not set until close(). iwrit is cumulative
  1981. HANDLE hfin; bool selfclosehf; // for input files and pipes
  1982. const char *bufin; unsigned int lenin,posin; // for memory
  1983. // and a variable for what we've done with the input: (i.e. compressed it!)
  1984. ulg csize; // compressed size, set by the compression routines
  1985. // and this is used by some of the compression routines
  1986. char buf[16384];
  1987. ZRESULT open_file(const TCHAR *fn);
  1988. ZRESULT open_handle(HANDLE hf,unsigned int len);
  1989. ZRESULT open_mem(void *src,unsigned int len);
  1990. ZRESULT open_dir();
  1991. static unsigned sread(TState &s,char *buf,unsigned size);
  1992. unsigned read(char *buf, unsigned size);
  1993. ZRESULT iclose();
  1994. ZRESULT ideflate(TZipFileInfo *zfi);
  1995. ZRESULT istore();
  1996. ZRESULT Add(const char *odstzn, void *src,unsigned int len, DWORD flags);
  1997. ZRESULT AddCentral();
  1998. };
  1999. ZRESULT TZip::Create(void *z,unsigned int len,DWORD flags)
  2000. {
  2001. if (hfout!=0 || hmapout!=0 || obuf!=0 || writ!=0 || oerr!=ZR_OK || hasputcen)
  2002. return ZR_NOTINITED;
  2003. //
  2004. if (flags==ZIP_MEMORY)
  2005. {
  2006. if (len==0)
  2007. return ZR_MEMSIZE;
  2008. if (z!=0)
  2009. obuf=(char*)z;
  2010. else
  2011. {
  2012. #ifdef _WIN32
  2013. hmapout = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,len,NULL);
  2014. if (hmapout==NULL)
  2015. return ZR_NOALLOC;
  2016. obuf = (char*)MapViewOfFile(hmapout,FILE_MAP_ALL_ACCESS,0,0,len);
  2017. if (obuf==0)
  2018. {
  2019. CloseHandle(hmapout);
  2020. hmapout=0;
  2021. return ZR_NOALLOC;
  2022. }
  2023. #endif
  2024. #ifdef POSIX
  2025. obuf = (char*) calloc( len, 1 );
  2026. hmapout = (void*)-1; // sentinel to let close know it's a file in posix.
  2027. if ( !obuf )
  2028. return ZR_NOALLOC;
  2029. #endif
  2030. }
  2031. ocanseek=true;
  2032. opos=0;
  2033. mapsize=len;
  2034. return ZR_OK;
  2035. }
  2036. #ifdef _WIN32
  2037. else if (flags==ZIP_HANDLE)
  2038. {
  2039. HANDLE hf = (HANDLE)z;
  2040. BOOL res = DuplicateHandle(GetCurrentProcess(),hf,GetCurrentProcess(),&hfout,0,FALSE,DUPLICATE_SAME_ACCESS);
  2041. if (!res)
  2042. return ZR_NODUPH;
  2043. // now we have our own hfout, which we must close. And the caller will close hf
  2044. DWORD type = GetFileType(hfout);
  2045. ocanseek = (type==FILE_TYPE_DISK);
  2046. if (type==FILE_TYPE_DISK)
  2047. ooffset=SetFilePointer(hfout,0,NULL,FILE_CURRENT);
  2048. else
  2049. ooffset=0;
  2050. return ZR_OK;
  2051. }
  2052. else if (flags==ZIP_FILENAME)
  2053. {
  2054. #ifdef _UNICODE
  2055. const TCHAR *fn = (const TCHAR*)z;
  2056. hfout = CreateFileW(fn,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  2057. #else
  2058. const char *fn = (const char*)z;
  2059. hfout = CreateFileA(fn,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  2060. #endif
  2061. if (hfout==INVALID_HANDLE_VALUE)
  2062. {
  2063. hfout=0;
  2064. return ZR_NOFILE;
  2065. }
  2066. ocanseek=true;
  2067. ooffset=0;
  2068. return ZR_OK;
  2069. }
  2070. #endif
  2071. else
  2072. return ZR_ARGS;
  2073. }
  2074. unsigned TZip::sflush(void *param,const char *buf, unsigned *size)
  2075. { // static
  2076. if (*size==0) return 0;
  2077. TZip *zip = (TZip*)param;
  2078. unsigned int writ = zip->write(buf,*size);
  2079. if (writ!=0) *size=0;
  2080. return writ;
  2081. }
  2082. unsigned TZip::swrite(void *param,const char *buf, unsigned size)
  2083. { // static
  2084. if (size==0) return 0;
  2085. TZip *zip=(TZip*)param; return zip->write(buf,size);
  2086. }
  2087. unsigned int TZip::write(const char *pBuf,unsigned int size)
  2088. { if (obuf!=0)
  2089. { if (opos+size>=mapsize) {oerr=ZR_MEMSIZE; return 0;}
  2090. memcpy(obuf+opos, pBuf, size);
  2091. opos+=size;
  2092. return size;
  2093. }
  2094. #ifdef _WIN32
  2095. else if (hfout!=0)
  2096. { DWORD writF; WriteFile(hfout, pBuf,size,&writF,NULL);
  2097. return writF;
  2098. }
  2099. #endif
  2100. oerr=ZR_NOTINITED; return 0;
  2101. }
  2102. bool TZip::oseek(unsigned int pos)
  2103. { if (!ocanseek) {oerr=ZR_SEEK; return false;}
  2104. if (obuf!=0)
  2105. { if (pos>=mapsize) {oerr=ZR_MEMSIZE; return false;}
  2106. opos=pos;
  2107. return true;
  2108. }
  2109. #ifdef _WIN32
  2110. else if (hfout!=0)
  2111. { SetFilePointer(hfout,pos+ooffset,NULL,FILE_BEGIN);
  2112. return true;
  2113. }
  2114. #endif
  2115. oerr=ZR_NOTINITED; return 0;
  2116. }
  2117. ZRESULT TZip::GetMemory(void **pbuf, unsigned long *plen)
  2118. { // When the user calls GetMemory, they're presumably at the end
  2119. // of all their adding. In any case, we have to add the central
  2120. // directory now, otherwise the memory we tell them won't be complete.
  2121. if (!hasputcen) AddCentral(); hasputcen=true;
  2122. if (pbuf!=NULL) *pbuf=(void*)obuf;
  2123. if (plen!=NULL) *plen=writ;
  2124. if (obuf==NULL) return ZR_NOTMMAP;
  2125. return ZR_OK;
  2126. }
  2127. ZRESULT TZip::Close()
  2128. { // if the directory hadn't already been added through a call to GetMemory,
  2129. // then we do it now
  2130. ZRESULT res=ZR_OK; if (!hasputcen) res=AddCentral(); hasputcen=true;
  2131. if (obuf!=0 && hmapout!=0)
  2132. #ifdef _WIN32
  2133. UnmapViewOfFile(obuf);
  2134. #elif defined( POSIX )
  2135. free(obuf);
  2136. #endif
  2137. obuf=0;
  2138. #ifdef _WIN32
  2139. if (hmapout!=0) CloseHandle(hmapout); hmapout=0;
  2140. if (hfout!=0) CloseHandle(hfout); hfout=0;
  2141. #endif
  2142. return res;
  2143. }
  2144. ZRESULT TZip::open_file(const TCHAR *fn)
  2145. { hfin=0; bufin=0; selfclosehf=false; crc=CRCVAL_INITIAL; isize=0; csize=0; ired=0;
  2146. if (fn==0) return ZR_ARGS;
  2147. HANDLE hf = INVALID_HANDLE_VALUE;
  2148. #ifdef _WIN32
  2149. hf = CreateFile(fn,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
  2150. #endif
  2151. if (hf==INVALID_HANDLE_VALUE) return ZR_NOFILE;
  2152. ZRESULT res = open_handle(hf,0);
  2153. if (res!=ZR_OK) {
  2154. #ifdef _WIN32
  2155. CloseHandle(hf);
  2156. #endif
  2157. return res;
  2158. }
  2159. selfclosehf=true;
  2160. return ZR_OK;
  2161. }
  2162. ZRESULT TZip::open_handle(HANDLE hf,unsigned int len)
  2163. { hfin=0; bufin=0; selfclosehf=false; crc=CRCVAL_INITIAL; isize=0; csize=0; ired=0;
  2164. if (hf==0 || hf==INVALID_HANDLE_VALUE) return ZR_ARGS;
  2165. #ifdef _WIN32
  2166. DWORD type = GetFileType(hf);
  2167. if (type==FILE_TYPE_DISK)
  2168. { ZRESULT res = GetFileInfo(hf,&attr,&isize,&times,&timestamp);
  2169. if (res!=ZR_OK) return res;
  2170. SetFilePointer(hf,0,NULL,FILE_BEGIN); // because GetFileInfo will have screwed it up
  2171. iseekable=true; hfin=hf;
  2172. return ZR_OK;
  2173. }
  2174. else
  2175. { attr= 0x80000000; // just a normal file
  2176. isize = -1; // can't know size until at the end
  2177. if (len!=0) isize=len; // unless we were told explicitly!
  2178. iseekable=false;
  2179. SYSTEMTIME st; GetLocalTime(&st);
  2180. FILETIME ft; SystemTimeToFileTime(&st,&ft);
  2181. WORD dosdate,dostime; FileTimeToDosDateTime(&ft,&dosdate,&dostime);
  2182. times.atime = filetime2timet(ft);
  2183. times.mtime = times.atime;
  2184. times.ctime = times.atime;
  2185. timestamp = (WORD)dostime | (((DWORD)dosdate)<<16);
  2186. hfin=hf;
  2187. return ZR_OK;
  2188. }
  2189. #else
  2190. return ZR_FAILED;
  2191. #endif
  2192. }
  2193. ZRESULT TZip::open_mem(void *src,unsigned int len)
  2194. { hfin=0; bufin=(const char*)src; selfclosehf=false; crc=CRCVAL_INITIAL; ired=0; csize=0; ired=0;
  2195. lenin=len; posin=0;
  2196. if (src==0 || len==0) return ZR_ARGS;
  2197. #ifdef _WIN32
  2198. attr= 0x80000000; // just a normal file
  2199. isize = len;
  2200. iseekable=true;
  2201. SYSTEMTIME st; GetLocalTime(&st);
  2202. FILETIME ft; SystemTimeToFileTime(&st,&ft);
  2203. WORD dosdate,dostime; FileTimeToDosDateTime(&ft,&dosdate,&dostime);
  2204. times.atime = filetime2timet(ft);
  2205. times.mtime = times.atime;
  2206. times.ctime = times.atime;
  2207. timestamp = (WORD)dostime | (((DWORD)dosdate)<<16);
  2208. return ZR_OK;
  2209. #else
  2210. times.atime = time(NULL);
  2211. times.mtime = times.atime;
  2212. times.ctime = times.atime;
  2213. timestamp = timet_to_timestamp( times.atime );
  2214. return ZR_OK;
  2215. #endif
  2216. }
  2217. ZRESULT TZip::open_dir()
  2218. { hfin=0; bufin=0; selfclosehf=false; crc=CRCVAL_INITIAL; isize=0; csize=0; ired=0;
  2219. #ifdef _WIN32
  2220. attr= 0x41C00010; // a readable writable directory, and again directory
  2221. isize = 0;
  2222. iseekable=false;
  2223. SYSTEMTIME st; GetLocalTime(&st);
  2224. FILETIME ft; SystemTimeToFileTime(&st,&ft);
  2225. WORD dosdate,dostime; FileTimeToDosDateTime(&ft,&dosdate,&dostime);
  2226. times.atime = filetime2timet(ft);
  2227. times.mtime = times.atime;
  2228. times.ctime = times.atime;
  2229. timestamp = (WORD)dostime | (((DWORD)dosdate)<<16);
  2230. return ZR_OK;
  2231. #else
  2232. times.atime = time(NULL);
  2233. times.mtime = times.atime;
  2234. times.ctime = times.atime;
  2235. timestamp = timet_to_timestamp( times.atime );
  2236. return ZR_OK;
  2237. #endif
  2238. }
  2239. unsigned TZip::sread(TState &s,char *buf,unsigned size)
  2240. { // static
  2241. TZip *zip = (TZip*)s.param;
  2242. return zip->read(buf,size);
  2243. }
  2244. unsigned TZip::read(char *pBuf, unsigned size)
  2245. { if (bufin!=0)
  2246. { if (posin>=lenin) return 0; // end of input
  2247. ulg red = lenin-posin;
  2248. if (red>size) red=size;
  2249. memcpy( pBuf, bufin+posin, red);
  2250. posin += red;
  2251. ired += red;
  2252. crc = crc32(crc, (uch*)pBuf, red);
  2253. return red;
  2254. }
  2255. #ifdef _WIN32
  2256. else if (hfin!=0)
  2257. { DWORD red;
  2258. BOOL ok = ReadFile(hfin, pBuf,size,&red,NULL);
  2259. if (!ok) return 0;
  2260. ired += red;
  2261. crc = crc32(crc, (uch*)pBuf, red);
  2262. return red;
  2263. }
  2264. #endif
  2265. else {oerr=ZR_NOTINITED; return 0;}
  2266. }
  2267. ZRESULT TZip::iclose()
  2268. {
  2269. #ifdef _WIN32
  2270. if (selfclosehf && hfin!=0) CloseHandle(hfin);
  2271. #endif
  2272. hfin=0;
  2273. bool mismatch = (isize!=-1 && isize!=ired);
  2274. isize=ired; // and crc has been being updated anyway
  2275. if (mismatch) return ZR_MISSIZE;
  2276. else return ZR_OK;
  2277. }
  2278. ZRESULT TZip::ideflate(TZipFileInfo *zfi)
  2279. { TState state;
  2280. state.readfunc=sread; state.flush_outbuf=sflush;
  2281. state.param=this; state.level=8; state.seekable=iseekable; state.err=NULL;
  2282. // the following line will make ct_init realise it has to perform the init
  2283. state.ts.static_dtree[0].dl.len = 0;
  2284. // It would be nicer if I could figure out precisely which data had to
  2285. // be initted each time, and which didn't, but that's kind of difficult.
  2286. // Maybe for the next version...
  2287. //
  2288. bi_init(state,buf, sizeof(buf), TRUE); // it used to be just 1024-size, not 16384 as here
  2289. ct_init(state,&zfi->att);
  2290. lm_init(state,state.level, &zfi->flg);
  2291. ulg sz = deflate(state);
  2292. csize=sz;
  2293. if (state.err!=NULL) return ZR_FLATE;
  2294. else return ZR_OK;
  2295. }
  2296. ZRESULT TZip::istore()
  2297. { ulg size=0;
  2298. for (;;)
  2299. { unsigned int cin=read(buf,16384); if (cin<=0 || cin==(unsigned int)EOF) break;
  2300. unsigned int cout = write(buf,cin); if (cout!=cin) return ZR_MISSIZE;
  2301. size += cin;
  2302. }
  2303. csize=size;
  2304. return ZR_OK;
  2305. }
  2306. ZRESULT TZip::Add(const char *odstzn, void *src,unsigned int len, DWORD flags)
  2307. {
  2308. if (oerr)
  2309. return ZR_FAILED;
  2310. if (hasputcen)
  2311. return ZR_ENDED;
  2312. // zip has its own notion of what its names should look like: i.e. dir/file.stuff
  2313. char dstzn[MAX_PATH];
  2314. strcpy(dstzn, odstzn);
  2315. if (*dstzn == 0)
  2316. return ZR_ARGS;
  2317. char *d=dstzn;
  2318. while (*d != 0)
  2319. {
  2320. if (*d == '\\')
  2321. *d = '/';
  2322. d++;
  2323. }
  2324. bool isdir = (flags==ZIP_FOLDER);
  2325. bool needs_trailing_slash = (isdir && dstzn[strlen(dstzn)-1]!='/');
  2326. int method=DEFLATE;
  2327. if (isdir || HasZipSuffix(dstzn))
  2328. method=STORE;
  2329. // now open whatever was our input source:
  2330. ZRESULT openres;
  2331. if (flags==ZIP_FILENAME)
  2332. openres=open_file((const TCHAR*)src);
  2333. else if (flags==ZIP_HANDLE)
  2334. openres=open_handle((HANDLE)src,len);
  2335. else if (flags==ZIP_MEMORY)
  2336. openres=open_mem(src,len);
  2337. else if (flags==ZIP_FOLDER)
  2338. openres=open_dir();
  2339. else return ZR_ARGS;
  2340. if (openres!=ZR_OK)
  2341. return openres;
  2342. // A zip "entry" consists of a local header (which includes the file name),
  2343. // then the compressed data, and possibly an extended local header.
  2344. // Initialize the local header
  2345. TZipFileInfo zfi; zfi.nxt=NULL;
  2346. strcpy(zfi.name,"");
  2347. strcpy(zfi.iname,dstzn);
  2348. zfi.nam=strlen(zfi.iname);
  2349. if (needs_trailing_slash)
  2350. {
  2351. strcat(zfi.iname,"/");
  2352. zfi.nam++;
  2353. }
  2354. strcpy(zfi.zname,"");
  2355. zfi.extra=NULL; zfi.ext=0; // extra header to go after this compressed data, and its length
  2356. zfi.cextra=NULL; zfi.cext=0; // extra header to go in the central end-of-zip directory, and its length
  2357. zfi.comment=NULL; zfi.com=0; // comment, and its length
  2358. zfi.mark = 1;
  2359. zfi.dosflag = 0;
  2360. zfi.att = (ush)BINARY;
  2361. zfi.vem = (ush)0xB17; // 0xB00 is win32 os-code. 0x17 is 23 in decimal: zip 2.3
  2362. zfi.ver = (ush)20; // Needs PKUNZIP 2.0 to unzip it
  2363. zfi.tim = timestamp;
  2364. // Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc.
  2365. zfi.crc = 0; // to be updated later
  2366. zfi.flg = 8; // 8 means 'there is an extra header'. Assume for the moment that we need it.
  2367. zfi.lflg = zfi.flg; // to be updated later
  2368. zfi.how = (ush)method; // to be updated later
  2369. zfi.siz = (ulg)(method==STORE && isize>=0 ? isize : 0); // to be updated later
  2370. zfi.len = (ulg)(isize); // to be updated later
  2371. zfi.dsk = 0;
  2372. zfi.atx = attr;
  2373. zfi.off = writ+ooffset; // offset within file of the start of this local record
  2374. // stuff the 'times' structure into zfi.extra
  2375. char xloc[EB_L_UT_SIZE];
  2376. zfi.extra=xloc;
  2377. zfi.ext=EB_L_UT_SIZE;
  2378. char xcen[EB_C_UT_SIZE];
  2379. zfi.cextra=xcen;
  2380. zfi.cext=EB_C_UT_SIZE;
  2381. xloc[0] = 'U';
  2382. xloc[1] = 'T';
  2383. xloc[2] = EB_UT_LEN(3); // length of data part of e.f.
  2384. xloc[3] = 0;
  2385. xloc[4] = EB_UT_FL_MTIME | EB_UT_FL_ATIME | EB_UT_FL_CTIME;
  2386. xloc[5] = (char)(times.mtime);
  2387. xloc[6] = (char)(times.mtime >> 8);
  2388. xloc[7] = (char)(times.mtime >> 16);
  2389. xloc[8] = (char)(times.mtime >> 24);
  2390. xloc[9] = (char)(times.atime);
  2391. xloc[10] = (char)(times.atime >> 8);
  2392. xloc[11] = (char)(times.atime >> 16);
  2393. xloc[12] = (char)(times.atime >> 24);
  2394. xloc[13] = (char)(times.ctime);
  2395. xloc[14] = (char)(times.ctime >> 8);
  2396. xloc[15] = (char)(times.ctime >> 16);
  2397. xloc[16] = (char)(times.ctime >> 24);
  2398. memcpy(zfi.cextra,zfi.extra,EB_C_UT_SIZE);
  2399. zfi.cextra[EB_LEN] = EB_UT_LEN(1);
  2400. // (1) Start by writing the local header:
  2401. int r = putlocal(&zfi,swrite,this);
  2402. if (r!=ZE_OK)
  2403. {
  2404. iclose();
  2405. return ZR_WRITE;
  2406. }
  2407. writ += 4 + LOCHEAD + (unsigned int)zfi.nam + (unsigned int)zfi.ext;
  2408. if (oerr!=ZR_OK)
  2409. {
  2410. iclose();
  2411. return oerr;
  2412. }
  2413. //(2) Write deflated/stored file to zip file
  2414. ZRESULT writeres=ZR_OK;
  2415. if (!isdir && method==DEFLATE)
  2416. writeres=ideflate(&zfi);
  2417. else if (!isdir && method==STORE)
  2418. writeres=istore();
  2419. else if (isdir)
  2420. csize=0;
  2421. iclose();
  2422. writ += csize;
  2423. if (oerr!=ZR_OK)
  2424. return oerr;
  2425. if (writeres!=ZR_OK)
  2426. return ZR_WRITE;
  2427. // (3) Either rewrite the local header with correct information...
  2428. bool first_header_has_size_right = (zfi.siz==csize);
  2429. zfi.crc = crc;
  2430. zfi.siz = csize;
  2431. zfi.len = isize;
  2432. if (ocanseek)
  2433. {
  2434. zfi.how = (ush)method;
  2435. if ((zfi.flg & 1) == 0)
  2436. zfi.flg &= ~8; // clear the extended local header flag
  2437. zfi.lflg = zfi.flg;
  2438. // rewrite the local header:
  2439. if (!oseek(zfi.off-ooffset))
  2440. return ZR_SEEK;
  2441. if ((r = putlocal(&zfi, swrite,this)) != ZE_OK)
  2442. return ZR_WRITE;
  2443. if (!oseek(writ))
  2444. return ZR_SEEK;
  2445. }
  2446. else
  2447. {
  2448. // (4) ... or put an updated header at the end
  2449. if (zfi.how != (ush) method)
  2450. return ZR_NOCHANGE;
  2451. if (method==STORE && !first_header_has_size_right)
  2452. return ZR_NOCHANGE;
  2453. if ((r = putextended(&zfi, swrite,this)) != ZE_OK)
  2454. return ZR_WRITE;
  2455. writ += 16L;
  2456. zfi.flg = zfi.lflg; // if flg modified by inflate, for the central index
  2457. }
  2458. if (oerr!=ZR_OK)
  2459. return oerr;
  2460. // Keep a copy of the zipfileinfo, for our end-of-zip directory
  2461. char *cextra = new char[zfi.cext];
  2462. memcpy(cextra,zfi.cextra,zfi.cext); zfi.cextra=cextra;
  2463. TZipFileInfo *pzfi = new TZipFileInfo;
  2464. memcpy(pzfi,&zfi,sizeof(zfi));
  2465. if (zfis==NULL)
  2466. zfis=pzfi;
  2467. else
  2468. {
  2469. TZipFileInfo *z=zfis;
  2470. while (z->nxt!=NULL)
  2471. z=z->nxt;
  2472. z->nxt=pzfi;
  2473. }
  2474. return ZR_OK;
  2475. }
  2476. ZRESULT TZip::AddCentral()
  2477. { // write central directory
  2478. int numentries = 0;
  2479. ulg pos_at_start_of_central = writ;
  2480. //ulg tot_unc_size=0, tot_compressed_size=0;
  2481. bool okay=true;
  2482. for (TZipFileInfo *zfi=zfis; zfi!=NULL; )
  2483. { if (okay)
  2484. { int res = putcentral(zfi, swrite,this);
  2485. if (res!=ZE_OK) okay=false;
  2486. }
  2487. writ += 4 + CENHEAD + (unsigned int)zfi->nam + (unsigned int)zfi->cext + (unsigned int)zfi->com;
  2488. //tot_unc_size += zfi->len;
  2489. //tot_compressed_size += zfi->siz;
  2490. numentries++;
  2491. //
  2492. TZipFileInfo *zfinext = zfi->nxt;
  2493. if (zfi->cextra!=0) delete[] zfi->cextra;
  2494. delete zfi;
  2495. zfi = zfinext;
  2496. }
  2497. ulg center_size = writ - pos_at_start_of_central;
  2498. if (okay)
  2499. { int res = putend(numentries, center_size, pos_at_start_of_central+ooffset, 0, NULL, swrite,this);
  2500. if (res!=ZE_OK) okay=false;
  2501. writ += 4 + ENDHEAD + 0;
  2502. }
  2503. if (!okay) return ZR_WRITE;
  2504. return ZR_OK;
  2505. }
  2506. unsigned int FormatZipMessageZ(ZRESULT code, char *buf,unsigned int len)
  2507. { if (code==ZR_RECENT) code=lasterrorZ;
  2508. const char *msg="unknown zip result code";
  2509. switch (code)
  2510. { case ZR_OK: msg="Success"; break;
  2511. case ZR_NODUPH: msg="Culdn't duplicate handle"; break;
  2512. case ZR_NOFILE: msg="Couldn't create/open file"; break;
  2513. case ZR_NOALLOC: msg="Failed to allocate memory"; break;
  2514. case ZR_WRITE: msg="Error writing to file"; break;
  2515. case ZR_NOTFOUND: msg="File not found in the zipfile"; break;
  2516. case ZR_MORE: msg="Still more data to unzip"; break;
  2517. case ZR_CORRUPT: msg="Zipfile is corrupt or not a zipfile"; break;
  2518. case ZR_READ: msg="Error reading file"; break;
  2519. case ZR_ARGS: msg="Caller: faulty arguments"; break;
  2520. case ZR_PARTIALUNZ: msg="Caller: the file had already been partially unzipped"; break;
  2521. case ZR_NOTMMAP: msg="Caller: can only get memory of a memory zipfile"; break;
  2522. case ZR_MEMSIZE: msg="Caller: not enough space allocated for memory zipfile"; break;
  2523. case ZR_FAILED: msg="Caller: there was a previous error"; break;
  2524. case ZR_ENDED: msg="Caller: additions to the zip have already been ended"; break;
  2525. case ZR_ZMODE: msg="Caller: mixing creation and opening of zip"; break;
  2526. case ZR_NOTINITED: msg="Zip-bug: internal initialisation not completed"; break;
  2527. case ZR_SEEK: msg="Zip-bug: trying to seek the unseekable"; break;
  2528. case ZR_MISSIZE: msg="Zip-bug: the anticipated size turned out wrong"; break;
  2529. case ZR_NOCHANGE: msg="Zip-bug: tried to change mind, but not allowed"; break;
  2530. case ZR_FLATE: msg="Zip-bug: an internal error during flation"; break;
  2531. }
  2532. unsigned int mlen=(unsigned int)strlen(msg);
  2533. if (buf==0 || len==0) return mlen;
  2534. unsigned int n=mlen; if (n+1>len) n=len-1;
  2535. memcpy(buf,msg,n); buf[n]=0;
  2536. return mlen;
  2537. }
  2538. typedef struct
  2539. { DWORD flag;
  2540. TZip *zip;
  2541. } TZipHandleData;
  2542. HZIP CreateZipZ(void *z,unsigned int len,DWORD flags)
  2543. {
  2544. _tzset();
  2545. TZip *zip = new TZip();
  2546. lasterrorZ = zip->Create(z,len,flags);
  2547. if (lasterrorZ != ZR_OK)
  2548. {
  2549. delete zip;
  2550. return 0;
  2551. }
  2552. TZipHandleData *han = new TZipHandleData;
  2553. han->flag = 2;
  2554. han->zip = zip;
  2555. return (HZIP)han;
  2556. }
  2557. ZRESULT ZipAdd(HZIP hz, const TCHAR *dstzn, void *src, unsigned int len, DWORD flags)
  2558. {
  2559. if (hz == 0)
  2560. {
  2561. lasterrorZ = ZR_ARGS;
  2562. return ZR_ARGS;
  2563. }
  2564. TZipHandleData *han = (TZipHandleData*)hz;
  2565. if (han->flag != 2)
  2566. {
  2567. lasterrorZ = ZR_ZMODE;
  2568. return ZR_ZMODE;
  2569. }
  2570. TZip *zip = han->zip;
  2571. if (flags == ZIP_FILENAME)
  2572. {
  2573. char szDest[MAX_PATH*2];
  2574. memset(szDest, 0, sizeof(szDest));
  2575. #ifdef _UNICODE
  2576. // need to convert Unicode dest to ANSI
  2577. int nActualChars = WideCharToMultiByte(CP_ACP, // code page
  2578. 0, // performance and mapping flags
  2579. (LPCWSTR) dstzn, // wide-character string
  2580. -1, // number of chars in string
  2581. szDest, // buffer for new string
  2582. MAX_PATH*2-2, // size of buffer
  2583. NULL, // default for unmappable chars
  2584. NULL); // set when default char used
  2585. if (nActualChars == 0)
  2586. return ZR_ARGS;
  2587. #else
  2588. strcpy(szDest, dstzn);
  2589. #endif
  2590. lasterrorZ = zip->Add(szDest, src, len, flags);
  2591. }
  2592. else
  2593. {
  2594. lasterrorZ = zip->Add((char *)dstzn, src, len, flags);
  2595. }
  2596. return lasterrorZ;
  2597. }
  2598. ZRESULT ZipGetMemory(HZIP hz, void **buf, unsigned long *len)
  2599. { if (hz==0) {if (buf!=0) *buf=0; if (len!=0) *len=0; lasterrorZ=ZR_ARGS;return ZR_ARGS;}
  2600. TZipHandleData *han = (TZipHandleData*)hz;
  2601. if (han->flag!=2) {lasterrorZ=ZR_ZMODE;return ZR_ZMODE;}
  2602. TZip *zip = han->zip;
  2603. lasterrorZ = zip->GetMemory(buf,len);
  2604. return lasterrorZ;
  2605. }
  2606. ZRESULT CloseZipZ(HZIP hz)
  2607. { if (hz==0) {lasterrorZ=ZR_ARGS;return ZR_ARGS;}
  2608. TZipHandleData *han = (TZipHandleData*)hz;
  2609. if (han->flag!=2) {lasterrorZ=ZR_ZMODE;return ZR_ZMODE;}
  2610. TZip *zip = han->zip;
  2611. lasterrorZ = zip->Close();
  2612. delete zip;
  2613. delete han;
  2614. return lasterrorZ;
  2615. }
  2616. bool IsZipHandleZ(HZIP hz)
  2617. { if (hz==0) return true;
  2618. TZipHandleData *han = (TZipHandleData*)hz;
  2619. return (han->flag==2);
  2620. }