Counter Strike : Global Offensive Source Code
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.

3078 lines
112 KiB

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