XZip.cpp 116 KB

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