当前位置:   article > 正文

[C++ ZIP] a class for zip

[C++ ZIP] a class for zip

CPP

code:

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


H

code:

  1. #ifndef _zip_H
  2. #define _zip_H
  3. // add for my VC++6.0 MFC Project.
  4. // #include "StdAfx.h" in cpp
  5. // ZIP functions -- for creating zip files
  6. // This file is a repackaged form of the Info-Zip source code available
  7. // at www.info-zip.org. The original copyright notice may be found in
  8. // zip.cpp. The repackaging was done by Lucian Wischik to simplify and
  9. // extend its use in Windows/C++. Also to add encryption and unicode.
  10. #ifndef _unzip_H
  11. DECLARE_HANDLE(HZIP);
  12. #endif
  13. // An HZIP identifies a zip file that is being created
  14. typedef DWORD ZRESULT;
  15. // return codes from any of the zip functions. Listed later.
  16. HZIP CreateZip(const TCHAR *fn, const char *password);
  17. HZIP CreateZip(void *buf,unsigned int len, const char *password);
  18. HZIP CreateZipHandle(HANDLE h, const char *password);
  19. // CreateZip - call this to start the creation of a zip file.
  20. // As the zip is being created, it will be stored somewhere:
  21. // to a pipe: CreateZipHandle(hpipe_write);
  22. // in a file (by handle): CreateZipHandle(hfile);
  23. // in a file (by name): CreateZip("c:\\test.zip");
  24. // in memory: CreateZip(buf, len);
  25. // or in pagefile memory: CreateZip(0, len);
  26. // The final case stores it in memory backed by the system paging file,
  27. // where the zip may not exceed len bytes. This is a bit friendlier than
  28. // allocating memory with new[]: it won't lead to fragmentation, and the
  29. // memory won't be touched unless needed. That means you can give very
  30. // large estimates of the maximum-size without too much worry.
  31. // As for the password, it lets you encrypt every file in the archive.
  32. // (This api doesn't support per-file encryption.)
  33. // Note: because pipes don't allow random access, the structure of a zipfile
  34. // created into a pipe is slightly different from that created into a file
  35. // or memory. In particular, the compressed-size of the item cannot be
  36. // stored in the zipfile until after the item itself. (Also, for an item added
  37. // itself via a pipe, the uncompressed-size might not either be known until
  38. // after.) This is not normally a problem. But if you try to unzip via a pipe
  39. // as well, then the unzipper will not know these things about the item until
  40. // after it has been unzipped. Therefore: for unzippers which don't just write
  41. // each item to disk or to a pipe, but instead pre-allocate memory space into
  42. // which to unzip them, then either you have to create the zip not to a pipe,
  43. // or you have to add items not from a pipe, or at least when adding items
  44. // from a pipe you have to specify the length.
  45. // Note: for windows-ce, you cannot close the handle until after CloseZip.
  46. // but for real windows, the zip makes its own copy of your handle, so you
  47. // can close yours anytime.
  48. ZRESULT ZipAdd(HZIP hz,const TCHAR *dstzn, const TCHAR *fn);
  49. ZRESULT ZipAdd(HZIP hz,const TCHAR *dstzn, void *src,unsigned int len);
  50. ZRESULT ZipAddHandle(HZIP hz,const TCHAR *dstzn, HANDLE h);
  51. ZRESULT ZipAddHandle(HZIP hz,const TCHAR *dstzn, HANDLE h, unsigned int len);
  52. ZRESULT ZipAddFolder(HZIP hz,const TCHAR *dstzn);
  53. // ZipAdd - call this for each file to be added to the zip.
  54. // dstzn is the name that the file will be stored as in the zip file.
  55. // The file to be added to the zip can come
  56. // from a pipe: ZipAddHandle(hz,"file.dat", hpipe_read);
  57. // from a file: ZipAddHandle(hz,"file.dat", hfile);
  58. // from a filen: ZipAdd(hz,"file.dat", "c:\\docs\\origfile.dat");
  59. // from memory: ZipAdd(hz,"subdir\\file.dat", buf,len);
  60. // (folder): ZipAddFolder(hz,"subdir");
  61. // Note: if adding an item from a pipe, and if also creating the zip file itself
  62. // to a pipe, then you might wish to pass a non-zero length to the ZipAddHandle
  63. // function. This will let the zipfile store the item's size ahead of the
  64. // compressed item itself, which in turn makes it easier when unzipping the
  65. // zipfile from a pipe.
  66. ZRESULT ZipGetMemory(HZIP hz, void **buf, unsigned long *len);
  67. // ZipGetMemory - If the zip was created in memory, via ZipCreate(0,len),
  68. // then this function will return information about that memory block.
  69. // buf will receive a pointer to its start, and len its length.
  70. // Note: you can't add any more after calling this.
  71. ZRESULT CloseZip(HZIP hz);
  72. // CloseZip - the zip handle must be closed with this function.
  73. unsigned int FormatZipMessage(ZRESULT code, TCHAR *buf,unsigned int len);
  74. // FormatZipMessage - given an error code, formats it as a string.
  75. // It returns the length of the error message. If buf/len points
  76. // to a real buffer, then it also writes as much as possible into there.
  77. // These are the result codes:
  78. #define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned,
  79. #define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage.
  80. // The following come from general system stuff (e.g. files not openable)
  81. #define ZR_GENMASK 0x0000FF00
  82. #define ZR_NODUPH 0x00000100 // couldn't duplicate the handle
  83. #define ZR_NOFILE 0x00000200 // couldn't create/open the file
  84. #define ZR_NOALLOC 0x00000300 // failed to allocate some resource
  85. #define ZR_WRITE 0x00000400 // a general error writing to the file
  86. #define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip
  87. #define ZR_MORE 0x00000600 // there's still more data to be unzipped
  88. #define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile
  89. #define ZR_READ 0x00000800 // a general error reading the file
  90. // The following come from mistakes on the part of the caller
  91. #define ZR_CALLERMASK 0x00FF0000
  92. #define ZR_ARGS 0x00010000 // general mistake with the arguments
  93. #define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't
  94. #define ZR_MEMSIZE 0x00030000 // the memory size is too small
  95. #define ZR_FAILED 0x00040000 // the thing was already failed when you called this function
  96. #define ZR_ENDED 0x00050000 // the zip creation has already been closed
  97. #define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken
  98. #define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped
  99. #define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip
  100. // The following come from bugs within the zip library itself
  101. #define ZR_BUGMASK 0xFF000000
  102. #define ZR_NOTINITED 0x01000000 // initialisation didn't work
  103. #define ZR_SEEK 0x02000000 // trying to seek in an unseekable file
  104. #define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed
  105. #define ZR_FLATE 0x05000000 // an internal error in the de/inflation code
  106. // e.g.
  107. //
  108. // (1) Traditional use, creating a zipfile from existing files
  109. // HZIP hz = CreateZip("c:\\simple1.zip",0);
  110. // ZipAdd(hz,"znsimple.bmp", "c:\\simple.bmp");
  111. // ZipAdd(hz,"znsimple.txt", "c:\\simple.txt");
  112. // CloseZip(hz);
  113. //
  114. // (2) Memory use, creating an auto-allocated mem-based zip file from various sources
  115. // HZIP hz = CreateZip(0,100000, 0);
  116. // // adding a conventional file...
  117. // ZipAdd(hz,"src1.txt", "c:\\src1.txt");
  118. // // adding something from memory...
  119. // char buf[1000]; for (int i=0; i<1000; i++) buf[i]=(char)(i&0x7F);
  120. // ZipAdd(hz,"file.dat", buf,1000);
  121. // // adding something from a pipe...
  122. // HANDLE hread,hwrite; CreatePipe(&hread,&hwrite,NULL,0);
  123. // HANDLE hthread = CreateThread(0,0,ThreadFunc,(void*)hwrite,0,0);
  124. // ZipAdd(hz,"unz3.dat", hread,1000); // the '1000' is optional.
  125. // WaitForSingleObject(hthread,INFINITE);
  126. // CloseHandle(hthread); CloseHandle(hread);
  127. // ... meanwhile DWORD WINAPI ThreadFunc(void *dat)
  128. // { HANDLE hwrite = (HANDLE)dat;
  129. // char buf[1000]={17};
  130. // DWORD writ; WriteFile(hwrite,buf,1000,&writ,NULL);
  131. // CloseHandle(hwrite);
  132. // return 0;
  133. // }
  134. // // and now that the zip is created, let's do something with it:
  135. // void *zbuf; unsigned long zlen; ZipGetMemory(hz,&zbuf,&zlen);
  136. // HANDLE hfz = CreateFile("test2.zip",GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
  137. // DWORD writ; WriteFile(hfz,zbuf,zlen,&writ,NULL);
  138. // CloseHandle(hfz);
  139. // CloseZip(hz);
  140. //
  141. // (3) Handle use, for file handles and pipes
  142. // HANDLE hzread,hzwrite; CreatePipe(&hzread,&hzwrite,0,0);
  143. // HANDLE hthread = CreateThread(0,0,ZipReceiverThread,(void*)hzread,0,0);
  144. // HZIP hz = CreateZipHandle(hzwrite,0);
  145. // // ... add to it
  146. // CloseZip(hz);
  147. // CloseHandle(hzwrite);
  148. // WaitForSingleObject(hthread,INFINITE);
  149. // CloseHandle(hthread);
  150. // ... meanwhile DWORD WINAPI ZipReceiverThread(void *dat)
  151. // { HANDLE hread = (HANDLE)dat;
  152. // char buf[1000];
  153. // while (true)
  154. // { DWORD red; ReadFile(hread,buf,1000,&red,NULL);
  155. // // ... and do something with this zip data we're receiving
  156. // if (red==0) break;
  157. // }
  158. // CloseHandle(hread);
  159. // return 0;
  160. // }
  161. // Now we indulge in a little skullduggery so that the code works whether
  162. // the user has included just zip or both zip and unzip.
  163. // Idea: if header files for both zip and unzip are present, then presumably
  164. // the cpp files for zip and unzip are both present, so we will call
  165. // one or the other of them based on a dynamic choice. If the header file
  166. // for only one is present, then we will bind to that particular one.
  167. ZRESULT CloseZipZ(HZIP hz);
  168. unsigned int FormatZipMessageZ(ZRESULT code, char *buf,unsigned int len);
  169. bool IsZipHandleZ(HZIP hz);
  170. #ifdef _unzip_H
  171. #undef CloseZip
  172. #define CloseZip(hz) (IsZipHandleZ(hz)?CloseZipZ(hz):CloseZipU(hz))
  173. #else
  174. #define CloseZip CloseZipZ
  175. #define FormatZipMessage FormatZipMessageZ
  176. #endif
  177. #endif
  178. /*
  179. CString szUserPath="";
  180. szUserPath =strUserPath;
  181. HZIP newZipFile = CreateZip(strZipFileName,0);
  182. CString szFileName="";
  183. szFileName.Format("\\[Content_Types].xml");
  184. ZipAdd(newZipFile, "[Content_Types].xml", szUserPath+szFileName); //将文件添加到zip文件中
  185. ZipAdd(newZipFile, "_rels/", NULL);
  186. szFileName.Format("\\_rels\\.rels");
  187. ZipAdd(newZipFile, "_rels\\.rels", szUserPath+szFileName); //将文件添加到zip文件中
  188. ZipAdd(newZipFile, "docProps/", NULL);
  189. szFileName.Format("\\docProps\\app.xml");
  190. ZipAdd(newZipFile, "docProps\\app.xml", szUserPath+szFileName); //将文件添加到zip文件中
  191. CloseZip(newZipFile); //关闭zip文件
  192. */


END

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/470930
推荐阅读
相关标签
  

闽ICP备14008679号