XZip.cpp 108 KB

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