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