XZip.cpp 118 KB

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