1
0

archive_read_support_format_zip.c 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426
  1. /*-
  2. * Copyright (c) 2004-2013 Tim Kientzle
  3. * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
  4. * Copyright (c) 2013 Konrad Kleine
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
  17. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  18. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  19. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  21. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  25. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "archive_platform.h"
  28. /*
  29. * The definitive documentation of the Zip file format is:
  30. * http://www.pkware.com/documents/casestudies/APPNOTE.TXT
  31. *
  32. * The Info-Zip project has pioneered various extensions to better
  33. * support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
  34. * "Ux", and 0x7875 "ux" extensions for time and ownership
  35. * information.
  36. *
  37. * History of this code: The streaming Zip reader was first added to
  38. * libarchive in January 2005. Support for seekable input sources was
  39. * added in Nov 2011. Zip64 support (including a significant code
  40. * refactoring) was added in 2014.
  41. */
  42. #ifdef HAVE_ERRNO_H
  43. #include <errno.h>
  44. #endif
  45. #ifdef HAVE_STDLIB_H
  46. #include <stdlib.h>
  47. #endif
  48. #ifdef HAVE_ZLIB_H
  49. #include <cm3p/zlib.h>
  50. #endif
  51. #ifdef HAVE_BZLIB_H
  52. #include <cm3p/bzlib.h>
  53. #endif
  54. #ifdef HAVE_LZMA_H
  55. #include <cm3p/lzma.h>
  56. #endif
  57. #ifdef HAVE_ZSTD_H
  58. #include <cm3p/zstd.h>
  59. #endif
  60. #include "archive.h"
  61. #include "archive_digest_private.h"
  62. #include "archive_cryptor_private.h"
  63. #include "archive_endian.h"
  64. #include "archive_entry.h"
  65. #include "archive_entry_locale.h"
  66. #include "archive_hmac_private.h"
  67. #include "archive_private.h"
  68. #include "archive_rb.h"
  69. #include "archive_read_private.h"
  70. #include "archive_ppmd8_private.h"
  71. #ifndef HAVE_ZLIB_H
  72. #include "archive_crc32.h"
  73. #endif
  74. struct zip_entry {
  75. struct archive_rb_node node;
  76. struct zip_entry *next;
  77. int64_t local_header_offset;
  78. int64_t compressed_size;
  79. int64_t uncompressed_size;
  80. int64_t gid;
  81. int64_t uid;
  82. struct archive_string rsrcname;
  83. time_t mtime;
  84. time_t atime;
  85. time_t ctime;
  86. uint32_t crc32;
  87. uint16_t mode;
  88. uint16_t zip_flags; /* From GP Flags Field */
  89. unsigned char compression;
  90. unsigned char system; /* From "version written by" */
  91. unsigned char flags; /* Our extra markers. */
  92. unsigned char decdat;/* Used for Decryption check */
  93. /* WinZip AES encryption extra field should be available
  94. * when compression is 99. */
  95. struct {
  96. /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
  97. unsigned vendor;
  98. #define AES_VENDOR_AE_1 0x0001
  99. #define AES_VENDOR_AE_2 0x0002
  100. /* AES encryption strength:
  101. * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
  102. unsigned strength;
  103. /* Actual compression method. */
  104. unsigned char compression;
  105. } aes_extra;
  106. };
  107. struct trad_enc_ctx {
  108. uint32_t keys[3];
  109. };
  110. /* Bits used in zip_flags. */
  111. #define ZIP_ENCRYPTED (1 << 0)
  112. #define ZIP_LENGTH_AT_END (1 << 3) /* Also called "Streaming bit" */
  113. #define ZIP_STRONG_ENCRYPTED (1 << 6)
  114. #define ZIP_UTF8_NAME (1 << 11)
  115. /* See "7.2 Single Password Symmetric Encryption Method"
  116. in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
  117. #define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
  118. /* Bits used in flags. */
  119. #define LA_USED_ZIP64 (1 << 0)
  120. #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
  121. /*
  122. * See "WinZip - AES Encryption Information"
  123. * http://www.winzip.com/aes_info.htm
  124. */
  125. /* Value used in compression method. */
  126. #define WINZIP_AES_ENCRYPTION 99
  127. /* Authentication code size. */
  128. #define AUTH_CODE_SIZE 10
  129. /**/
  130. #define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
  131. struct zip {
  132. /* Structural information about the archive. */
  133. struct archive_string format_name;
  134. int64_t central_directory_offset;
  135. int64_t central_directory_offset_adjusted;
  136. size_t central_directory_entries_total;
  137. size_t central_directory_entries_on_this_disk;
  138. int has_encrypted_entries;
  139. /* List of entries (seekable Zip only) */
  140. struct zip_entry *zip_entries;
  141. struct archive_rb_tree tree;
  142. struct archive_rb_tree tree_rsrc;
  143. /* Bytes read but not yet consumed via __archive_read_consume() */
  144. size_t unconsumed;
  145. /* Information about entry we're currently reading. */
  146. struct zip_entry *entry;
  147. int64_t entry_bytes_remaining;
  148. /* These count the number of bytes actually read for the entry. */
  149. int64_t entry_compressed_bytes_read;
  150. int64_t entry_uncompressed_bytes_read;
  151. /* Running CRC32 of the decompressed and decrypted data */
  152. unsigned long computed_crc32;
  153. unsigned long (*crc32func)(unsigned long, const void *,
  154. size_t);
  155. char ignore_crc32;
  156. /* Flags to mark progress of decompression. */
  157. char decompress_init;
  158. char end_of_entry;
  159. unsigned char *uncompressed_buffer;
  160. size_t uncompressed_buffer_size;
  161. #ifdef HAVE_ZLIB_H
  162. z_stream stream;
  163. char stream_valid;
  164. #endif
  165. #if HAVE_LZMA_H && HAVE_LIBLZMA
  166. lzma_stream zipx_lzma_stream;
  167. char zipx_lzma_valid;
  168. #endif
  169. #ifdef HAVE_BZLIB_H
  170. bz_stream bzstream;
  171. char bzstream_valid;
  172. #endif
  173. #if HAVE_ZSTD_H && HAVE_LIBZSTD
  174. ZSTD_DStream *zstdstream;
  175. char zstdstream_valid;
  176. #endif
  177. IByteIn zipx_ppmd_stream;
  178. ssize_t zipx_ppmd_read_compressed;
  179. CPpmd8 ppmd8;
  180. char ppmd8_valid;
  181. char ppmd8_stream_failed;
  182. struct archive_string_conv *sconv;
  183. struct archive_string_conv *sconv_default;
  184. struct archive_string_conv *sconv_utf8;
  185. int init_default_conversion;
  186. int process_mac_extensions;
  187. char init_decryption;
  188. /* Decryption buffer. */
  189. /*
  190. * The decrypted data starts at decrypted_ptr and
  191. * extends for decrypted_bytes_remaining. Decryption
  192. * adds new data to the end of this block, data is returned
  193. * to clients from the beginning. When the block hits the
  194. * end of decrypted_buffer, it has to be shuffled back to
  195. * the beginning of the buffer.
  196. */
  197. unsigned char *decrypted_buffer;
  198. unsigned char *decrypted_ptr;
  199. size_t decrypted_buffer_size;
  200. size_t decrypted_bytes_remaining;
  201. size_t decrypted_unconsumed_bytes;
  202. /* Traditional PKWARE decryption. */
  203. struct trad_enc_ctx tctx;
  204. char tctx_valid;
  205. /* WinZip AES decryption. */
  206. /* Contexts used for AES decryption. */
  207. archive_crypto_ctx cctx;
  208. char cctx_valid;
  209. archive_hmac_sha1_ctx hctx;
  210. char hctx_valid;
  211. /* Strong encryption's decryption header information. */
  212. unsigned iv_size;
  213. unsigned alg_id;
  214. unsigned bit_len;
  215. unsigned flags;
  216. unsigned erd_size;
  217. unsigned v_size;
  218. unsigned v_crc32;
  219. uint8_t *iv;
  220. uint8_t *erd;
  221. uint8_t *v_data;
  222. };
  223. /* Many systems define min or MIN, but not all. */
  224. #define zipmin(a,b) ((a) < (b) ? (a) : (b))
  225. #ifdef HAVE_ZLIB_H
  226. static int
  227. zip_read_data_deflate(struct archive_read *a, const void **buff,
  228. size_t *size, int64_t *offset);
  229. #endif
  230. #if HAVE_LZMA_H && HAVE_LIBLZMA
  231. static int
  232. zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
  233. size_t *size, int64_t *offset);
  234. #endif
  235. /* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8
  236. * streams inside ZIP files. It has 2 purposes: one is to fetch the next
  237. * compressed byte from the stream, second one is to increase the counter how
  238. * many compressed bytes were read. */
  239. static Byte
  240. ppmd_read(void* p) {
  241. /* Get the handle to current decompression context. */
  242. struct archive_read *a = ((IByteIn*)p)->a;
  243. struct zip *zip = (struct zip*) a->format->data;
  244. ssize_t bytes_avail = 0;
  245. /* Fetch next byte. */
  246. const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail);
  247. if(bytes_avail < 1) {
  248. zip->ppmd8_stream_failed = 1;
  249. return 0;
  250. }
  251. __archive_read_consume(a, 1);
  252. /* Increment the counter. */
  253. ++zip->zipx_ppmd_read_compressed;
  254. /* Return the next compressed byte. */
  255. return data[0];
  256. }
  257. /* ------------------------------------------------------------------------ */
  258. /*
  259. Traditional PKWARE Decryption functions.
  260. */
  261. static void
  262. trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
  263. {
  264. uint8_t t;
  265. #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
  266. ctx->keys[0] = CRC32(ctx->keys[0], c);
  267. ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
  268. t = (ctx->keys[1] >> 24) & 0xff;
  269. ctx->keys[2] = CRC32(ctx->keys[2], t);
  270. #undef CRC32
  271. }
  272. static uint8_t
  273. trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
  274. {
  275. unsigned temp = ctx->keys[2] | 2;
  276. return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
  277. }
  278. static void
  279. trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
  280. size_t in_len, uint8_t *out, size_t out_len)
  281. {
  282. unsigned i, max;
  283. max = (unsigned)((in_len < out_len)? in_len: out_len);
  284. for (i = 0; i < max; i++) {
  285. uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
  286. out[i] = t;
  287. trad_enc_update_keys(ctx, t);
  288. }
  289. }
  290. static int
  291. trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
  292. const uint8_t *key, size_t key_len, uint8_t *crcchk)
  293. {
  294. uint8_t header[12];
  295. if (key_len < 12) {
  296. *crcchk = 0xff;
  297. return -1;
  298. }
  299. ctx->keys[0] = 305419896L;
  300. ctx->keys[1] = 591751049L;
  301. ctx->keys[2] = 878082192L;
  302. for (;pw_len; --pw_len)
  303. trad_enc_update_keys(ctx, *pw++);
  304. trad_enc_decrypt_update(ctx, key, 12, header, 12);
  305. /* Return the last byte for CRC check. */
  306. *crcchk = header[11];
  307. return 0;
  308. }
  309. #if 0
  310. static void
  311. crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
  312. int key_size)
  313. {
  314. #define MD_SIZE 20
  315. archive_sha1_ctx ctx;
  316. unsigned char md1[MD_SIZE];
  317. unsigned char md2[MD_SIZE * 2];
  318. unsigned char mkb[64];
  319. int i;
  320. archive_sha1_init(&ctx);
  321. archive_sha1_update(&ctx, p, size);
  322. archive_sha1_final(&ctx, md1);
  323. memset(mkb, 0x36, sizeof(mkb));
  324. for (i = 0; i < MD_SIZE; i++)
  325. mkb[i] ^= md1[i];
  326. archive_sha1_init(&ctx);
  327. archive_sha1_update(&ctx, mkb, sizeof(mkb));
  328. archive_sha1_final(&ctx, md2);
  329. memset(mkb, 0x5C, sizeof(mkb));
  330. for (i = 0; i < MD_SIZE; i++)
  331. mkb[i] ^= md1[i];
  332. archive_sha1_init(&ctx);
  333. archive_sha1_update(&ctx, mkb, sizeof(mkb));
  334. archive_sha1_final(&ctx, md2 + MD_SIZE);
  335. if (key_size > 32)
  336. key_size = 32;
  337. memcpy(key, md2, key_size);
  338. #undef MD_SIZE
  339. }
  340. #endif
  341. /*
  342. * Common code for streaming or seeking modes.
  343. *
  344. * Includes code to read local file headers, decompress data
  345. * from entry bodies, and common API.
  346. */
  347. static unsigned long
  348. real_crc32(unsigned long crc, const void *buff, size_t len)
  349. {
  350. return crc32(crc, buff, (unsigned int)len);
  351. }
  352. /* Used by "ignorecrc32" option to speed up tests. */
  353. static unsigned long
  354. fake_crc32(unsigned long crc, const void *buff, size_t len)
  355. {
  356. (void)crc; /* UNUSED */
  357. (void)buff; /* UNUSED */
  358. (void)len; /* UNUSED */
  359. return 0;
  360. }
  361. static const struct {
  362. int id;
  363. const char * name;
  364. } compression_methods[] = {
  365. {0, "uncompressed"}, /* The file is stored (no compression) */
  366. {1, "shrinking"}, /* The file is Shrunk */
  367. {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
  368. {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
  369. {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
  370. {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
  371. {6, "imploded"}, /* The file is Imploded */
  372. {7, "reserved"}, /* Reserved for Tokenizing compression algorithm */
  373. {8, "deflation"}, /* The file is Deflated */
  374. {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
  375. {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
  376. * (old IBM TERSE) */
  377. {11, "reserved"}, /* Reserved by PKWARE */
  378. {12, "bzip"}, /* File is compressed using BZIP2 algorithm */
  379. {13, "reserved"}, /* Reserved by PKWARE */
  380. {14, "lzma"}, /* LZMA (EFS) */
  381. {15, "reserved"}, /* Reserved by PKWARE */
  382. {16, "reserved"}, /* Reserved by PKWARE */
  383. {17, "reserved"}, /* Reserved by PKWARE */
  384. {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
  385. {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
  386. {93, "zstd"}, /* Zstandard (zstd) Compression */
  387. {95, "xz"}, /* XZ compressed data */
  388. {96, "jpeg"}, /* JPEG compressed data */
  389. {97, "wav-pack"}, /* WavPack compressed data */
  390. {98, "ppmd-1"}, /* PPMd version I, Rev 1 */
  391. {99, "aes"} /* WinZip AES encryption */
  392. };
  393. static const char *
  394. compression_name(const int compression)
  395. {
  396. static const int num_compression_methods =
  397. sizeof(compression_methods)/sizeof(compression_methods[0]);
  398. int i=0;
  399. while(compression >= 0 && i < num_compression_methods) {
  400. if (compression_methods[i].id == compression)
  401. return compression_methods[i].name;
  402. i++;
  403. }
  404. return "??";
  405. }
  406. /* Convert an MSDOS-style date/time into Unix-style time. */
  407. static time_t
  408. zip_time(const char *p)
  409. {
  410. int msTime, msDate;
  411. struct tm ts;
  412. msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
  413. msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
  414. memset(&ts, 0, sizeof(ts));
  415. ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
  416. ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
  417. ts.tm_mday = msDate & 0x1f; /* Day of month. */
  418. ts.tm_hour = (msTime >> 11) & 0x1f;
  419. ts.tm_min = (msTime >> 5) & 0x3f;
  420. ts.tm_sec = (msTime << 1) & 0x3e;
  421. ts.tm_isdst = -1;
  422. return mktime(&ts);
  423. }
  424. /*
  425. * The extra data is stored as a list of
  426. * id1+size1+data1 + id2+size2+data2 ...
  427. * triplets. id and size are 2 bytes each.
  428. */
  429. static int
  430. process_extra(struct archive_read *a, struct archive_entry *entry,
  431. const char *p, size_t extra_length, struct zip_entry* zip_entry)
  432. {
  433. unsigned offset = 0;
  434. struct zip *zip = (struct zip *)(a->format->data);
  435. if (extra_length == 0) {
  436. return ARCHIVE_OK;
  437. }
  438. if (extra_length < 4) {
  439. size_t i = 0;
  440. /* Some ZIP files may have trailing 0 bytes. Let's check they
  441. * are all 0 and ignore them instead of returning an error.
  442. *
  443. * This is not technically correct, but some ZIP files look
  444. * like this and other tools support those files - so let's
  445. * also support them.
  446. */
  447. for (; i < extra_length; i++) {
  448. if (p[i] != 0) {
  449. archive_set_error(&a->archive,
  450. ARCHIVE_ERRNO_FILE_FORMAT,
  451. "Too-small extra data: "
  452. "Need at least 4 bytes, "
  453. "but only found %d bytes",
  454. (int)extra_length);
  455. return ARCHIVE_FAILED;
  456. }
  457. }
  458. return ARCHIVE_OK;
  459. }
  460. while (offset <= extra_length - 4) {
  461. unsigned short headerid = archive_le16dec(p + offset);
  462. unsigned short datasize = archive_le16dec(p + offset + 2);
  463. offset += 4;
  464. if (offset + datasize > extra_length) {
  465. archive_set_error(&a->archive,
  466. ARCHIVE_ERRNO_FILE_FORMAT, "Extra data overflow: "
  467. "Need %d bytes but only found %d bytes",
  468. (int)datasize, (int)(extra_length - offset));
  469. return ARCHIVE_FAILED;
  470. }
  471. #ifdef DEBUG
  472. fprintf(stderr, "Header id 0x%04x, length %d\n",
  473. headerid, datasize);
  474. #endif
  475. switch (headerid) {
  476. case 0x0001:
  477. /* Zip64 extended information extra field. */
  478. zip_entry->flags |= LA_USED_ZIP64;
  479. if (zip_entry->uncompressed_size == 0xffffffff) {
  480. uint64_t t = 0;
  481. if (datasize < 8
  482. || (t = archive_le64dec(p + offset)) >
  483. INT64_MAX) {
  484. archive_set_error(&a->archive,
  485. ARCHIVE_ERRNO_FILE_FORMAT,
  486. "Malformed 64-bit "
  487. "uncompressed size");
  488. return ARCHIVE_FAILED;
  489. }
  490. zip_entry->uncompressed_size = t;
  491. offset += 8;
  492. datasize -= 8;
  493. }
  494. if (zip_entry->compressed_size == 0xffffffff) {
  495. uint64_t t = 0;
  496. if (datasize < 8
  497. || (t = archive_le64dec(p + offset)) >
  498. INT64_MAX) {
  499. archive_set_error(&a->archive,
  500. ARCHIVE_ERRNO_FILE_FORMAT,
  501. "Malformed 64-bit "
  502. "compressed size");
  503. return ARCHIVE_FAILED;
  504. }
  505. zip_entry->compressed_size = t;
  506. offset += 8;
  507. datasize -= 8;
  508. }
  509. if (zip_entry->local_header_offset == 0xffffffff) {
  510. uint64_t t = 0;
  511. if (datasize < 8
  512. || (t = archive_le64dec(p + offset)) >
  513. INT64_MAX) {
  514. archive_set_error(&a->archive,
  515. ARCHIVE_ERRNO_FILE_FORMAT,
  516. "Malformed 64-bit "
  517. "local header offset");
  518. return ARCHIVE_FAILED;
  519. }
  520. zip_entry->local_header_offset = t;
  521. offset += 8;
  522. datasize -= 8;
  523. }
  524. /* archive_le32dec(p + offset) gives disk
  525. * on which file starts, but we don't handle
  526. * multi-volume Zip files. */
  527. break;
  528. #ifdef DEBUG
  529. case 0x0017:
  530. {
  531. /* Strong encryption field. */
  532. if (archive_le16dec(p + offset) == 2) {
  533. unsigned algId =
  534. archive_le16dec(p + offset + 2);
  535. unsigned bitLen =
  536. archive_le16dec(p + offset + 4);
  537. int flags =
  538. archive_le16dec(p + offset + 6);
  539. fprintf(stderr, "algId=0x%04x, bitLen=%u, "
  540. "flgas=%d\n", algId, bitLen,flags);
  541. }
  542. break;
  543. }
  544. #endif
  545. case 0x5455:
  546. {
  547. /* Extended time field "UT". */
  548. int flags;
  549. if (datasize == 0) {
  550. archive_set_error(&a->archive,
  551. ARCHIVE_ERRNO_FILE_FORMAT,
  552. "Incomplete extended time field");
  553. return ARCHIVE_FAILED;
  554. }
  555. flags = p[offset];
  556. offset++;
  557. datasize--;
  558. /* Flag bits indicate which dates are present. */
  559. if (flags & 0x01)
  560. {
  561. #ifdef DEBUG
  562. fprintf(stderr, "mtime: %lld -> %d\n",
  563. (long long)zip_entry->mtime,
  564. archive_le32dec(p + offset));
  565. #endif
  566. if (datasize < 4)
  567. break;
  568. zip_entry->mtime = archive_le32dec(p + offset);
  569. offset += 4;
  570. datasize -= 4;
  571. }
  572. if (flags & 0x02)
  573. {
  574. if (datasize < 4)
  575. break;
  576. zip_entry->atime = archive_le32dec(p + offset);
  577. offset += 4;
  578. datasize -= 4;
  579. }
  580. if (flags & 0x04)
  581. {
  582. if (datasize < 4)
  583. break;
  584. zip_entry->ctime = archive_le32dec(p + offset);
  585. offset += 4;
  586. datasize -= 4;
  587. }
  588. break;
  589. }
  590. case 0x5855:
  591. {
  592. /* Info-ZIP Unix Extra Field (old version) "UX". */
  593. if (datasize >= 8) {
  594. zip_entry->atime = archive_le32dec(p + offset);
  595. zip_entry->mtime =
  596. archive_le32dec(p + offset + 4);
  597. }
  598. if (datasize >= 12) {
  599. zip_entry->uid =
  600. archive_le16dec(p + offset + 8);
  601. zip_entry->gid =
  602. archive_le16dec(p + offset + 10);
  603. }
  604. break;
  605. }
  606. case 0x6c78:
  607. {
  608. /* Experimental 'xl' field */
  609. /*
  610. * Introduced Dec 2013 to provide a way to
  611. * include external file attributes (and other
  612. * fields that ordinarily appear only in
  613. * central directory) in local file header.
  614. * This provides file type and permission
  615. * information necessary to support full
  616. * streaming extraction. Currently being
  617. * discussed with other Zip developers
  618. * ... subject to change.
  619. *
  620. * Format:
  621. * The field starts with a bitmap that specifies
  622. * which additional fields are included. The
  623. * bitmap is variable length and can be extended in
  624. * the future.
  625. *
  626. * n bytes - feature bitmap: first byte has low-order
  627. * 7 bits. If high-order bit is set, a subsequent
  628. * byte holds the next 7 bits, etc.
  629. *
  630. * if bitmap & 1, 2 byte "version made by"
  631. * if bitmap & 2, 2 byte "internal file attributes"
  632. * if bitmap & 4, 4 byte "external file attributes"
  633. * if bitmap & 8, 2 byte comment length + n byte
  634. * comment
  635. */
  636. int bitmap, bitmap_last;
  637. if (datasize < 1)
  638. break;
  639. bitmap_last = bitmap = 0xff & p[offset];
  640. offset += 1;
  641. datasize -= 1;
  642. /* We only support first 7 bits of bitmap; skip rest. */
  643. while ((bitmap_last & 0x80) != 0
  644. && datasize >= 1) {
  645. bitmap_last = p[offset];
  646. offset += 1;
  647. datasize -= 1;
  648. }
  649. if (bitmap & 1) {
  650. /* 2 byte "version made by" */
  651. if (datasize < 2)
  652. break;
  653. zip_entry->system
  654. = archive_le16dec(p + offset) >> 8;
  655. offset += 2;
  656. datasize -= 2;
  657. }
  658. if (bitmap & 2) {
  659. /* 2 byte "internal file attributes" */
  660. uint32_t internal_attributes;
  661. if (datasize < 2)
  662. break;
  663. internal_attributes
  664. = archive_le16dec(p + offset);
  665. /* Not used by libarchive at present. */
  666. (void)internal_attributes; /* UNUSED */
  667. offset += 2;
  668. datasize -= 2;
  669. }
  670. if (bitmap & 4) {
  671. /* 4 byte "external file attributes" */
  672. uint32_t external_attributes;
  673. if (datasize < 4)
  674. break;
  675. external_attributes
  676. = archive_le32dec(p + offset);
  677. if (zip_entry->system == 3) {
  678. zip_entry->mode
  679. = external_attributes >> 16;
  680. } else if (zip_entry->system == 0) {
  681. // Interpret MSDOS directory bit
  682. if (0x10 == (external_attributes &
  683. 0x10)) {
  684. zip_entry->mode =
  685. AE_IFDIR | 0775;
  686. } else {
  687. zip_entry->mode =
  688. AE_IFREG | 0664;
  689. }
  690. if (0x01 == (external_attributes &
  691. 0x01)) {
  692. /* Read-only bit;
  693. * strip write permissions */
  694. zip_entry->mode &= 0555;
  695. }
  696. } else {
  697. zip_entry->mode = 0;
  698. }
  699. offset += 4;
  700. datasize -= 4;
  701. }
  702. if (bitmap & 8) {
  703. /* 2 byte comment length + comment */
  704. uint32_t comment_length;
  705. if (datasize < 2)
  706. break;
  707. comment_length
  708. = archive_le16dec(p + offset);
  709. offset += 2;
  710. datasize -= 2;
  711. if (datasize < comment_length)
  712. break;
  713. /* Comment is not supported by libarchive */
  714. offset += comment_length;
  715. datasize -= comment_length;
  716. }
  717. break;
  718. }
  719. case 0x7075:
  720. {
  721. /* Info-ZIP Unicode Path Extra Field. */
  722. if (datasize < 5 || entry == NULL)
  723. break;
  724. offset += 5;
  725. datasize -= 5;
  726. /* The path name in this field is always encoded
  727. * in UTF-8. */
  728. if (zip->sconv_utf8 == NULL) {
  729. zip->sconv_utf8 =
  730. archive_string_conversion_from_charset(
  731. &a->archive, "UTF-8", 1);
  732. /* If the converter from UTF-8 is not
  733. * available, then the path name from the main
  734. * field will more likely be correct. */
  735. if (zip->sconv_utf8 == NULL)
  736. break;
  737. }
  738. /* Make sure the CRC32 of the filename matches. */
  739. if (!zip->ignore_crc32) {
  740. const char *cp = archive_entry_pathname(entry);
  741. if (cp) {
  742. unsigned long file_crc =
  743. zip->crc32func(0, cp, strlen(cp));
  744. unsigned long utf_crc =
  745. archive_le32dec(p + offset - 4);
  746. if (file_crc != utf_crc) {
  747. #ifdef DEBUG
  748. fprintf(stderr,
  749. "CRC filename mismatch; "
  750. "CDE is %lx, but UTF8 "
  751. "is outdated with %lx\n",
  752. file_crc, utf_crc);
  753. #endif
  754. break;
  755. }
  756. }
  757. }
  758. if (archive_entry_copy_pathname_l(entry,
  759. p + offset, datasize, zip->sconv_utf8) != 0) {
  760. /* Ignore the error, and fallback to the path
  761. * name from the main field. */
  762. #ifdef DEBUG
  763. fprintf(stderr, "Failed to read the ZIP "
  764. "0x7075 extra field path.\n");
  765. #endif
  766. }
  767. break;
  768. }
  769. case 0x7855:
  770. /* Info-ZIP Unix Extra Field (type 2) "Ux". */
  771. #ifdef DEBUG
  772. fprintf(stderr, "uid %d gid %d\n",
  773. archive_le16dec(p + offset),
  774. archive_le16dec(p + offset + 2));
  775. #endif
  776. if (datasize >= 2)
  777. zip_entry->uid = archive_le16dec(p + offset);
  778. if (datasize >= 4)
  779. zip_entry->gid =
  780. archive_le16dec(p + offset + 2);
  781. break;
  782. case 0x7875:
  783. {
  784. /* Info-Zip Unix Extra Field (type 3) "ux". */
  785. int uidsize = 0, gidsize = 0;
  786. /* TODO: support arbitrary uidsize/gidsize. */
  787. if (datasize >= 1 && p[offset] == 1) {/* version=1 */
  788. if (datasize >= 4) {
  789. /* get a uid size. */
  790. uidsize = 0xff & (int)p[offset+1];
  791. if (uidsize == 2)
  792. zip_entry->uid =
  793. archive_le16dec(
  794. p + offset + 2);
  795. else if (uidsize == 4 && datasize >= 6)
  796. zip_entry->uid =
  797. archive_le32dec(
  798. p + offset + 2);
  799. }
  800. if (datasize >= (2 + uidsize + 3)) {
  801. /* get a gid size. */
  802. gidsize = 0xff &
  803. (int)p[offset+2+uidsize];
  804. if (gidsize == 2)
  805. zip_entry->gid =
  806. archive_le16dec(
  807. p+offset+2+uidsize+1);
  808. else if (gidsize == 4 &&
  809. datasize >= (2 + uidsize + 5))
  810. zip_entry->gid =
  811. archive_le32dec(
  812. p+offset+2+uidsize+1);
  813. }
  814. }
  815. break;
  816. }
  817. case 0x9901:
  818. /* WinZip AES extra data field. */
  819. if (datasize < 6) {
  820. archive_set_error(&a->archive,
  821. ARCHIVE_ERRNO_FILE_FORMAT,
  822. "Incomplete AES field");
  823. return ARCHIVE_FAILED;
  824. }
  825. if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
  826. /* Vendor version. */
  827. zip_entry->aes_extra.vendor =
  828. archive_le16dec(p + offset);
  829. /* AES encryption strength. */
  830. zip_entry->aes_extra.strength = p[offset + 4];
  831. /* Actual compression method. */
  832. zip_entry->aes_extra.compression =
  833. p[offset + 5];
  834. }
  835. break;
  836. default:
  837. break;
  838. }
  839. offset += datasize;
  840. }
  841. return ARCHIVE_OK;
  842. }
  843. /*
  844. * Assumes file pointer is at beginning of local file header.
  845. */
  846. static int
  847. zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
  848. struct zip *zip)
  849. {
  850. const char *p;
  851. const void *h;
  852. const wchar_t *wp;
  853. const char *cp;
  854. size_t len, filename_length, extra_length;
  855. struct archive_string_conv *sconv;
  856. struct zip_entry *zip_entry = zip->entry;
  857. struct zip_entry zip_entry_central_dir;
  858. int ret = ARCHIVE_OK;
  859. char version;
  860. /* Save a copy of the original for consistency checks. */
  861. zip_entry_central_dir = *zip_entry;
  862. zip->decompress_init = 0;
  863. zip->end_of_entry = 0;
  864. zip->entry_uncompressed_bytes_read = 0;
  865. zip->entry_compressed_bytes_read = 0;
  866. zip->computed_crc32 = zip->crc32func(0, NULL, 0);
  867. /* Setup default conversion. */
  868. if (zip->sconv == NULL && !zip->init_default_conversion) {
  869. zip->sconv_default =
  870. archive_string_default_conversion_for_read(&(a->archive));
  871. zip->init_default_conversion = 1;
  872. }
  873. if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
  874. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  875. "Truncated ZIP file header");
  876. return (ARCHIVE_FATAL);
  877. }
  878. if (memcmp(p, "PK\003\004", 4) != 0) {
  879. archive_set_error(&a->archive, -1, "Damaged Zip archive");
  880. return ARCHIVE_FATAL;
  881. }
  882. version = p[4];
  883. zip_entry->system = p[5];
  884. zip_entry->zip_flags = archive_le16dec(p + 6);
  885. if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
  886. zip->has_encrypted_entries = 1;
  887. archive_entry_set_is_data_encrypted(entry, 1);
  888. if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
  889. zip_entry->zip_flags & ZIP_ENCRYPTED &&
  890. zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
  891. archive_entry_set_is_metadata_encrypted(entry, 1);
  892. return ARCHIVE_FATAL;
  893. }
  894. }
  895. zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
  896. zip_entry->compression = (char)archive_le16dec(p + 8);
  897. zip_entry->mtime = zip_time(p + 10);
  898. zip_entry->crc32 = archive_le32dec(p + 14);
  899. if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
  900. zip_entry->decdat = p[11];
  901. else
  902. zip_entry->decdat = p[17];
  903. zip_entry->compressed_size = archive_le32dec(p + 18);
  904. zip_entry->uncompressed_size = archive_le32dec(p + 22);
  905. filename_length = archive_le16dec(p + 26);
  906. extra_length = archive_le16dec(p + 28);
  907. __archive_read_consume(a, 30);
  908. /* Read the filename. */
  909. if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
  910. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  911. "Truncated ZIP file header");
  912. return (ARCHIVE_FATAL);
  913. }
  914. if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
  915. /* The filename is stored to be UTF-8. */
  916. if (zip->sconv_utf8 == NULL) {
  917. zip->sconv_utf8 =
  918. archive_string_conversion_from_charset(
  919. &a->archive, "UTF-8", 1);
  920. if (zip->sconv_utf8 == NULL)
  921. return (ARCHIVE_FATAL);
  922. }
  923. sconv = zip->sconv_utf8;
  924. } else if (zip->sconv != NULL)
  925. sconv = zip->sconv;
  926. else
  927. sconv = zip->sconv_default;
  928. if (archive_entry_copy_pathname_l(entry,
  929. h, filename_length, sconv) != 0) {
  930. if (errno == ENOMEM) {
  931. archive_set_error(&a->archive, ENOMEM,
  932. "Can't allocate memory for Pathname");
  933. return (ARCHIVE_FATAL);
  934. }
  935. archive_set_error(&a->archive,
  936. ARCHIVE_ERRNO_FILE_FORMAT,
  937. "Pathname cannot be converted "
  938. "from %s to current locale.",
  939. archive_string_conversion_charset_name(sconv));
  940. ret = ARCHIVE_WARN;
  941. }
  942. __archive_read_consume(a, filename_length);
  943. /* Read the extra data. */
  944. if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
  945. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  946. "Truncated ZIP file header");
  947. return (ARCHIVE_FATAL);
  948. }
  949. if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
  950. zip_entry)) {
  951. return ARCHIVE_FATAL;
  952. }
  953. __archive_read_consume(a, extra_length);
  954. /* Work around a bug in Info-Zip: When reading from a pipe, it
  955. * stats the pipe instead of synthesizing a file entry. */
  956. if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
  957. zip_entry->mode &= ~ AE_IFMT;
  958. zip_entry->mode |= AE_IFREG;
  959. }
  960. /* If the mode is totally empty, set some sane default. */
  961. if (zip_entry->mode == 0) {
  962. zip_entry->mode |= 0664;
  963. }
  964. /* Windows archivers sometimes use backslash as the directory
  965. * separator. Normalize to slash. */
  966. if (zip_entry->system == 0 &&
  967. (wp = archive_entry_pathname_w(entry)) != NULL) {
  968. if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
  969. size_t i;
  970. struct archive_wstring s;
  971. archive_string_init(&s);
  972. archive_wstrcpy(&s, wp);
  973. for (i = 0; i < archive_strlen(&s); i++) {
  974. if (s.s[i] == '\\')
  975. s.s[i] = '/';
  976. }
  977. archive_entry_copy_pathname_w(entry, s.s);
  978. archive_wstring_free(&s);
  979. }
  980. }
  981. /* Make sure that entries with a trailing '/' are marked as directories
  982. * even if the External File Attributes contains bogus values. If this
  983. * is not a directory and there is no type, assume a regular file. */
  984. if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
  985. int has_slash;
  986. wp = archive_entry_pathname_w(entry);
  987. if (wp != NULL) {
  988. len = wcslen(wp);
  989. has_slash = len > 0 && wp[len - 1] == L'/';
  990. } else {
  991. cp = archive_entry_pathname(entry);
  992. len = (cp != NULL)?strlen(cp):0;
  993. has_slash = len > 0 && cp[len - 1] == '/';
  994. }
  995. /* Correct file type as needed. */
  996. if (has_slash) {
  997. zip_entry->mode &= ~AE_IFMT;
  998. zip_entry->mode |= AE_IFDIR;
  999. zip_entry->mode |= 0111;
  1000. } else if ((zip_entry->mode & AE_IFMT) == 0) {
  1001. zip_entry->mode |= AE_IFREG;
  1002. }
  1003. }
  1004. /* Make sure directories end in '/' */
  1005. if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
  1006. wp = archive_entry_pathname_w(entry);
  1007. if (wp != NULL) {
  1008. len = wcslen(wp);
  1009. if (len > 0 && wp[len - 1] != L'/') {
  1010. struct archive_wstring s;
  1011. archive_string_init(&s);
  1012. archive_wstrcat(&s, wp);
  1013. archive_wstrappend_wchar(&s, L'/');
  1014. archive_entry_copy_pathname_w(entry, s.s);
  1015. archive_wstring_free(&s);
  1016. }
  1017. } else {
  1018. cp = archive_entry_pathname(entry);
  1019. len = (cp != NULL)?strlen(cp):0;
  1020. if (len > 0 && cp[len - 1] != '/') {
  1021. struct archive_string s;
  1022. archive_string_init(&s);
  1023. archive_strcat(&s, cp);
  1024. archive_strappend_char(&s, '/');
  1025. archive_entry_set_pathname(entry, s.s);
  1026. archive_string_free(&s);
  1027. }
  1028. }
  1029. }
  1030. if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
  1031. /* If this came from the central dir, its size info
  1032. * is definitive, so ignore the length-at-end flag. */
  1033. zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
  1034. /* If local header is missing a value, use the one from
  1035. the central directory. If both have it, warn about
  1036. mismatches. */
  1037. if (zip_entry->crc32 == 0) {
  1038. zip_entry->crc32 = zip_entry_central_dir.crc32;
  1039. } else if (!zip->ignore_crc32
  1040. && zip_entry->crc32 != zip_entry_central_dir.crc32) {
  1041. archive_set_error(&a->archive,
  1042. ARCHIVE_ERRNO_FILE_FORMAT,
  1043. "Inconsistent CRC32 values");
  1044. ret = ARCHIVE_WARN;
  1045. }
  1046. if (zip_entry->compressed_size == 0
  1047. || zip_entry->compressed_size == 0xffffffff) {
  1048. zip_entry->compressed_size
  1049. = zip_entry_central_dir.compressed_size;
  1050. } else if (zip_entry->compressed_size
  1051. != zip_entry_central_dir.compressed_size) {
  1052. archive_set_error(&a->archive,
  1053. ARCHIVE_ERRNO_FILE_FORMAT,
  1054. "Inconsistent compressed size: "
  1055. "%jd in central directory, %jd in local header",
  1056. (intmax_t)zip_entry_central_dir.compressed_size,
  1057. (intmax_t)zip_entry->compressed_size);
  1058. ret = ARCHIVE_WARN;
  1059. }
  1060. if (zip_entry->uncompressed_size == 0 ||
  1061. zip_entry->uncompressed_size == 0xffffffff) {
  1062. zip_entry->uncompressed_size
  1063. = zip_entry_central_dir.uncompressed_size;
  1064. } else if (zip_entry->uncompressed_size
  1065. != zip_entry_central_dir.uncompressed_size) {
  1066. archive_set_error(&a->archive,
  1067. ARCHIVE_ERRNO_FILE_FORMAT,
  1068. "Inconsistent uncompressed size: "
  1069. "%jd in central directory, %jd in local header",
  1070. (intmax_t)zip_entry_central_dir.uncompressed_size,
  1071. (intmax_t)zip_entry->uncompressed_size);
  1072. ret = ARCHIVE_WARN;
  1073. }
  1074. }
  1075. /* Populate some additional entry fields: */
  1076. archive_entry_set_mode(entry, zip_entry->mode);
  1077. archive_entry_set_uid(entry, zip_entry->uid);
  1078. archive_entry_set_gid(entry, zip_entry->gid);
  1079. archive_entry_set_mtime(entry, zip_entry->mtime, 0);
  1080. archive_entry_set_ctime(entry, zip_entry->ctime, 0);
  1081. archive_entry_set_atime(entry, zip_entry->atime, 0);
  1082. if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
  1083. size_t linkname_length;
  1084. if (zip_entry->compressed_size > 64 * 1024) {
  1085. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1086. "Zip file with oversized link entry");
  1087. return ARCHIVE_FATAL;
  1088. }
  1089. linkname_length = (size_t)zip_entry->compressed_size;
  1090. archive_entry_set_size(entry, 0);
  1091. // take into account link compression if any
  1092. size_t linkname_full_length = linkname_length;
  1093. if (zip->entry->compression != 0)
  1094. {
  1095. // symlink target string appeared to be compressed
  1096. int status = ARCHIVE_FATAL;
  1097. const void *uncompressed_buffer = NULL;
  1098. switch (zip->entry->compression)
  1099. {
  1100. #if HAVE_ZLIB_H
  1101. case 8: /* Deflate compression. */
  1102. zip->entry_bytes_remaining = zip_entry->compressed_size;
  1103. status = zip_read_data_deflate(a, &uncompressed_buffer,
  1104. &linkname_full_length, NULL);
  1105. break;
  1106. #endif
  1107. #if HAVE_LZMA_H && HAVE_LIBLZMA
  1108. case 14: /* ZIPx LZMA compression. */
  1109. /*(see zip file format specification, section 4.4.5)*/
  1110. zip->entry_bytes_remaining = zip_entry->compressed_size;
  1111. status = zip_read_data_zipx_lzma_alone(a, &uncompressed_buffer,
  1112. &linkname_full_length, NULL);
  1113. break;
  1114. #endif
  1115. default: /* Unsupported compression. */
  1116. break;
  1117. }
  1118. if (status == ARCHIVE_OK)
  1119. {
  1120. p = uncompressed_buffer;
  1121. }
  1122. else
  1123. {
  1124. archive_set_error(&a->archive,
  1125. ARCHIVE_ERRNO_FILE_FORMAT,
  1126. "Unsupported ZIP compression method "
  1127. "during decompression of link entry (%d: %s)",
  1128. zip->entry->compression,
  1129. compression_name(zip->entry->compression));
  1130. return ARCHIVE_FAILED;
  1131. }
  1132. }
  1133. else
  1134. {
  1135. p = __archive_read_ahead(a, linkname_length, NULL);
  1136. }
  1137. if (p == NULL) {
  1138. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1139. "Truncated Zip file");
  1140. return ARCHIVE_FATAL;
  1141. }
  1142. sconv = zip->sconv;
  1143. if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
  1144. sconv = zip->sconv_utf8;
  1145. if (sconv == NULL)
  1146. sconv = zip->sconv_default;
  1147. if (archive_entry_copy_symlink_l(entry, p, linkname_full_length,
  1148. sconv) != 0) {
  1149. if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
  1150. (zip->entry->zip_flags & ZIP_UTF8_NAME))
  1151. archive_entry_copy_symlink_l(entry, p,
  1152. linkname_full_length, NULL);
  1153. if (errno == ENOMEM) {
  1154. archive_set_error(&a->archive, ENOMEM,
  1155. "Can't allocate memory for Symlink");
  1156. return (ARCHIVE_FATAL);
  1157. }
  1158. /*
  1159. * Since there is no character-set regulation for
  1160. * symlink name, do not report the conversion error
  1161. * in an automatic conversion.
  1162. */
  1163. if (sconv != zip->sconv_utf8 ||
  1164. (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
  1165. archive_set_error(&a->archive,
  1166. ARCHIVE_ERRNO_FILE_FORMAT,
  1167. "Symlink cannot be converted "
  1168. "from %s to current locale.",
  1169. archive_string_conversion_charset_name(
  1170. sconv));
  1171. ret = ARCHIVE_WARN;
  1172. }
  1173. }
  1174. zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
  1175. if (__archive_read_consume(a, linkname_length) < 0) {
  1176. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1177. "Read error skipping symlink target name");
  1178. return ARCHIVE_FATAL;
  1179. }
  1180. } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
  1181. || (zip_entry->uncompressed_size > 0
  1182. && zip_entry->uncompressed_size != 0xffffffff)) {
  1183. /* Set the size only if it's meaningful. */
  1184. archive_entry_set_size(entry, zip_entry->uncompressed_size);
  1185. }
  1186. zip->entry_bytes_remaining = zip_entry->compressed_size;
  1187. /* If there's no body, force read_data() to return EOF immediately. */
  1188. if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
  1189. && zip->entry_bytes_remaining < 1)
  1190. zip->end_of_entry = 1;
  1191. /* Set up a more descriptive format name. */
  1192. archive_string_empty(&zip->format_name);
  1193. archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
  1194. version / 10, version % 10,
  1195. compression_name(zip->entry->compression));
  1196. a->archive.archive_format_name = zip->format_name.s;
  1197. return (ret);
  1198. }
  1199. static int
  1200. check_authentication_code(struct archive_read *a, const void *_p)
  1201. {
  1202. struct zip *zip = (struct zip *)(a->format->data);
  1203. /* Check authentication code. */
  1204. if (zip->hctx_valid) {
  1205. const void *p;
  1206. uint8_t hmac[20];
  1207. size_t hmac_len = 20;
  1208. int cmp;
  1209. archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
  1210. if (_p == NULL) {
  1211. /* Read authentication code. */
  1212. p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
  1213. if (p == NULL) {
  1214. archive_set_error(&a->archive,
  1215. ARCHIVE_ERRNO_FILE_FORMAT,
  1216. "Truncated ZIP file data");
  1217. return (ARCHIVE_FATAL);
  1218. }
  1219. } else {
  1220. p = _p;
  1221. }
  1222. cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
  1223. __archive_read_consume(a, AUTH_CODE_SIZE);
  1224. if (cmp != 0) {
  1225. archive_set_error(&a->archive,
  1226. ARCHIVE_ERRNO_MISC,
  1227. "ZIP bad Authentication code");
  1228. return (ARCHIVE_WARN);
  1229. }
  1230. }
  1231. return (ARCHIVE_OK);
  1232. }
  1233. /*
  1234. * The Zip end-of-file marker is inherently ambiguous. The specification
  1235. * in APPNOTE.TXT allows any of four possible formats, and there is no
  1236. * guaranteed-correct way for a reader to know a priori which one the writer
  1237. * will have used. The four formats are:
  1238. * 1. 32-bit format with an initial PK78 marker
  1239. * 2. 32-bit format without that marker
  1240. * 3. 64-bit format with the marker
  1241. * 4. 64-bit format without the marker
  1242. *
  1243. * Mark Adler's `sunzip` streaming unzip program solved this ambiguity
  1244. * by just looking at every possible combination and accepting the
  1245. * longest one that matches the expected values. His approach always
  1246. * consumes the longest possible matching EOF marker, based on an
  1247. * analysis of all the possible failures and how the values could
  1248. * overlap.
  1249. *
  1250. * For example, suppose both of the first two formats listed
  1251. * above match. In that case, we know the next four
  1252. * 32-bit words match this pattern:
  1253. * ```
  1254. * [PK\07\08] [CRC32] [compressed size] [uncompressed size]
  1255. * ```
  1256. * but we know they must also match this pattern:
  1257. * ```
  1258. * [CRC32] [compressed size] [uncompressed size] [other PK marker]
  1259. * ```
  1260. *
  1261. * Since the first word here matches both the PK78 signature in the
  1262. * first form and the CRC32 in the second, we know those two values
  1263. * are equal, the CRC32 must be exactly 0x08074b50. Similarly, the
  1264. * compressed and uncompressed size must also be exactly this value.
  1265. * So we know these four words are all 0x08074b50. If we were to
  1266. * accept the shorter pattern, it would be immediately followed by
  1267. * another PK78 marker, which is not possible in a well-formed ZIP
  1268. * archive unless there is garbage between entries. This implies we
  1269. * should not accept the shorter form in such a case; we should accept
  1270. * the longer form.
  1271. *
  1272. * If the second and third possibilities above both match, we
  1273. * have a slightly different situation. The following words
  1274. * must match both the 32-bit format
  1275. * ```
  1276. * [CRC32] [compressed size] [uncompressed size] [other PK marker]
  1277. * ```
  1278. * and the 64-bit format
  1279. * ```
  1280. * [CRC32] [compressed low] [compressed high] [uncompressed low] [uncompressed high] [other PK marker]
  1281. * ```
  1282. * Since the 32-bit and 64-bit compressed sizes both match, the
  1283. * actual size must fit in 32 bits, which implies the high-order
  1284. * word of the compressed size is zero. So we know the uncompressed
  1285. * low word is zero, which again implies that if we accept the shorter
  1286. * format, there will not be a valid PK marker following it.
  1287. *
  1288. * Similar considerations rule out the shorter form in every other
  1289. * possibly-ambiguous pair. So if two of the four possible formats
  1290. * match, we should accept the longer option.
  1291. *
  1292. * If none of the four formats matches, we know the archive must be
  1293. * corrupted in some fashion. In particular, it's possible that the
  1294. * length-at-end bit was incorrect and we should not really be looking
  1295. * for an EOF marker at all. To allow for this possibility, we
  1296. * evaluate the following words to collect data for a later error
  1297. * report but do not consume any bytes. We instead rely on the later
  1298. * search for a new PK marker to re-sync to the next well-formed
  1299. * entry.
  1300. */
  1301. static void
  1302. consume_end_of_file_marker(struct archive_read *a, struct zip *zip)
  1303. {
  1304. const char *marker;
  1305. const char *p;
  1306. uint64_t compressed32, uncompressed32;
  1307. uint64_t compressed64, uncompressed64;
  1308. uint64_t compressed_actual, uncompressed_actual;
  1309. uint32_t crc32_actual;
  1310. const uint32_t PK78 = 0x08074B50ULL;
  1311. uint8_t crc32_ignored, crc32_may_be_zero;
  1312. /* If there shouldn't be a marker, don't consume it. */
  1313. if ((zip->entry->zip_flags & ZIP_LENGTH_AT_END) == 0) {
  1314. return;
  1315. }
  1316. /* The longest Zip end-of-file record is 24 bytes. Since an
  1317. * end-of-file record can never appear at the end of the
  1318. * archive, we know 24 bytes will be available unless
  1319. * the archive is severely truncated. */
  1320. if (NULL == (marker = __archive_read_ahead(a, 24, NULL))) {
  1321. return;
  1322. }
  1323. p = marker;
  1324. /* The end-of-file record comprises:
  1325. * = Optional PK\007\010 marker
  1326. * = 4-byte CRC32
  1327. * = Compressed size
  1328. * = Uncompressed size
  1329. *
  1330. * The last two fields are either both 32 bits or both 64
  1331. * bits. We check all possible layouts and accept any one
  1332. * that gives us a complete match, else we make a best-effort
  1333. * attempt to parse out the pieces.
  1334. */
  1335. /* CRC32 checking can be tricky:
  1336. * * Test suites sometimes ignore the CRC32
  1337. * * AES AE-2 always writes zero for the CRC32
  1338. * * AES AE-1 sometimes writes zero for the CRC32
  1339. */
  1340. crc32_ignored = zip->ignore_crc32;
  1341. crc32_may_be_zero = 0;
  1342. crc32_actual = zip->computed_crc32;
  1343. if (zip->hctx_valid) {
  1344. switch (zip->entry->aes_extra.vendor) {
  1345. case AES_VENDOR_AE_2:
  1346. crc32_actual = 0;
  1347. break;
  1348. case AES_VENDOR_AE_1:
  1349. default:
  1350. crc32_may_be_zero = 1;
  1351. break;
  1352. }
  1353. }
  1354. /* Values computed from the actual data in the archive. */
  1355. compressed_actual = (uint64_t)zip->entry_compressed_bytes_read;
  1356. uncompressed_actual = (uint64_t)zip->entry_uncompressed_bytes_read;
  1357. /* Longest: PK78 marker, all 64-bit fields (24 bytes total) */
  1358. if (archive_le32dec(p) == PK78
  1359. && ((archive_le32dec(p + 4) == crc32_actual)
  1360. || (crc32_may_be_zero && (archive_le32dec(p + 4) == 0))
  1361. || crc32_ignored)
  1362. && (archive_le64dec(p + 8) == compressed_actual)
  1363. && (archive_le64dec(p + 16) == uncompressed_actual)) {
  1364. if (!crc32_ignored) {
  1365. zip->entry->crc32 = crc32_actual;
  1366. }
  1367. zip->entry->compressed_size = compressed_actual;
  1368. zip->entry->uncompressed_size = uncompressed_actual;
  1369. zip->unconsumed += 24;
  1370. return;
  1371. }
  1372. /* No PK78 marker, 64-bit fields (20 bytes total) */
  1373. if (((archive_le32dec(p) == crc32_actual)
  1374. || (crc32_may_be_zero && (archive_le32dec(p + 4) == 0))
  1375. || crc32_ignored)
  1376. && (archive_le64dec(p + 4) == compressed_actual)
  1377. && (archive_le64dec(p + 12) == uncompressed_actual)) {
  1378. if (!crc32_ignored) {
  1379. zip->entry->crc32 = crc32_actual;
  1380. }
  1381. zip->entry->compressed_size = compressed_actual;
  1382. zip->entry->uncompressed_size = uncompressed_actual;
  1383. zip->unconsumed += 20;
  1384. return;
  1385. }
  1386. /* PK78 marker and 32-bit fields (16 bytes total) */
  1387. if (archive_le32dec(p) == PK78
  1388. && ((archive_le32dec(p + 4) == crc32_actual)
  1389. || (crc32_may_be_zero && (archive_le32dec(p + 4) == 0))
  1390. || crc32_ignored)
  1391. && (archive_le32dec(p + 8) == compressed_actual)
  1392. && (archive_le32dec(p + 12) == uncompressed_actual)) {
  1393. if (!crc32_ignored) {
  1394. zip->entry->crc32 = crc32_actual;
  1395. }
  1396. zip->entry->compressed_size = compressed_actual;
  1397. zip->entry->uncompressed_size = uncompressed_actual;
  1398. zip->unconsumed += 16;
  1399. return;
  1400. }
  1401. /* Shortest: No PK78 marker, all 32-bit fields (12 bytes total) */
  1402. if (((archive_le32dec(p) == crc32_actual)
  1403. || (crc32_may_be_zero && (archive_le32dec(p + 4) == 0))
  1404. || crc32_ignored)
  1405. && (archive_le32dec(p + 4) == compressed_actual)
  1406. && (archive_le32dec(p + 8) == uncompressed_actual)) {
  1407. if (!crc32_ignored) {
  1408. zip->entry->crc32 = crc32_actual;
  1409. }
  1410. zip->entry->compressed_size = compressed_actual;
  1411. zip->entry->uncompressed_size = uncompressed_actual;
  1412. zip->unconsumed += 12;
  1413. return;
  1414. }
  1415. /* If none of the above patterns gives us a full exact match,
  1416. * then there's something definitely amiss. The fallback code
  1417. * below will parse out some plausible values for error
  1418. * reporting purposes. Note that this won't actually
  1419. * consume anything:
  1420. *
  1421. * = If there really is a marker here, the logic to resync to
  1422. * the next entry will suffice to skip it.
  1423. *
  1424. * = There might not really be a marker: Corruption or bugs
  1425. * may have set the length-at-end bit without a marker ever
  1426. * having actually been written. In this case, we
  1427. * explicitly should not consume any bytes, since that would
  1428. * prevent us from correctly reading the next entry.
  1429. */
  1430. if (archive_le32dec(p) == PK78) {
  1431. p += 4; /* Ignore PK78 if it appears to be present */
  1432. }
  1433. zip->entry->crc32 = archive_le32dec(p); /* Parse CRC32 */
  1434. p += 4;
  1435. /* Consider both 32- and 64-bit interpretations */
  1436. compressed32 = archive_le32dec(p);
  1437. uncompressed32 = archive_le32dec(p + 4);
  1438. compressed64 = archive_le64dec(p);
  1439. uncompressed64 = archive_le64dec(p + 8);
  1440. /* The earlier patterns may have failed because of CRC32
  1441. * mismatch, so it's still possible that both sizes match.
  1442. * Try to match as many as we can...
  1443. */
  1444. if (compressed32 == compressed_actual
  1445. && uncompressed32 == uncompressed_actual) {
  1446. /* Both 32-bit fields match */
  1447. zip->entry->compressed_size = compressed32;
  1448. zip->entry->uncompressed_size = uncompressed32;
  1449. } else if (compressed64 == compressed_actual
  1450. || uncompressed64 == uncompressed_actual) {
  1451. /* One or both 64-bit fields match */
  1452. zip->entry->compressed_size = compressed64;
  1453. zip->entry->uncompressed_size = uncompressed64;
  1454. } else {
  1455. /* Zero or one 32-bit fields match */
  1456. zip->entry->compressed_size = compressed32;
  1457. zip->entry->uncompressed_size = uncompressed32;
  1458. }
  1459. }
  1460. /*
  1461. * Read "uncompressed" data.
  1462. *
  1463. * This is straightforward if we know the size of the data. This is
  1464. * always true for the seeking reader (we've examined the Central
  1465. * Directory already), and will often be true for the streaming reader
  1466. * (the writer was writing uncompressed so probably knows the size).
  1467. *
  1468. * If we don't know the size, then life is more interesting. Note
  1469. * that a careful reading of the Zip specification says that a writer
  1470. * must use ZIP_LENGTH_AT_END if it cannot write the CRC into the
  1471. * local header. And if it uses ZIP_LENGTH_AT_END, then it is
  1472. * prohibited from storing the sizes in the local header. This
  1473. * prevents fully-compliant streaming writers from providing any size
  1474. * clues to a streaming reader. In this case, we have to scan the
  1475. * data as we read to try to locate the end-of-file marker.
  1476. *
  1477. * We assume here that the end-of-file marker always has the
  1478. * PK\007\010 signature. Although it's technically optional, newer
  1479. * writers seem to provide it pretty consistently, and it's not clear
  1480. * how to efficiently recognize an end-of-file marker that lacks it.
  1481. *
  1482. * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
  1483. * zip->end_of_entry if it consumes all of the data.
  1484. */
  1485. static int
  1486. zip_read_data_none(struct archive_read *a, const void **_buff,
  1487. size_t *size, int64_t *offset)
  1488. {
  1489. struct zip *zip;
  1490. const char *buff;
  1491. ssize_t bytes_avail;
  1492. ssize_t trailing_extra;
  1493. int r;
  1494. (void)offset; /* UNUSED */
  1495. zip = (struct zip *)(a->format->data);
  1496. trailing_extra = zip->hctx_valid ? AUTH_CODE_SIZE : 0;
  1497. if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
  1498. const char *p;
  1499. ssize_t grabbing_bytes = 24 + trailing_extra;
  1500. /* Grab at least 24 bytes. */
  1501. buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
  1502. if (bytes_avail < grabbing_bytes) {
  1503. /* Zip archives have end-of-archive markers
  1504. that are longer than this, so a failure to get at
  1505. least 24 bytes really does indicate a truncated
  1506. file. */
  1507. archive_set_error(&a->archive,
  1508. ARCHIVE_ERRNO_FILE_FORMAT,
  1509. "Truncated ZIP file data");
  1510. return (ARCHIVE_FATAL);
  1511. }
  1512. /* Check for a complete PK\007\010 signature, followed
  1513. * by the correct 4-byte CRC. */
  1514. p = buff + trailing_extra;
  1515. if (p[0] == 'P' && p[1] == 'K'
  1516. && p[2] == '\007' && p[3] == '\010'
  1517. && (archive_le32dec(p + 4) == zip->computed_crc32
  1518. || zip->ignore_crc32
  1519. || (zip->hctx_valid
  1520. && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
  1521. zip->end_of_entry = 1;
  1522. if (zip->hctx_valid) {
  1523. r = check_authentication_code(a, buff);
  1524. if (r != ARCHIVE_OK)
  1525. return (r);
  1526. }
  1527. return (ARCHIVE_OK);
  1528. }
  1529. /* If not at EOF, ensure we consume at least one byte. */
  1530. ++p;
  1531. /* Scan forward until we see where a PK\007\010 signature
  1532. * might be. */
  1533. /* Return bytes up until that point. On the next call,
  1534. * the code above will verify the data descriptor. */
  1535. while (p < buff + bytes_avail - 4) {
  1536. if (p[3] == 'P') { p += 3; }
  1537. else if (p[3] == 'K') { p += 2; }
  1538. else if (p[3] == '\007') { p += 1; }
  1539. else if (p[3] == '\010' && p[2] == '\007'
  1540. && p[1] == 'K' && p[0] == 'P') {
  1541. break;
  1542. } else { p += 4; }
  1543. }
  1544. p -= trailing_extra;
  1545. bytes_avail = p - buff;
  1546. } else {
  1547. if (zip->entry_bytes_remaining == 0) {
  1548. zip->end_of_entry = 1;
  1549. if (zip->hctx_valid) {
  1550. r = check_authentication_code(a, NULL);
  1551. if (r != ARCHIVE_OK)
  1552. return (r);
  1553. }
  1554. return (ARCHIVE_OK);
  1555. }
  1556. /* Grab a bunch of bytes. */
  1557. buff = __archive_read_ahead(a, 1, &bytes_avail);
  1558. if (bytes_avail <= 0) {
  1559. archive_set_error(&a->archive,
  1560. ARCHIVE_ERRNO_FILE_FORMAT,
  1561. "Truncated ZIP file data");
  1562. return (ARCHIVE_FATAL);
  1563. }
  1564. if (bytes_avail > zip->entry_bytes_remaining)
  1565. bytes_avail = (ssize_t)zip->entry_bytes_remaining;
  1566. }
  1567. if (zip->tctx_valid || zip->cctx_valid) {
  1568. size_t dec_size = bytes_avail;
  1569. if (dec_size > zip->decrypted_buffer_size)
  1570. dec_size = zip->decrypted_buffer_size;
  1571. if (zip->tctx_valid) {
  1572. trad_enc_decrypt_update(&zip->tctx,
  1573. (const uint8_t *)buff, dec_size,
  1574. zip->decrypted_buffer, dec_size);
  1575. } else {
  1576. size_t dsize = dec_size;
  1577. archive_hmac_sha1_update(&zip->hctx,
  1578. (const uint8_t *)buff, dec_size);
  1579. archive_decrypto_aes_ctr_update(&zip->cctx,
  1580. (const uint8_t *)buff, dec_size,
  1581. zip->decrypted_buffer, &dsize);
  1582. }
  1583. bytes_avail = dec_size;
  1584. buff = (const char *)zip->decrypted_buffer;
  1585. }
  1586. zip->entry_bytes_remaining -= bytes_avail;
  1587. zip->entry_uncompressed_bytes_read += bytes_avail;
  1588. zip->entry_compressed_bytes_read += bytes_avail;
  1589. zip->unconsumed += bytes_avail;
  1590. *size = bytes_avail;
  1591. *_buff = buff;
  1592. return (ARCHIVE_OK);
  1593. }
  1594. #if HAVE_LZMA_H && HAVE_LIBLZMA
  1595. static int
  1596. zipx_xz_init(struct archive_read *a, struct zip *zip)
  1597. {
  1598. lzma_ret r;
  1599. if(zip->zipx_lzma_valid) {
  1600. lzma_end(&zip->zipx_lzma_stream);
  1601. zip->zipx_lzma_valid = 0;
  1602. }
  1603. memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
  1604. r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
  1605. if (r != LZMA_OK) {
  1606. archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
  1607. "xz initialization failed(%d)",
  1608. r);
  1609. return (ARCHIVE_FAILED);
  1610. }
  1611. zip->zipx_lzma_valid = 1;
  1612. free(zip->uncompressed_buffer);
  1613. zip->uncompressed_buffer_size = 256 * 1024;
  1614. zip->uncompressed_buffer = malloc(zip->uncompressed_buffer_size);
  1615. if (zip->uncompressed_buffer == NULL) {
  1616. archive_set_error(&a->archive, ENOMEM,
  1617. "No memory for xz decompression");
  1618. return (ARCHIVE_FATAL);
  1619. }
  1620. zip->decompress_init = 1;
  1621. return (ARCHIVE_OK);
  1622. }
  1623. static int
  1624. zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
  1625. {
  1626. lzma_ret r;
  1627. const uint8_t* p;
  1628. #pragma pack(push)
  1629. #pragma pack(1)
  1630. struct _alone_header {
  1631. uint8_t bytes[5];
  1632. uint64_t uncompressed_size;
  1633. } alone_header;
  1634. #pragma pack(pop)
  1635. if(zip->zipx_lzma_valid) {
  1636. lzma_end(&zip->zipx_lzma_stream);
  1637. zip->zipx_lzma_valid = 0;
  1638. }
  1639. /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
  1640. * that is a part of XZ Utils. The stream format stored inside ZIPX
  1641. * file is a modified "lzma alone" file format, that was used by the
  1642. * `lzma` utility which was later deprecated in favour of `xz` utility.
  1643. * Since those formats are nearly the same, we can use a standard
  1644. * "lzma alone" decoder from XZ Utils. */
  1645. memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
  1646. r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
  1647. if (r != LZMA_OK) {
  1648. archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
  1649. "lzma initialization failed(%d)", r);
  1650. return (ARCHIVE_FAILED);
  1651. }
  1652. /* Flag the cleanup function that we want our lzma-related structures
  1653. * to be freed later. */
  1654. zip->zipx_lzma_valid = 1;
  1655. /* The "lzma alone" file format and the stream format inside ZIPx are
  1656. * almost the same. Here's an example of a structure of "lzma alone"
  1657. * format:
  1658. *
  1659. * $ cat /bin/ls | lzma | xxd | head -n 1
  1660. * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
  1661. *
  1662. * 5 bytes 8 bytes n bytes
  1663. * <lzma_params><uncompressed_size><data...>
  1664. *
  1665. * lzma_params is a 5-byte blob that has to be decoded to extract
  1666. * parameters of this LZMA stream. The uncompressed_size field is an
  1667. * uint64_t value that contains information about the size of the
  1668. * uncompressed file, or UINT64_MAX if this value is unknown.
  1669. * The <data...> part is the actual lzma-compressed data stream.
  1670. *
  1671. * Now here's the structure of the stream inside the ZIPX file:
  1672. *
  1673. * $ cat stream_inside_zipx | xxd | head -n 1
  1674. * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
  1675. *
  1676. * 2byte 2byte 5 bytes n bytes
  1677. * <magic1><magic2><lzma_params><data...>
  1678. *
  1679. * This means that the ZIPX file contains an additional magic1 and
  1680. * magic2 headers, the lzma_params field contains the same parameter
  1681. * set as in the "lzma alone" format, and the <data...> field is the
  1682. * same as in the "lzma alone" format as well. Note that also the zipx
  1683. * format is missing the uncompressed_size field.
  1684. *
  1685. * So, in order to use the "lzma alone" decoder for the zipx lzma
  1686. * stream, we simply need to shuffle around some fields, prepare a new
  1687. * lzma alone header, feed it into lzma alone decoder so it will
  1688. * initialize itself properly, and then we can start feeding normal
  1689. * zipx lzma stream into the decoder.
  1690. */
  1691. /* Read magic1,magic2,lzma_params from the ZIPX stream. */
  1692. if(zip->entry_bytes_remaining < 9 || (p = __archive_read_ahead(a, 9, NULL)) == NULL) {
  1693. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1694. "Truncated lzma data");
  1695. return (ARCHIVE_FATAL);
  1696. }
  1697. if(p[2] != 0x05 || p[3] != 0x00) {
  1698. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1699. "Invalid lzma data");
  1700. return (ARCHIVE_FATAL);
  1701. }
  1702. /* Prepare an lzma alone header: copy the lzma_params blob into
  1703. * a proper place into the lzma alone header. */
  1704. memcpy(&alone_header.bytes[0], p + 4, 5);
  1705. /* Initialize the 'uncompressed size' field to unknown; we'll manually
  1706. * monitor how many bytes there are still to be uncompressed. */
  1707. alone_header.uncompressed_size = UINT64_MAX;
  1708. if(!zip->uncompressed_buffer) {
  1709. zip->uncompressed_buffer_size = 256 * 1024;
  1710. zip->uncompressed_buffer = malloc(zip->uncompressed_buffer_size);
  1711. if (zip->uncompressed_buffer == NULL) {
  1712. archive_set_error(&a->archive, ENOMEM,
  1713. "No memory for lzma decompression");
  1714. return (ARCHIVE_FATAL);
  1715. }
  1716. }
  1717. zip->zipx_lzma_stream.next_in = (void*) &alone_header;
  1718. zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
  1719. zip->zipx_lzma_stream.total_in = 0;
  1720. zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
  1721. zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
  1722. zip->zipx_lzma_stream.total_out = 0;
  1723. /* Feed only the header into the lzma alone decoder. This will
  1724. * effectively initialize the decoder, and will not produce any
  1725. * output bytes yet. */
  1726. r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
  1727. if (r != LZMA_OK) {
  1728. archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
  1729. "lzma stream initialization error");
  1730. return ARCHIVE_FATAL;
  1731. }
  1732. /* We've already consumed some bytes, so take this into account. */
  1733. __archive_read_consume(a, 9);
  1734. zip->entry_bytes_remaining -= 9;
  1735. zip->entry_compressed_bytes_read += 9;
  1736. zip->decompress_init = 1;
  1737. return (ARCHIVE_OK);
  1738. }
  1739. static int
  1740. zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
  1741. size_t *size, int64_t *offset)
  1742. {
  1743. struct zip* zip = (struct zip *)(a->format->data);
  1744. int ret;
  1745. lzma_ret lz_ret;
  1746. const void* compressed_buf;
  1747. ssize_t bytes_avail, in_bytes, to_consume = 0;
  1748. (void) offset; /* UNUSED */
  1749. /* Initialize decompressor if not yet initialized. */
  1750. if (!zip->decompress_init) {
  1751. ret = zipx_xz_init(a, zip);
  1752. if (ret != ARCHIVE_OK)
  1753. return (ret);
  1754. }
  1755. compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
  1756. if (bytes_avail < 0) {
  1757. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1758. "Truncated xz file body");
  1759. return (ARCHIVE_FATAL);
  1760. }
  1761. in_bytes = (ssize_t)zipmin(zip->entry_bytes_remaining, bytes_avail);
  1762. zip->zipx_lzma_stream.next_in = compressed_buf;
  1763. zip->zipx_lzma_stream.avail_in = in_bytes;
  1764. zip->zipx_lzma_stream.total_in = 0;
  1765. zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
  1766. zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
  1767. zip->zipx_lzma_stream.total_out = 0;
  1768. /* Perform the decompression. */
  1769. lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
  1770. switch(lz_ret) {
  1771. case LZMA_DATA_ERROR:
  1772. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1773. "xz data error (error %d)", (int) lz_ret);
  1774. return (ARCHIVE_FATAL);
  1775. case LZMA_NO_CHECK:
  1776. case LZMA_OK:
  1777. break;
  1778. default:
  1779. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1780. "xz unknown error %d", (int) lz_ret);
  1781. return (ARCHIVE_FATAL);
  1782. case LZMA_STREAM_END:
  1783. lzma_end(&zip->zipx_lzma_stream);
  1784. zip->zipx_lzma_valid = 0;
  1785. if((int64_t) zip->zipx_lzma_stream.total_in !=
  1786. zip->entry_bytes_remaining)
  1787. {
  1788. archive_set_error(&a->archive,
  1789. ARCHIVE_ERRNO_MISC,
  1790. "xz premature end of stream");
  1791. return (ARCHIVE_FATAL);
  1792. }
  1793. zip->end_of_entry = 1;
  1794. break;
  1795. }
  1796. to_consume = (ssize_t)zip->zipx_lzma_stream.total_in;
  1797. __archive_read_consume(a, to_consume);
  1798. zip->entry_bytes_remaining -= to_consume;
  1799. zip->entry_compressed_bytes_read += to_consume;
  1800. zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
  1801. *size = (size_t)zip->zipx_lzma_stream.total_out;
  1802. *buff = zip->uncompressed_buffer;
  1803. return (ARCHIVE_OK);
  1804. }
  1805. static int
  1806. zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
  1807. size_t *size, int64_t *offset)
  1808. {
  1809. struct zip* zip = (struct zip *)(a->format->data);
  1810. int ret;
  1811. lzma_ret lz_ret;
  1812. const void* compressed_buf;
  1813. ssize_t bytes_avail, in_bytes, to_consume;
  1814. (void) offset; /* UNUSED */
  1815. /* Initialize decompressor if not yet initialized. */
  1816. if (!zip->decompress_init) {
  1817. ret = zipx_lzma_alone_init(a, zip);
  1818. if (ret != ARCHIVE_OK)
  1819. return (ret);
  1820. }
  1821. /* Fetch more compressed data. The same note as in deflate handler
  1822. * applies here as well:
  1823. *
  1824. * Note: '1' here is a performance optimization. Recall that the
  1825. * decompression layer returns a count of available bytes; asking for
  1826. * more than that forces the decompressor to combine reads by copying
  1827. * data.
  1828. */
  1829. compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
  1830. if (bytes_avail < 0) {
  1831. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1832. "Truncated lzma file body");
  1833. return (ARCHIVE_FATAL);
  1834. }
  1835. /* Set decompressor parameters. */
  1836. in_bytes = (ssize_t)zipmin(zip->entry_bytes_remaining, bytes_avail);
  1837. zip->zipx_lzma_stream.next_in = compressed_buf;
  1838. zip->zipx_lzma_stream.avail_in = in_bytes;
  1839. zip->zipx_lzma_stream.total_in = 0;
  1840. zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
  1841. zip->zipx_lzma_stream.avail_out =
  1842. /* These lzma_alone streams lack end of stream marker, so let's
  1843. * make sure the unpacker won't try to unpack more than it's
  1844. * supposed to. */
  1845. (size_t)zipmin((int64_t) zip->uncompressed_buffer_size,
  1846. zip->entry->uncompressed_size -
  1847. zip->entry_uncompressed_bytes_read);
  1848. zip->zipx_lzma_stream.total_out = 0;
  1849. /* Perform the decompression. */
  1850. lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
  1851. switch(lz_ret) {
  1852. case LZMA_DATA_ERROR:
  1853. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1854. "lzma data error (error %d)", (int) lz_ret);
  1855. return (ARCHIVE_FATAL);
  1856. /* This case is optional in lzma alone format. It can happen,
  1857. * but most of the files don't have it. (GitHub #1257) */
  1858. case LZMA_STREAM_END:
  1859. if((int64_t) zip->zipx_lzma_stream.total_in !=
  1860. zip->entry_bytes_remaining)
  1861. {
  1862. archive_set_error(&a->archive,
  1863. ARCHIVE_ERRNO_MISC,
  1864. "lzma alone premature end of stream");
  1865. return (ARCHIVE_FATAL);
  1866. }
  1867. zip->end_of_entry = 1;
  1868. break;
  1869. case LZMA_OK:
  1870. break;
  1871. default:
  1872. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  1873. "lzma unknown error %d", (int) lz_ret);
  1874. return (ARCHIVE_FATAL);
  1875. }
  1876. to_consume = (ssize_t)zip->zipx_lzma_stream.total_in;
  1877. /* Update pointers. */
  1878. __archive_read_consume(a, to_consume);
  1879. zip->entry_bytes_remaining -= to_consume;
  1880. zip->entry_compressed_bytes_read += to_consume;
  1881. zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
  1882. if(zip->entry_bytes_remaining == 0) {
  1883. zip->end_of_entry = 1;
  1884. }
  1885. /* Free lzma decoder handle because we'll no longer need it. */
  1886. /* This cannot be folded into LZMA_STREAM_END handling above
  1887. * because the stream end marker is not required in this format. */
  1888. if(zip->end_of_entry) {
  1889. lzma_end(&zip->zipx_lzma_stream);
  1890. zip->zipx_lzma_valid = 0;
  1891. }
  1892. /* Return values. */
  1893. *size = (size_t)zip->zipx_lzma_stream.total_out;
  1894. *buff = zip->uncompressed_buffer;
  1895. /* If we're here, then we're good! */
  1896. return (ARCHIVE_OK);
  1897. }
  1898. #endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
  1899. static int
  1900. zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
  1901. {
  1902. const void* p;
  1903. uint32_t val;
  1904. uint32_t order;
  1905. uint32_t mem;
  1906. uint32_t restore_method;
  1907. /* Remove previous decompression context if it exists. */
  1908. if(zip->ppmd8_valid) {
  1909. __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
  1910. zip->ppmd8_valid = 0;
  1911. }
  1912. /* Create a new decompression context. */
  1913. __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
  1914. zip->ppmd8_stream_failed = 0;
  1915. /* Setup function pointers required by Ppmd8 decompressor. The
  1916. * 'ppmd_read' function will feed new bytes to the decompressor,
  1917. * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
  1918. zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
  1919. zip->zipx_ppmd_stream.a = a;
  1920. zip->zipx_ppmd_stream.Read = &ppmd_read;
  1921. /* Reset number of read bytes to 0. */
  1922. zip->zipx_ppmd_read_compressed = 0;
  1923. /* Read Ppmd8 header (2 bytes). */
  1924. p = __archive_read_ahead(a, 2, NULL);
  1925. if(!p) {
  1926. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1927. "Truncated file data in PPMd8 stream");
  1928. return (ARCHIVE_FATAL);
  1929. }
  1930. __archive_read_consume(a, 2);
  1931. /* Decode the stream's compression parameters. */
  1932. val = archive_le16dec(p);
  1933. order = (val & 15) + 1;
  1934. mem = ((val >> 4) & 0xff) + 1;
  1935. restore_method = (val >> 12);
  1936. if(order < 2 || restore_method > 2) {
  1937. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1938. "Invalid parameter set in PPMd8 stream (order=%" PRIu32 ", "
  1939. "restore=%" PRIu32 ")", order, restore_method);
  1940. return (ARCHIVE_FAILED);
  1941. }
  1942. /* Allocate the memory needed to properly decompress the file. */
  1943. if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
  1944. archive_set_error(&a->archive, ENOMEM,
  1945. "Unable to allocate memory for PPMd8 stream: %" PRIu32 " bytes",
  1946. mem << 20);
  1947. return (ARCHIVE_FATAL);
  1948. }
  1949. /* Signal the cleanup function to release Ppmd8 context in the
  1950. * cleanup phase. */
  1951. zip->ppmd8_valid = 1;
  1952. /* Perform further Ppmd8 initialization. */
  1953. if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
  1954. archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
  1955. "PPMd8 stream range decoder initialization error");
  1956. return (ARCHIVE_FATAL);
  1957. }
  1958. __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
  1959. restore_method);
  1960. /* Allocate the buffer that will hold uncompressed data. */
  1961. free(zip->uncompressed_buffer);
  1962. zip->uncompressed_buffer_size = 256 * 1024;
  1963. zip->uncompressed_buffer = malloc(zip->uncompressed_buffer_size);
  1964. if(zip->uncompressed_buffer == NULL) {
  1965. archive_set_error(&a->archive, ENOMEM,
  1966. "No memory for PPMd8 decompression");
  1967. return ARCHIVE_FATAL;
  1968. }
  1969. /* Ppmd8 initialization is done. */
  1970. zip->decompress_init = 1;
  1971. /* We've already read 2 bytes in the output stream. Additionally,
  1972. * Ppmd8 initialization code could read some data as well. So we
  1973. * are advancing the stream by 2 bytes plus whatever number of
  1974. * bytes Ppmd8 init function used. */
  1975. zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
  1976. return ARCHIVE_OK;
  1977. }
  1978. static int
  1979. zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
  1980. size_t *size, int64_t *offset)
  1981. {
  1982. struct zip* zip = (struct zip *)(a->format->data);
  1983. int ret;
  1984. size_t consumed_bytes = 0;
  1985. ssize_t bytes_avail = 0;
  1986. (void) offset; /* UNUSED */
  1987. /* If we're here for the first time, initialize Ppmd8 decompression
  1988. * context first. */
  1989. if(!zip->decompress_init) {
  1990. ret = zipx_ppmd8_init(a, zip);
  1991. if(ret != ARCHIVE_OK)
  1992. return ret;
  1993. }
  1994. /* Fetch for more data. We're reading 1 byte here, but libarchive
  1995. * should prefetch more bytes. */
  1996. (void) __archive_read_ahead(a, 1, &bytes_avail);
  1997. if(bytes_avail < 0) {
  1998. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  1999. "Truncated PPMd8 file body");
  2000. return (ARCHIVE_FATAL);
  2001. }
  2002. /* This counter will be updated inside ppmd_read(), which at one
  2003. * point will be called by Ppmd8_DecodeSymbol. */
  2004. zip->zipx_ppmd_read_compressed = 0;
  2005. /* Decompression loop. */
  2006. do {
  2007. int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
  2008. &zip->ppmd8);
  2009. if(sym < 0) {
  2010. zip->end_of_entry = 1;
  2011. break;
  2012. }
  2013. /* This field is set by ppmd_read() when there was no more data
  2014. * to be read. */
  2015. if(zip->ppmd8_stream_failed) {
  2016. archive_set_error(&a->archive,
  2017. ARCHIVE_ERRNO_FILE_FORMAT,
  2018. "Truncated PPMd8 file body");
  2019. return (ARCHIVE_FATAL);
  2020. }
  2021. zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
  2022. ++consumed_bytes;
  2023. } while(consumed_bytes < zip->uncompressed_buffer_size);
  2024. /* Update pointers so we can continue decompression in another call. */
  2025. zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
  2026. zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
  2027. zip->entry_uncompressed_bytes_read += consumed_bytes;
  2028. /* If we're at the end of stream, deinitialize Ppmd8 context. */
  2029. if(zip->end_of_entry) {
  2030. __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
  2031. zip->ppmd8_valid = 0;
  2032. }
  2033. /* Update pointers for libarchive. */
  2034. *buff = zip->uncompressed_buffer;
  2035. *size = consumed_bytes;
  2036. return ARCHIVE_OK;
  2037. }
  2038. #ifdef HAVE_BZLIB_H
  2039. static int
  2040. zipx_bzip2_init(struct archive_read *a, struct zip *zip)
  2041. {
  2042. int r;
  2043. /* Deallocate already existing BZ2 decompression context if it
  2044. * exists. */
  2045. if(zip->bzstream_valid) {
  2046. BZ2_bzDecompressEnd(&zip->bzstream);
  2047. zip->bzstream_valid = 0;
  2048. }
  2049. /* Allocate a new BZ2 decompression context. */
  2050. memset(&zip->bzstream, 0, sizeof(bz_stream));
  2051. r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
  2052. if(r != BZ_OK) {
  2053. archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
  2054. "bzip2 initialization failed(%d)",
  2055. r);
  2056. return ARCHIVE_FAILED;
  2057. }
  2058. /* Mark the bzstream field to be released in cleanup phase. */
  2059. zip->bzstream_valid = 1;
  2060. /* (Re)allocate the buffer that will contain decompressed bytes. */
  2061. free(zip->uncompressed_buffer);
  2062. zip->uncompressed_buffer_size = 256 * 1024;
  2063. zip->uncompressed_buffer = malloc(zip->uncompressed_buffer_size);
  2064. if (zip->uncompressed_buffer == NULL) {
  2065. archive_set_error(&a->archive, ENOMEM,
  2066. "No memory for bzip2 decompression");
  2067. return ARCHIVE_FATAL;
  2068. }
  2069. /* Initialization done. */
  2070. zip->decompress_init = 1;
  2071. return ARCHIVE_OK;
  2072. }
  2073. static int
  2074. zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
  2075. size_t *size, int64_t *offset)
  2076. {
  2077. struct zip *zip = (struct zip *)(a->format->data);
  2078. ssize_t bytes_avail = 0, in_bytes, to_consume;
  2079. const void *compressed_buff;
  2080. int r;
  2081. uint64_t total_out;
  2082. (void) offset; /* UNUSED */
  2083. /* Initialize decompression context if we're here for the first time. */
  2084. if(!zip->decompress_init) {
  2085. r = zipx_bzip2_init(a, zip);
  2086. if(r != ARCHIVE_OK)
  2087. return r;
  2088. }
  2089. /* Fetch more compressed bytes. */
  2090. compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
  2091. if(bytes_avail < 0) {
  2092. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2093. "Truncated bzip2 file body");
  2094. return (ARCHIVE_FATAL);
  2095. }
  2096. in_bytes = (ssize_t)zipmin(zip->entry_bytes_remaining, bytes_avail);
  2097. if(in_bytes < 1) {
  2098. /* libbz2 doesn't complain when caller feeds avail_in == 0.
  2099. * It will actually return success in this case, which is
  2100. * undesirable. This is why we need to make this check
  2101. * manually. */
  2102. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2103. "Truncated bzip2 file body");
  2104. return (ARCHIVE_FATAL);
  2105. }
  2106. /* Setup buffer boundaries. */
  2107. zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
  2108. zip->bzstream.avail_in = (uint32_t)in_bytes;
  2109. zip->bzstream.total_in_hi32 = 0;
  2110. zip->bzstream.total_in_lo32 = 0;
  2111. zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
  2112. zip->bzstream.avail_out = (uint32_t)zip->uncompressed_buffer_size;
  2113. zip->bzstream.total_out_hi32 = 0;
  2114. zip->bzstream.total_out_lo32 = 0;
  2115. /* Perform the decompression. */
  2116. r = BZ2_bzDecompress(&zip->bzstream);
  2117. switch(r) {
  2118. case BZ_STREAM_END:
  2119. /* If we're at the end of the stream, deinitialize the
  2120. * decompression context now. */
  2121. switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
  2122. case BZ_OK:
  2123. break;
  2124. default:
  2125. archive_set_error(&a->archive,
  2126. ARCHIVE_ERRNO_MISC,
  2127. "Failed to clean up bzip2 "
  2128. "decompressor");
  2129. return ARCHIVE_FATAL;
  2130. }
  2131. zip->end_of_entry = 1;
  2132. break;
  2133. case BZ_OK:
  2134. /* The decompressor has successfully decoded this
  2135. * chunk of data, but more data is still in queue. */
  2136. break;
  2137. default:
  2138. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2139. "bzip2 decompression failed");
  2140. return ARCHIVE_FATAL;
  2141. }
  2142. /* Update the pointers so decompressor can continue decoding. */
  2143. to_consume = zip->bzstream.total_in_lo32;
  2144. __archive_read_consume(a, to_consume);
  2145. total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) |
  2146. zip->bzstream.total_out_lo32;
  2147. zip->entry_bytes_remaining -= to_consume;
  2148. zip->entry_compressed_bytes_read += to_consume;
  2149. zip->entry_uncompressed_bytes_read += total_out;
  2150. /* Give libarchive its due. */
  2151. *size = (size_t)total_out;
  2152. *buff = zip->uncompressed_buffer;
  2153. return ARCHIVE_OK;
  2154. }
  2155. #endif
  2156. #if HAVE_ZSTD_H && HAVE_LIBZSTD
  2157. static int
  2158. zipx_zstd_init(struct archive_read *a, struct zip *zip)
  2159. {
  2160. size_t r;
  2161. /* Deallocate already existing Zstd decompression context if it
  2162. * exists. */
  2163. if(zip->zstdstream_valid) {
  2164. ZSTD_freeDStream(zip->zstdstream);
  2165. zip->zstdstream_valid = 0;
  2166. }
  2167. /* Allocate a new Zstd decompression context. */
  2168. zip->zstdstream = ZSTD_createDStream();
  2169. r = ZSTD_initDStream(zip->zstdstream);
  2170. if (ZSTD_isError(r)) {
  2171. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2172. "Error initializing zstd decompressor: %s",
  2173. ZSTD_getErrorName(r));
  2174. return ARCHIVE_FAILED;
  2175. }
  2176. /* Mark the zstdstream field to be released in cleanup phase. */
  2177. zip->zstdstream_valid = 1;
  2178. /* (Re)allocate the buffer that will contain decompressed bytes. */
  2179. free(zip->uncompressed_buffer);
  2180. zip->uncompressed_buffer_size = ZSTD_DStreamOutSize();
  2181. zip->uncompressed_buffer = malloc(zip->uncompressed_buffer_size);
  2182. if (zip->uncompressed_buffer == NULL) {
  2183. archive_set_error(&a->archive, ENOMEM,
  2184. "No memory for Zstd decompression");
  2185. return ARCHIVE_FATAL;
  2186. }
  2187. /* Initialization done. */
  2188. zip->decompress_init = 1;
  2189. return ARCHIVE_OK;
  2190. }
  2191. static int
  2192. zip_read_data_zipx_zstd(struct archive_read *a, const void **buff,
  2193. size_t *size, int64_t *offset)
  2194. {
  2195. struct zip *zip = (struct zip *)(a->format->data);
  2196. ssize_t bytes_avail = 0, in_bytes, to_consume;
  2197. const void *compressed_buff;
  2198. int r;
  2199. size_t ret;
  2200. uint64_t total_out;
  2201. ZSTD_outBuffer out;
  2202. ZSTD_inBuffer in;
  2203. (void) offset; /* UNUSED */
  2204. /* Initialize decompression context if we're here for the first time. */
  2205. if(!zip->decompress_init) {
  2206. r = zipx_zstd_init(a, zip);
  2207. if(r != ARCHIVE_OK)
  2208. return r;
  2209. }
  2210. /* Fetch more compressed bytes */
  2211. compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
  2212. if(bytes_avail < 0) {
  2213. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2214. "Truncated zstd file body");
  2215. return (ARCHIVE_FATAL);
  2216. }
  2217. in_bytes = (ssize_t)zipmin(zip->entry_bytes_remaining, bytes_avail);
  2218. if(in_bytes < 1) {
  2219. /* zstd doesn't complain when caller feeds avail_in == 0.
  2220. * It will actually return success in this case, which is
  2221. * undesirable. This is why we need to make this check
  2222. * manually. */
  2223. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2224. "Truncated zstd file body");
  2225. return (ARCHIVE_FATAL);
  2226. }
  2227. /* Setup buffer boundaries */
  2228. in.src = compressed_buff;
  2229. in.size = in_bytes;
  2230. in.pos = 0;
  2231. out = (ZSTD_outBuffer) { zip->uncompressed_buffer, zip->uncompressed_buffer_size, 0 };
  2232. /* Perform the decompression. */
  2233. ret = ZSTD_decompressStream(zip->zstdstream, &out, &in);
  2234. if (ZSTD_isError(ret)) {
  2235. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2236. "Error during zstd decompression: %s",
  2237. ZSTD_getErrorName(ret));
  2238. return (ARCHIVE_FATAL);
  2239. }
  2240. /* Check end of the stream. */
  2241. if (ret == 0) {
  2242. if ((in.pos == in.size) && (out.pos < out.size)) {
  2243. zip->end_of_entry = 1;
  2244. ZSTD_freeDStream(zip->zstdstream);
  2245. zip->zstdstream_valid = 0;
  2246. }
  2247. }
  2248. /* Update the pointers so decompressor can continue decoding. */
  2249. to_consume = in.pos;
  2250. __archive_read_consume(a, to_consume);
  2251. total_out = out.pos;
  2252. zip->entry_bytes_remaining -= to_consume;
  2253. zip->entry_compressed_bytes_read += to_consume;
  2254. zip->entry_uncompressed_bytes_read += total_out;
  2255. /* Give libarchive its due. */
  2256. *size = (size_t)total_out;
  2257. *buff = zip->uncompressed_buffer;
  2258. return ARCHIVE_OK;
  2259. }
  2260. #endif
  2261. #ifdef HAVE_ZLIB_H
  2262. static int
  2263. zip_deflate_init(struct archive_read *a, struct zip *zip)
  2264. {
  2265. int r;
  2266. /* If we haven't yet read any data, initialize the decompressor. */
  2267. if (!zip->decompress_init) {
  2268. if (zip->stream_valid)
  2269. r = inflateReset(&zip->stream);
  2270. else
  2271. r = inflateInit2(&zip->stream,
  2272. -15 /* Don't check for zlib header */);
  2273. if (r != Z_OK) {
  2274. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2275. "Can't initialize ZIP decompression.");
  2276. return (ARCHIVE_FATAL);
  2277. }
  2278. /* Stream structure has been set up. */
  2279. zip->stream_valid = 1;
  2280. /* We've initialized decompression for this stream. */
  2281. zip->decompress_init = 1;
  2282. }
  2283. return (ARCHIVE_OK);
  2284. }
  2285. static int
  2286. zip_read_data_deflate(struct archive_read *a, const void **buff,
  2287. size_t *size, int64_t *offset)
  2288. {
  2289. struct zip *zip;
  2290. ssize_t bytes_avail, to_consume = 0;
  2291. const void *compressed_buff, *sp;
  2292. int r;
  2293. (void)offset; /* UNUSED */
  2294. zip = (struct zip *)(a->format->data);
  2295. /* If the buffer hasn't been allocated, allocate it now. */
  2296. if (zip->uncompressed_buffer == NULL) {
  2297. zip->uncompressed_buffer_size = 256 * 1024;
  2298. zip->uncompressed_buffer
  2299. = malloc(zip->uncompressed_buffer_size);
  2300. if (zip->uncompressed_buffer == NULL) {
  2301. archive_set_error(&a->archive, ENOMEM,
  2302. "No memory for ZIP decompression");
  2303. return (ARCHIVE_FATAL);
  2304. }
  2305. }
  2306. r = zip_deflate_init(a, zip);
  2307. if (r != ARCHIVE_OK)
  2308. return (r);
  2309. /*
  2310. * Note: '1' here is a performance optimization.
  2311. * Recall that the decompression layer returns a count of
  2312. * available bytes; asking for more than that forces the
  2313. * decompressor to combine reads by copying data.
  2314. */
  2315. compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
  2316. if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
  2317. && bytes_avail > zip->entry_bytes_remaining) {
  2318. bytes_avail = (ssize_t)zip->entry_bytes_remaining;
  2319. }
  2320. if (bytes_avail < 0) {
  2321. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2322. "Truncated ZIP file body");
  2323. return (ARCHIVE_FATAL);
  2324. }
  2325. if (zip->tctx_valid || zip->cctx_valid) {
  2326. if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
  2327. size_t buff_remaining =
  2328. (zip->decrypted_buffer +
  2329. zip->decrypted_buffer_size)
  2330. - (zip->decrypted_ptr +
  2331. zip->decrypted_bytes_remaining);
  2332. if (buff_remaining > (size_t)bytes_avail)
  2333. buff_remaining = (size_t)bytes_avail;
  2334. if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
  2335. zip->entry_bytes_remaining > 0) {
  2336. if ((int64_t)(zip->decrypted_bytes_remaining
  2337. + buff_remaining)
  2338. > zip->entry_bytes_remaining) {
  2339. if (zip->entry_bytes_remaining <
  2340. (int64_t)zip->decrypted_bytes_remaining)
  2341. buff_remaining = 0;
  2342. else
  2343. buff_remaining =
  2344. (size_t)zip->entry_bytes_remaining
  2345. - zip->decrypted_bytes_remaining;
  2346. }
  2347. }
  2348. if (buff_remaining > 0) {
  2349. if (zip->tctx_valid) {
  2350. trad_enc_decrypt_update(&zip->tctx,
  2351. compressed_buff, buff_remaining,
  2352. zip->decrypted_ptr
  2353. + zip->decrypted_bytes_remaining,
  2354. buff_remaining);
  2355. } else {
  2356. size_t dsize = buff_remaining;
  2357. archive_decrypto_aes_ctr_update(
  2358. &zip->cctx,
  2359. compressed_buff, buff_remaining,
  2360. zip->decrypted_ptr
  2361. + zip->decrypted_bytes_remaining,
  2362. &dsize);
  2363. }
  2364. zip->decrypted_bytes_remaining +=
  2365. buff_remaining;
  2366. }
  2367. }
  2368. bytes_avail = zip->decrypted_bytes_remaining;
  2369. compressed_buff = (const char *)zip->decrypted_ptr;
  2370. }
  2371. /*
  2372. * A bug in zlib.h: stream.next_in should be marked 'const'
  2373. * but isn't (the library never alters data through the
  2374. * next_in pointer, only reads it). The result: this ugly
  2375. * cast to remove 'const'.
  2376. */
  2377. zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
  2378. zip->stream.avail_in = (uInt)bytes_avail;
  2379. zip->stream.total_in = 0;
  2380. zip->stream.next_out = zip->uncompressed_buffer;
  2381. zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
  2382. zip->stream.total_out = 0;
  2383. r = inflate(&zip->stream, 0);
  2384. switch (r) {
  2385. case Z_OK:
  2386. break;
  2387. case Z_STREAM_END:
  2388. zip->end_of_entry = 1;
  2389. break;
  2390. case Z_MEM_ERROR:
  2391. archive_set_error(&a->archive, ENOMEM,
  2392. "Out of memory for ZIP decompression");
  2393. return (ARCHIVE_FATAL);
  2394. default:
  2395. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2396. "ZIP decompression failed (%d)", r);
  2397. return (ARCHIVE_FATAL);
  2398. }
  2399. /* Consume as much as the compressor actually used. */
  2400. to_consume = zip->stream.total_in;
  2401. __archive_read_consume(a, to_consume);
  2402. zip->entry_bytes_remaining -= to_consume;
  2403. zip->entry_compressed_bytes_read += to_consume;
  2404. zip->entry_uncompressed_bytes_read += zip->stream.total_out;
  2405. if (zip->tctx_valid || zip->cctx_valid) {
  2406. zip->decrypted_bytes_remaining -= to_consume;
  2407. if (zip->decrypted_bytes_remaining == 0)
  2408. zip->decrypted_ptr = zip->decrypted_buffer;
  2409. else
  2410. zip->decrypted_ptr += to_consume;
  2411. }
  2412. if (zip->hctx_valid)
  2413. archive_hmac_sha1_update(&zip->hctx, sp, to_consume);
  2414. if (zip->end_of_entry) {
  2415. if (zip->hctx_valid) {
  2416. r = check_authentication_code(a, NULL);
  2417. if (r != ARCHIVE_OK) {
  2418. return (r);
  2419. }
  2420. }
  2421. }
  2422. *size = zip->stream.total_out;
  2423. *buff = zip->uncompressed_buffer;
  2424. return (ARCHIVE_OK);
  2425. }
  2426. #endif
  2427. static int
  2428. read_decryption_header(struct archive_read *a)
  2429. {
  2430. struct zip *zip = (struct zip *)(a->format->data);
  2431. const char *p;
  2432. unsigned int remaining_size;
  2433. unsigned int ts;
  2434. /*
  2435. * Read an initialization vector data field.
  2436. */
  2437. p = __archive_read_ahead(a, 2, NULL);
  2438. if (p == NULL)
  2439. goto truncated;
  2440. ts = zip->iv_size;
  2441. zip->iv_size = archive_le16dec(p);
  2442. __archive_read_consume(a, 2);
  2443. if (ts < zip->iv_size) {
  2444. free(zip->iv);
  2445. zip->iv = NULL;
  2446. }
  2447. p = __archive_read_ahead(a, zip->iv_size, NULL);
  2448. if (p == NULL)
  2449. goto truncated;
  2450. if (zip->iv == NULL) {
  2451. zip->iv = malloc(zip->iv_size);
  2452. if (zip->iv == NULL)
  2453. goto nomem;
  2454. }
  2455. memcpy(zip->iv, p, zip->iv_size);
  2456. __archive_read_consume(a, zip->iv_size);
  2457. /*
  2458. * Read a size of remaining decryption header field.
  2459. */
  2460. p = __archive_read_ahead(a, 14, NULL);
  2461. if (p == NULL)
  2462. goto truncated;
  2463. remaining_size = archive_le32dec(p);
  2464. if (remaining_size < 16 || remaining_size > (1 << 18))
  2465. goto corrupted;
  2466. /* Check if format version is supported. */
  2467. if (archive_le16dec(p+4) != 3) {
  2468. archive_set_error(&a->archive,
  2469. ARCHIVE_ERRNO_FILE_FORMAT,
  2470. "Unsupported encryption format version: %u",
  2471. archive_le16dec(p+4));
  2472. return (ARCHIVE_FAILED);
  2473. }
  2474. /*
  2475. * Read an encryption algorithm field.
  2476. */
  2477. zip->alg_id = archive_le16dec(p+6);
  2478. switch (zip->alg_id) {
  2479. case 0x6601:/* DES */
  2480. case 0x6602:/* RC2 */
  2481. case 0x6603:/* 3DES 168 */
  2482. case 0x6609:/* 3DES 112 */
  2483. case 0x660E:/* AES 128 */
  2484. case 0x660F:/* AES 192 */
  2485. case 0x6610:/* AES 256 */
  2486. case 0x6702:/* RC2 (version >= 5.2) */
  2487. case 0x6720:/* Blowfish */
  2488. case 0x6721:/* Twofish */
  2489. case 0x6801:/* RC4 */
  2490. /* Supported encryption algorithm. */
  2491. break;
  2492. default:
  2493. archive_set_error(&a->archive,
  2494. ARCHIVE_ERRNO_FILE_FORMAT,
  2495. "Unknown encryption algorithm: %u", zip->alg_id);
  2496. return (ARCHIVE_FAILED);
  2497. }
  2498. /*
  2499. * Read a bit length field.
  2500. */
  2501. zip->bit_len = archive_le16dec(p+8);
  2502. /*
  2503. * Read a flags field.
  2504. */
  2505. zip->flags = archive_le16dec(p+10);
  2506. switch (zip->flags & 0xf000) {
  2507. case 0x0001: /* Password is required to decrypt. */
  2508. case 0x0002: /* Certificates only. */
  2509. case 0x0003: /* Password or certificate required to decrypt. */
  2510. break;
  2511. default:
  2512. archive_set_error(&a->archive,
  2513. ARCHIVE_ERRNO_FILE_FORMAT,
  2514. "Unknown encryption flag: %u", zip->flags);
  2515. return (ARCHIVE_FAILED);
  2516. }
  2517. if ((zip->flags & 0xf000) == 0 ||
  2518. (zip->flags & 0xf000) == 0x4000) {
  2519. archive_set_error(&a->archive,
  2520. ARCHIVE_ERRNO_FILE_FORMAT,
  2521. "Unknown encryption flag: %u", zip->flags);
  2522. return (ARCHIVE_FAILED);
  2523. }
  2524. /*
  2525. * Read an encrypted random data field.
  2526. */
  2527. ts = zip->erd_size;
  2528. zip->erd_size = archive_le16dec(p+12);
  2529. __archive_read_consume(a, 14);
  2530. if ((zip->erd_size & 0xf) != 0 ||
  2531. (zip->erd_size + 16) > remaining_size ||
  2532. (zip->erd_size + 16) < zip->erd_size)
  2533. goto corrupted;
  2534. if (ts < zip->erd_size) {
  2535. free(zip->erd);
  2536. zip->erd = NULL;
  2537. }
  2538. p = __archive_read_ahead(a, zip->erd_size, NULL);
  2539. if (p == NULL)
  2540. goto truncated;
  2541. if (zip->erd == NULL) {
  2542. zip->erd = malloc(zip->erd_size);
  2543. if (zip->erd == NULL)
  2544. goto nomem;
  2545. }
  2546. memcpy(zip->erd, p, zip->erd_size);
  2547. __archive_read_consume(a, zip->erd_size);
  2548. /*
  2549. * Read a reserved data field.
  2550. */
  2551. p = __archive_read_ahead(a, 4, NULL);
  2552. if (p == NULL)
  2553. goto truncated;
  2554. /* Reserved data size should be zero. */
  2555. if (archive_le32dec(p) != 0)
  2556. goto corrupted;
  2557. __archive_read_consume(a, 4);
  2558. /*
  2559. * Read a password validation data field.
  2560. */
  2561. p = __archive_read_ahead(a, 2, NULL);
  2562. if (p == NULL)
  2563. goto truncated;
  2564. ts = zip->v_size;
  2565. zip->v_size = archive_le16dec(p);
  2566. __archive_read_consume(a, 2);
  2567. if ((zip->v_size & 0x0f) != 0 ||
  2568. (zip->erd_size + zip->v_size + 16) > remaining_size ||
  2569. (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
  2570. goto corrupted;
  2571. if (ts < zip->v_size) {
  2572. free(zip->v_data);
  2573. zip->v_data = NULL;
  2574. }
  2575. p = __archive_read_ahead(a, zip->v_size, NULL);
  2576. if (p == NULL)
  2577. goto truncated;
  2578. if (zip->v_data == NULL) {
  2579. zip->v_data = malloc(zip->v_size);
  2580. if (zip->v_data == NULL)
  2581. goto nomem;
  2582. }
  2583. memcpy(zip->v_data, p, zip->v_size);
  2584. __archive_read_consume(a, zip->v_size);
  2585. p = __archive_read_ahead(a, 4, NULL);
  2586. if (p == NULL)
  2587. goto truncated;
  2588. zip->v_crc32 = archive_le32dec(p);
  2589. __archive_read_consume(a, 4);
  2590. /*return (ARCHIVE_OK);
  2591. * This is not fully implemented yet.*/
  2592. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2593. "Encrypted file is unsupported");
  2594. return (ARCHIVE_FAILED);
  2595. truncated:
  2596. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2597. "Truncated ZIP file data");
  2598. return (ARCHIVE_FATAL);
  2599. corrupted:
  2600. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2601. "Corrupted ZIP file data");
  2602. return (ARCHIVE_FATAL);
  2603. nomem:
  2604. archive_set_error(&a->archive, ENOMEM,
  2605. "No memory for ZIP decryption");
  2606. return (ARCHIVE_FATAL);
  2607. }
  2608. static int
  2609. zip_alloc_decryption_buffer(struct archive_read *a)
  2610. {
  2611. struct zip *zip = (struct zip *)(a->format->data);
  2612. size_t bs = 256 * 1024;
  2613. if (zip->decrypted_buffer == NULL) {
  2614. zip->decrypted_buffer_size = bs;
  2615. zip->decrypted_buffer = malloc(bs);
  2616. if (zip->decrypted_buffer == NULL) {
  2617. archive_set_error(&a->archive, ENOMEM,
  2618. "No memory for ZIP decryption");
  2619. return (ARCHIVE_FATAL);
  2620. }
  2621. }
  2622. zip->decrypted_ptr = zip->decrypted_buffer;
  2623. return (ARCHIVE_OK);
  2624. }
  2625. static int
  2626. init_traditional_PKWARE_decryption(struct archive_read *a)
  2627. {
  2628. struct zip *zip = (struct zip *)(a->format->data);
  2629. const void *p;
  2630. int retry;
  2631. int r;
  2632. if (zip->tctx_valid)
  2633. return (ARCHIVE_OK);
  2634. /*
  2635. Read the 12 bytes encryption header stored at
  2636. the start of the data area.
  2637. */
  2638. #define ENC_HEADER_SIZE 12
  2639. if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
  2640. && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
  2641. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2642. "Truncated Zip encrypted body: only %jd bytes available",
  2643. (intmax_t)zip->entry_bytes_remaining);
  2644. return (ARCHIVE_FATAL);
  2645. }
  2646. p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
  2647. if (p == NULL) {
  2648. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2649. "Truncated ZIP file data");
  2650. return (ARCHIVE_FATAL);
  2651. }
  2652. for (retry = 0;; retry++) {
  2653. const char *passphrase;
  2654. uint8_t crcchk;
  2655. passphrase = __archive_read_next_passphrase(a);
  2656. if (passphrase == NULL) {
  2657. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2658. (retry > 0)?
  2659. "Incorrect passphrase":
  2660. "Passphrase required for this entry");
  2661. return (ARCHIVE_FAILED);
  2662. }
  2663. /*
  2664. * Initialize ctx for Traditional PKWARE Decryption.
  2665. */
  2666. r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
  2667. p, ENC_HEADER_SIZE, &crcchk);
  2668. if (r == 0 && crcchk == zip->entry->decdat)
  2669. break;/* The passphrase is OK. */
  2670. if (retry > 10000) {
  2671. /* Avoid infinity loop. */
  2672. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2673. "Too many incorrect passphrases");
  2674. return (ARCHIVE_FAILED);
  2675. }
  2676. }
  2677. __archive_read_consume(a, ENC_HEADER_SIZE);
  2678. zip->tctx_valid = 1;
  2679. if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
  2680. zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
  2681. }
  2682. /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
  2683. zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
  2684. zip->decrypted_bytes_remaining = 0;
  2685. return (zip_alloc_decryption_buffer(a));
  2686. #undef ENC_HEADER_SIZE
  2687. }
  2688. static int
  2689. init_WinZip_AES_decryption(struct archive_read *a)
  2690. {
  2691. struct zip *zip = (struct zip *)(a->format->data);
  2692. const void *p;
  2693. const uint8_t *pv;
  2694. size_t key_len, salt_len;
  2695. uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
  2696. int retry;
  2697. int r;
  2698. if (zip->cctx_valid || zip->hctx_valid)
  2699. return (ARCHIVE_OK);
  2700. switch (zip->entry->aes_extra.strength) {
  2701. case 1: salt_len = 8; key_len = 16; break;
  2702. case 2: salt_len = 12; key_len = 24; break;
  2703. case 3: salt_len = 16; key_len = 32; break;
  2704. default: goto corrupted;
  2705. }
  2706. p = __archive_read_ahead(a, salt_len + 2, NULL);
  2707. if (p == NULL)
  2708. goto truncated;
  2709. for (retry = 0;; retry++) {
  2710. const char *passphrase;
  2711. passphrase = __archive_read_next_passphrase(a);
  2712. if (passphrase == NULL) {
  2713. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2714. (retry > 0)?
  2715. "Incorrect passphrase":
  2716. "Passphrase required for this entry");
  2717. return (ARCHIVE_FAILED);
  2718. }
  2719. memset(derived_key, 0, sizeof(derived_key));
  2720. r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
  2721. p, salt_len, 1000, derived_key, key_len * 2 + 2);
  2722. if (r != 0) {
  2723. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2724. "Decryption is unsupported due to lack of "
  2725. "crypto library");
  2726. return (ARCHIVE_FAILED);
  2727. }
  2728. /* Check password verification value. */
  2729. pv = ((const uint8_t *)p) + salt_len;
  2730. if (derived_key[key_len * 2] == pv[0] &&
  2731. derived_key[key_len * 2 + 1] == pv[1])
  2732. break;/* The passphrase is OK. */
  2733. if (retry > 10000) {
  2734. /* Avoid infinity loop. */
  2735. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2736. "Too many incorrect passphrases");
  2737. return (ARCHIVE_FAILED);
  2738. }
  2739. }
  2740. r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
  2741. if (r != 0) {
  2742. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2743. "Decryption is unsupported due to lack of crypto library");
  2744. return (ARCHIVE_FAILED);
  2745. }
  2746. r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
  2747. if (r != 0) {
  2748. archive_decrypto_aes_ctr_release(&zip->cctx);
  2749. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2750. "Failed to initialize HMAC-SHA1");
  2751. return (ARCHIVE_FAILED);
  2752. }
  2753. zip->cctx_valid = zip->hctx_valid = 1;
  2754. __archive_read_consume(a, salt_len + 2);
  2755. zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
  2756. if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
  2757. && zip->entry_bytes_remaining < 0)
  2758. goto corrupted;
  2759. zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
  2760. zip->decrypted_bytes_remaining = 0;
  2761. zip->entry->compression = zip->entry->aes_extra.compression;
  2762. return (zip_alloc_decryption_buffer(a));
  2763. truncated:
  2764. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2765. "Truncated ZIP file data");
  2766. return (ARCHIVE_FATAL);
  2767. corrupted:
  2768. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2769. "Corrupted ZIP file data");
  2770. return (ARCHIVE_FATAL);
  2771. }
  2772. static int
  2773. archive_read_format_zip_read_data(struct archive_read *a,
  2774. const void **buff, size_t *size, int64_t *offset)
  2775. {
  2776. int r;
  2777. struct zip *zip = (struct zip *)(a->format->data);
  2778. if (zip->has_encrypted_entries ==
  2779. ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
  2780. zip->has_encrypted_entries = 0;
  2781. }
  2782. *offset = zip->entry_uncompressed_bytes_read;
  2783. *size = 0;
  2784. *buff = NULL;
  2785. /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
  2786. if (zip->end_of_entry)
  2787. return (ARCHIVE_EOF);
  2788. /* Return EOF immediately if this is a non-regular file. */
  2789. if (AE_IFREG != (zip->entry->mode & AE_IFMT))
  2790. return (ARCHIVE_EOF);
  2791. __archive_read_consume(a, zip->unconsumed);
  2792. zip->unconsumed = 0;
  2793. if (zip->init_decryption) {
  2794. zip->has_encrypted_entries = 1;
  2795. if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
  2796. r = read_decryption_header(a);
  2797. else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
  2798. r = init_WinZip_AES_decryption(a);
  2799. else
  2800. r = init_traditional_PKWARE_decryption(a);
  2801. if (r != ARCHIVE_OK)
  2802. return (r);
  2803. zip->init_decryption = 0;
  2804. }
  2805. switch(zip->entry->compression) {
  2806. case 0: /* No compression. */
  2807. r = zip_read_data_none(a, buff, size, offset);
  2808. break;
  2809. #ifdef HAVE_BZLIB_H
  2810. case 12: /* ZIPx bzip2 compression. */
  2811. r = zip_read_data_zipx_bzip2(a, buff, size, offset);
  2812. break;
  2813. #endif
  2814. #if HAVE_LZMA_H && HAVE_LIBLZMA
  2815. case 14: /* ZIPx LZMA compression. */
  2816. r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
  2817. break;
  2818. case 95: /* ZIPx XZ compression. */
  2819. r = zip_read_data_zipx_xz(a, buff, size, offset);
  2820. break;
  2821. #endif
  2822. #if HAVE_ZSTD_H && HAVE_LIBZSTD
  2823. case 93: /* ZIPx Zstd compression. */
  2824. r = zip_read_data_zipx_zstd(a, buff, size, offset);
  2825. break;
  2826. #endif
  2827. /* PPMd support is built-in, so we don't need any #if guards. */
  2828. case 98: /* ZIPx PPMd compression. */
  2829. r = zip_read_data_zipx_ppmd(a, buff, size, offset);
  2830. break;
  2831. #ifdef HAVE_ZLIB_H
  2832. case 8: /* Deflate compression. */
  2833. r = zip_read_data_deflate(a, buff, size, offset);
  2834. break;
  2835. #endif
  2836. default: /* Unsupported compression. */
  2837. /* Return a warning. */
  2838. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  2839. "Unsupported ZIP compression method (%d: %s)",
  2840. zip->entry->compression, compression_name(zip->entry->compression));
  2841. /* We can't decompress this entry, but we will
  2842. * be able to skip() it and try the next entry. */
  2843. return (ARCHIVE_FAILED);
  2844. }
  2845. if (r != ARCHIVE_OK)
  2846. return (r);
  2847. if (*size > 0) {
  2848. zip->computed_crc32 = zip->crc32func(zip->computed_crc32, *buff,
  2849. (unsigned)*size);
  2850. }
  2851. /* If we hit the end, swallow any end-of-data marker and
  2852. * verify the final check values. */
  2853. if (zip->end_of_entry) {
  2854. consume_end_of_file_marker(a, zip);
  2855. /* Check computed CRC against header */
  2856. if ((!zip->hctx_valid ||
  2857. zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
  2858. zip->entry->crc32 != zip->computed_crc32
  2859. && !zip->ignore_crc32) {
  2860. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2861. "ZIP bad CRC: 0x%lx should be 0x%lx",
  2862. (unsigned long)zip->computed_crc32,
  2863. (unsigned long)zip->entry->crc32);
  2864. return (ARCHIVE_FAILED);
  2865. }
  2866. /* Check file size against header. */
  2867. if (zip->entry->compressed_size !=
  2868. zip->entry_compressed_bytes_read) {
  2869. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2870. "ZIP compressed data is wrong size "
  2871. "(read %jd, expected %jd)",
  2872. (intmax_t)zip->entry_compressed_bytes_read,
  2873. (intmax_t)zip->entry->compressed_size);
  2874. return (ARCHIVE_FAILED);
  2875. }
  2876. /* Size field only stores the lower 32 bits of the actual
  2877. * size. */
  2878. if ((zip->entry->uncompressed_size & UINT32_MAX)
  2879. != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
  2880. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2881. "ZIP uncompressed data is wrong size "
  2882. "(read %jd, expected %jd)\n",
  2883. (intmax_t)zip->entry_uncompressed_bytes_read,
  2884. (intmax_t)zip->entry->uncompressed_size);
  2885. return (ARCHIVE_FAILED);
  2886. }
  2887. }
  2888. return (ARCHIVE_OK);
  2889. }
  2890. static int
  2891. archive_read_format_zip_cleanup(struct archive_read *a)
  2892. {
  2893. struct zip *zip;
  2894. struct zip_entry *zip_entry, *next_zip_entry;
  2895. zip = (struct zip *)(a->format->data);
  2896. #ifdef HAVE_ZLIB_H
  2897. if (zip->stream_valid)
  2898. inflateEnd(&zip->stream);
  2899. #endif
  2900. #if HAVE_LZMA_H && HAVE_LIBLZMA
  2901. if (zip->zipx_lzma_valid) {
  2902. lzma_end(&zip->zipx_lzma_stream);
  2903. }
  2904. #endif
  2905. #ifdef HAVE_BZLIB_H
  2906. if (zip->bzstream_valid) {
  2907. BZ2_bzDecompressEnd(&zip->bzstream);
  2908. }
  2909. #endif
  2910. #if HAVE_ZSTD_H && HAVE_LIBZSTD
  2911. if (zip->zstdstream_valid) {
  2912. ZSTD_freeDStream(zip->zstdstream);
  2913. }
  2914. #endif
  2915. free(zip->uncompressed_buffer);
  2916. if (zip->ppmd8_valid)
  2917. __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
  2918. if (zip->zip_entries) {
  2919. zip_entry = zip->zip_entries;
  2920. while (zip_entry != NULL) {
  2921. next_zip_entry = zip_entry->next;
  2922. archive_string_free(&zip_entry->rsrcname);
  2923. free(zip_entry);
  2924. zip_entry = next_zip_entry;
  2925. }
  2926. }
  2927. free(zip->decrypted_buffer);
  2928. if (zip->cctx_valid)
  2929. archive_decrypto_aes_ctr_release(&zip->cctx);
  2930. if (zip->hctx_valid)
  2931. archive_hmac_sha1_cleanup(&zip->hctx);
  2932. free(zip->iv);
  2933. free(zip->erd);
  2934. free(zip->v_data);
  2935. archive_string_free(&zip->format_name);
  2936. free(zip);
  2937. (a->format->data) = NULL;
  2938. return (ARCHIVE_OK);
  2939. }
  2940. static int
  2941. archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
  2942. {
  2943. if (_a && _a->format) {
  2944. struct zip * zip = (struct zip *)_a->format->data;
  2945. if (zip) {
  2946. return zip->has_encrypted_entries;
  2947. }
  2948. }
  2949. return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
  2950. }
  2951. static int
  2952. archive_read_format_zip_options(struct archive_read *a,
  2953. const char *key, const char *val)
  2954. {
  2955. struct zip *zip;
  2956. int ret = ARCHIVE_FAILED;
  2957. zip = (struct zip *)(a->format->data);
  2958. if (strcmp(key, "compat-2x") == 0) {
  2959. /* Handle filenames as libarchive 2.x */
  2960. zip->init_default_conversion = (val != NULL) ? 1 : 0;
  2961. return (ARCHIVE_OK);
  2962. } else if (strcmp(key, "hdrcharset") == 0) {
  2963. if (val == NULL || val[0] == 0)
  2964. archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
  2965. "zip: hdrcharset option needs a character-set name"
  2966. );
  2967. else {
  2968. zip->sconv = archive_string_conversion_from_charset(
  2969. &a->archive, val, 0);
  2970. if (zip->sconv != NULL) {
  2971. if (strcmp(val, "UTF-8") == 0)
  2972. zip->sconv_utf8 = zip->sconv;
  2973. ret = ARCHIVE_OK;
  2974. } else
  2975. ret = ARCHIVE_FATAL;
  2976. }
  2977. return (ret);
  2978. } else if (strcmp(key, "ignorecrc32") == 0) {
  2979. /* Mostly useful for testing. */
  2980. if (val == NULL || val[0] == 0) {
  2981. zip->crc32func = real_crc32;
  2982. zip->ignore_crc32 = 0;
  2983. } else {
  2984. zip->crc32func = fake_crc32;
  2985. zip->ignore_crc32 = 1;
  2986. }
  2987. return (ARCHIVE_OK);
  2988. } else if (strcmp(key, "mac-ext") == 0) {
  2989. zip->process_mac_extensions = (val != NULL && val[0] != 0);
  2990. return (ARCHIVE_OK);
  2991. }
  2992. /* Note: The "warn" return is just to inform the options
  2993. * supervisor that we didn't handle it. It will generate
  2994. * a suitable error if no one used this option. */
  2995. return (ARCHIVE_WARN);
  2996. }
  2997. int
  2998. archive_read_support_format_zip(struct archive *a)
  2999. {
  3000. int r;
  3001. r = archive_read_support_format_zip_streamable(a);
  3002. if (r != ARCHIVE_OK)
  3003. return r;
  3004. return (archive_read_support_format_zip_seekable(a));
  3005. }
  3006. /* ------------------------------------------------------------------------ */
  3007. /*
  3008. * Streaming-mode support
  3009. */
  3010. static int
  3011. archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
  3012. {
  3013. (void)a; /* UNUSED */
  3014. return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
  3015. ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
  3016. }
  3017. static int
  3018. archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
  3019. {
  3020. const char *p;
  3021. (void)best_bid; /* UNUSED */
  3022. if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
  3023. return (-1);
  3024. /*
  3025. * Bid of 29 here comes from:
  3026. * + 16 bits for "PK",
  3027. * + next 16-bit field has 6 options so contributes
  3028. * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
  3029. *
  3030. * So we've effectively verified ~29 total bits of check data.
  3031. */
  3032. if (p[0] == 'P' && p[1] == 'K') {
  3033. if ((p[2] == '\001' && p[3] == '\002')
  3034. || (p[2] == '\003' && p[3] == '\004')
  3035. || (p[2] == '\005' && p[3] == '\006')
  3036. || (p[2] == '\006' && p[3] == '\006')
  3037. || (p[2] == '\007' && p[3] == '\010')
  3038. || (p[2] == '0' && p[3] == '0'))
  3039. return (29);
  3040. }
  3041. /* TODO: It's worth looking ahead a little bit for a valid
  3042. * PK signature. In particular, that would make it possible
  3043. * to read some UUEncoded SFX files or SFX files coming from
  3044. * a network socket. */
  3045. return (0);
  3046. }
  3047. static int
  3048. archive_read_format_zip_streamable_read_header(struct archive_read *a,
  3049. struct archive_entry *entry)
  3050. {
  3051. struct zip *zip;
  3052. a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
  3053. if (a->archive.archive_format_name == NULL)
  3054. a->archive.archive_format_name = "ZIP";
  3055. zip = (struct zip *)(a->format->data);
  3056. /*
  3057. * It should be sufficient to call archive_read_next_header() for
  3058. * a reader to determine if an entry is encrypted or not. If the
  3059. * encryption of an entry is only detectable when calling
  3060. * archive_read_data(), so be it. We'll do the same check there
  3061. * as well.
  3062. */
  3063. if (zip->has_encrypted_entries ==
  3064. ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
  3065. zip->has_encrypted_entries = 0;
  3066. /* Make sure we have a zip_entry structure to use. */
  3067. if (zip->zip_entries == NULL) {
  3068. zip->zip_entries = malloc(sizeof(struct zip_entry));
  3069. if (zip->zip_entries == NULL) {
  3070. archive_set_error(&a->archive, ENOMEM,
  3071. "Out of memory");
  3072. return ARCHIVE_FATAL;
  3073. }
  3074. }
  3075. zip->entry = zip->zip_entries;
  3076. memset(zip->entry, 0, sizeof(struct zip_entry));
  3077. if (zip->cctx_valid)
  3078. archive_decrypto_aes_ctr_release(&zip->cctx);
  3079. if (zip->hctx_valid)
  3080. archive_hmac_sha1_cleanup(&zip->hctx);
  3081. zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
  3082. __archive_read_reset_passphrase(a);
  3083. /* Search ahead for the next local file header. */
  3084. __archive_read_consume(a, zip->unconsumed);
  3085. zip->unconsumed = 0;
  3086. for (;;) {
  3087. int64_t skipped = 0;
  3088. const char *p, *end;
  3089. ssize_t bytes;
  3090. p = __archive_read_ahead(a, 4, &bytes);
  3091. if (p == NULL)
  3092. return (ARCHIVE_FATAL);
  3093. end = p + bytes;
  3094. while (p + 4 <= end) {
  3095. if (p[0] == 'P' && p[1] == 'K') {
  3096. if (p[2] == '\003' && p[3] == '\004') {
  3097. /* Regular file entry. */
  3098. __archive_read_consume(a, skipped);
  3099. return zip_read_local_file_header(a,
  3100. entry, zip);
  3101. }
  3102. /*
  3103. * TODO: We cannot restore permissions
  3104. * based only on the local file headers.
  3105. * Consider scanning the central
  3106. * directory and returning additional
  3107. * entries for at least directories.
  3108. * This would allow us to properly set
  3109. * directory permissions.
  3110. *
  3111. * This won't help us fix symlinks
  3112. * and may not help with regular file
  3113. * permissions, either. <sigh>
  3114. */
  3115. if (p[2] == '\001' && p[3] == '\002') {
  3116. return (ARCHIVE_EOF);
  3117. }
  3118. /* End of central directory? Must be an
  3119. * empty archive. */
  3120. if ((p[2] == '\005' && p[3] == '\006')
  3121. || (p[2] == '\006' && p[3] == '\006'))
  3122. return (ARCHIVE_EOF);
  3123. }
  3124. ++p;
  3125. ++skipped;
  3126. }
  3127. __archive_read_consume(a, skipped);
  3128. }
  3129. }
  3130. static int
  3131. archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
  3132. {
  3133. struct zip *zip;
  3134. int64_t bytes_skipped;
  3135. zip = (struct zip *)(a->format->data);
  3136. bytes_skipped = __archive_read_consume(a, zip->unconsumed);
  3137. zip->unconsumed = 0;
  3138. if (bytes_skipped < 0)
  3139. return (ARCHIVE_FATAL);
  3140. /* If we've already read to end of data, we're done. */
  3141. if (zip->end_of_entry)
  3142. return (ARCHIVE_OK);
  3143. /* So we know we're streaming... */
  3144. if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
  3145. || zip->entry->compressed_size > 0) {
  3146. /* We know the compressed length, so we can just skip. */
  3147. bytes_skipped = __archive_read_consume(a,
  3148. zip->entry_bytes_remaining);
  3149. if (bytes_skipped < 0)
  3150. return (ARCHIVE_FATAL);
  3151. return (ARCHIVE_OK);
  3152. }
  3153. if (zip->init_decryption) {
  3154. int r;
  3155. zip->has_encrypted_entries = 1;
  3156. if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
  3157. r = read_decryption_header(a);
  3158. else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
  3159. r = init_WinZip_AES_decryption(a);
  3160. else
  3161. r = init_traditional_PKWARE_decryption(a);
  3162. if (r != ARCHIVE_OK)
  3163. return (r);
  3164. zip->init_decryption = 0;
  3165. }
  3166. /* We're streaming and we don't know the length. */
  3167. /* If the body is compressed and we know the format, we can
  3168. * find an exact end-of-entry by decompressing it. */
  3169. switch (zip->entry->compression) {
  3170. #ifdef HAVE_ZLIB_H
  3171. case 8: /* Deflate compression. */
  3172. while (!zip->end_of_entry) {
  3173. int64_t offset = 0;
  3174. const void *buff = NULL;
  3175. size_t size = 0;
  3176. int r;
  3177. r = zip_read_data_deflate(a, &buff, &size, &offset);
  3178. if (r != ARCHIVE_OK)
  3179. return (r);
  3180. }
  3181. return ARCHIVE_OK;
  3182. #endif
  3183. default: /* Uncompressed or unknown. */
  3184. /* Scan for a PK\007\010 signature. */
  3185. for (;;) {
  3186. const char *p, *buff;
  3187. ssize_t bytes_avail;
  3188. buff = __archive_read_ahead(a, 16, &bytes_avail);
  3189. if (bytes_avail < 16) {
  3190. archive_set_error(&a->archive,
  3191. ARCHIVE_ERRNO_FILE_FORMAT,
  3192. "Truncated ZIP file data");
  3193. return (ARCHIVE_FATAL);
  3194. }
  3195. p = buff;
  3196. while (p <= buff + bytes_avail - 16) {
  3197. if (p[3] == 'P') { p += 3; }
  3198. else if (p[3] == 'K') { p += 2; }
  3199. else if (p[3] == '\007') { p += 1; }
  3200. else if (p[3] == '\010' && p[2] == '\007'
  3201. && p[1] == 'K' && p[0] == 'P') {
  3202. if (zip->entry->flags & LA_USED_ZIP64)
  3203. __archive_read_consume(a,
  3204. p - buff + 24);
  3205. else
  3206. __archive_read_consume(a,
  3207. p - buff + 16);
  3208. return ARCHIVE_OK;
  3209. } else { p += 4; }
  3210. }
  3211. __archive_read_consume(a, p - buff);
  3212. }
  3213. }
  3214. }
  3215. int
  3216. archive_read_support_format_zip_streamable(struct archive *_a)
  3217. {
  3218. struct archive_read *a = (struct archive_read *)_a;
  3219. struct zip *zip;
  3220. int r;
  3221. archive_check_magic(_a, ARCHIVE_READ_MAGIC,
  3222. ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
  3223. zip = calloc(1, sizeof(*zip));
  3224. if (zip == NULL) {
  3225. archive_set_error(&a->archive, ENOMEM,
  3226. "Can't allocate zip data");
  3227. return (ARCHIVE_FATAL);
  3228. }
  3229. /* Streamable reader doesn't support mac extensions. */
  3230. zip->process_mac_extensions = 0;
  3231. /*
  3232. * Until enough data has been read, we cannot tell about
  3233. * any encrypted entries yet.
  3234. */
  3235. zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
  3236. zip->crc32func = real_crc32;
  3237. r = __archive_read_register_format(a,
  3238. zip,
  3239. "zip",
  3240. archive_read_format_zip_streamable_bid,
  3241. archive_read_format_zip_options,
  3242. archive_read_format_zip_streamable_read_header,
  3243. archive_read_format_zip_read_data,
  3244. archive_read_format_zip_read_data_skip_streamable,
  3245. NULL,
  3246. archive_read_format_zip_cleanup,
  3247. archive_read_support_format_zip_capabilities_streamable,
  3248. archive_read_format_zip_has_encrypted_entries);
  3249. if (r != ARCHIVE_OK)
  3250. free(zip);
  3251. return (ARCHIVE_OK);
  3252. }
  3253. /* ------------------------------------------------------------------------ */
  3254. /*
  3255. * Seeking-mode support
  3256. */
  3257. static int
  3258. archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
  3259. {
  3260. (void)a; /* UNUSED */
  3261. return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
  3262. ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
  3263. }
  3264. /*
  3265. * TODO: This is a performance sink because it forces the read core to
  3266. * drop buffered data from the start of file, which will then have to
  3267. * be re-read again if this bidder loses.
  3268. *
  3269. * We workaround this a little by passing in the best bid so far so
  3270. * that later bidders can do nothing if they know they'll never
  3271. * outbid. But we can certainly do better...
  3272. */
  3273. static int
  3274. read_eocd(struct zip *zip, const char *p, int64_t current_offset)
  3275. {
  3276. uint16_t disk_num;
  3277. uint32_t cd_size, cd_offset;
  3278. disk_num = archive_le16dec(p + 4);
  3279. cd_size = archive_le32dec(p + 12);
  3280. cd_offset = archive_le32dec(p + 16);
  3281. /* Sanity-check the EOCD we've found. */
  3282. /* This must be the first volume. */
  3283. if (disk_num != 0)
  3284. return 0;
  3285. /* Central directory must be on this volume. */
  3286. if (disk_num != archive_le16dec(p + 6))
  3287. return 0;
  3288. /* All central directory entries must be on this volume. */
  3289. if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
  3290. return 0;
  3291. /* Central directory can't extend beyond start of EOCD record. */
  3292. if ((int64_t)cd_offset + cd_size > current_offset)
  3293. return 0;
  3294. /* Save the central directory location for later use. */
  3295. zip->central_directory_offset = cd_offset;
  3296. zip->central_directory_offset_adjusted = current_offset - cd_size;
  3297. /* This is just a tiny bit higher than the maximum
  3298. returned by the streaming Zip bidder. This ensures
  3299. that the more accurate seeking Zip parser wins
  3300. whenever seek is available. */
  3301. return 32;
  3302. }
  3303. /*
  3304. * Examine Zip64 EOCD locator: If it's valid, store the information
  3305. * from it.
  3306. */
  3307. static int
  3308. read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
  3309. {
  3310. int64_t eocd64_offset;
  3311. int64_t eocd64_size;
  3312. /* Sanity-check the locator record. */
  3313. /* Central dir must be on first volume. */
  3314. if (archive_le32dec(p + 4) != 0)
  3315. return 0;
  3316. /* Must be only a single volume. */
  3317. if (archive_le32dec(p + 16) != 1)
  3318. return 0;
  3319. /* Find the Zip64 EOCD record. */
  3320. eocd64_offset = archive_le64dec(p + 8);
  3321. if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
  3322. return 0;
  3323. if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
  3324. return 0;
  3325. /* Make sure we can read all of it. */
  3326. eocd64_size = archive_le64dec(p + 4) + 12;
  3327. if (eocd64_size < 56 || eocd64_size > 16384)
  3328. return 0;
  3329. if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
  3330. return 0;
  3331. /* Sanity-check the EOCD64 */
  3332. if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
  3333. return 0;
  3334. if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
  3335. return 0;
  3336. /* CD can't be split. */
  3337. if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
  3338. return 0;
  3339. /* Save the central directory offset for later use. */
  3340. zip->central_directory_offset = archive_le64dec(p + 48);
  3341. /* TODO: Needs scanning backwards to find the eocd64 instead of assuming */
  3342. zip->central_directory_offset_adjusted = zip->central_directory_offset;
  3343. return 32;
  3344. }
  3345. static int
  3346. archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
  3347. {
  3348. struct zip *zip = (struct zip *)a->format->data;
  3349. int64_t file_size, current_offset;
  3350. const char *p;
  3351. int i, tail;
  3352. /* If someone has already bid more than 32, then avoid
  3353. trashing the look-ahead buffers with a seek. */
  3354. if (best_bid > 32)
  3355. return (-1);
  3356. file_size = __archive_read_seek(a, 0, SEEK_END);
  3357. if (file_size <= 0)
  3358. return 0;
  3359. /* Search last 16k of file for end-of-central-directory
  3360. * record (which starts with PK\005\006) */
  3361. tail = (int)zipmin(1024 * 16, file_size);
  3362. current_offset = __archive_read_seek(a, -tail, SEEK_END);
  3363. if (current_offset < 0)
  3364. return 0;
  3365. if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
  3366. return 0;
  3367. /* Boyer-Moore search backwards from the end, since we want
  3368. * to match the last EOCD in the file (there can be more than
  3369. * one if there is an uncompressed Zip archive as a member
  3370. * within this Zip archive). */
  3371. for (i = tail - 22; i > 0;) {
  3372. switch (p[i]) {
  3373. case 'P':
  3374. if (memcmp(p + i, "PK\005\006", 4) == 0) {
  3375. int ret = read_eocd(zip, p + i,
  3376. current_offset + i);
  3377. /* Zip64 EOCD locator precedes
  3378. * regular EOCD if present. */
  3379. if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
  3380. int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
  3381. if (ret_zip64 > ret)
  3382. ret = ret_zip64;
  3383. }
  3384. return (ret);
  3385. }
  3386. i -= 4;
  3387. break;
  3388. case 'K': i -= 1; break;
  3389. case 005: i -= 2; break;
  3390. case 006: i -= 3; break;
  3391. default: i -= 4; break;
  3392. }
  3393. }
  3394. return 0;
  3395. }
  3396. /* The red-black trees are only used in seeking mode to manage
  3397. * the in-memory copy of the central directory. */
  3398. static int
  3399. cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
  3400. {
  3401. const struct zip_entry *e1 = (const struct zip_entry *)n1;
  3402. const struct zip_entry *e2 = (const struct zip_entry *)n2;
  3403. if (e1->local_header_offset > e2->local_header_offset)
  3404. return -1;
  3405. if (e1->local_header_offset < e2->local_header_offset)
  3406. return 1;
  3407. return 0;
  3408. }
  3409. static int
  3410. cmp_key(const struct archive_rb_node *n, const void *key)
  3411. {
  3412. /* This function won't be called */
  3413. (void)n; /* UNUSED */
  3414. (void)key; /* UNUSED */
  3415. return 1;
  3416. }
  3417. static const struct archive_rb_tree_ops rb_ops = {
  3418. &cmp_node, &cmp_key
  3419. };
  3420. static int
  3421. rsrc_cmp_node(const struct archive_rb_node *n1,
  3422. const struct archive_rb_node *n2)
  3423. {
  3424. const struct zip_entry *e1 = (const struct zip_entry *)n1;
  3425. const struct zip_entry *e2 = (const struct zip_entry *)n2;
  3426. return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
  3427. }
  3428. static int
  3429. rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
  3430. {
  3431. const struct zip_entry *e = (const struct zip_entry *)n;
  3432. return (strcmp((const char *)key, e->rsrcname.s));
  3433. }
  3434. static const struct archive_rb_tree_ops rb_rsrc_ops = {
  3435. &rsrc_cmp_node, &rsrc_cmp_key
  3436. };
  3437. static const char *
  3438. rsrc_basename(const char *name, size_t name_length)
  3439. {
  3440. const char *s, *r;
  3441. r = s = name;
  3442. for (;;) {
  3443. s = memchr(s, '/', name_length - (s - name));
  3444. if (s == NULL)
  3445. break;
  3446. r = ++s;
  3447. }
  3448. return (r);
  3449. }
  3450. static void
  3451. expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
  3452. {
  3453. struct archive_string str;
  3454. struct zip_entry *dir;
  3455. char *s;
  3456. archive_string_init(&str);
  3457. archive_strncpy(&str, name, name_length);
  3458. for (;;) {
  3459. s = strrchr(str.s, '/');
  3460. if (s == NULL)
  3461. break;
  3462. *s = '\0';
  3463. /* Transfer the parent directory from zip->tree_rsrc RB
  3464. * tree to zip->tree RB tree to expose. */
  3465. dir = (struct zip_entry *)
  3466. __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
  3467. if (dir == NULL)
  3468. break;
  3469. __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
  3470. archive_string_free(&dir->rsrcname);
  3471. __archive_rb_tree_insert_node(&zip->tree, &dir->node);
  3472. }
  3473. archive_string_free(&str);
  3474. }
  3475. static int
  3476. slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
  3477. struct zip *zip)
  3478. {
  3479. ssize_t i;
  3480. unsigned found;
  3481. int64_t correction;
  3482. ssize_t bytes_avail;
  3483. const char *p;
  3484. /*
  3485. * Find the start of the central directory. The end-of-CD
  3486. * record has our starting point, but there are lots of
  3487. * Zip archives which have had other data prepended to the
  3488. * file, which makes the recorded offsets all too small.
  3489. * So we search forward from the specified offset until we
  3490. * find the real start of the central directory. Then we
  3491. * know the correction we need to apply to account for leading
  3492. * padding.
  3493. */
  3494. if (__archive_read_seek(a, zip->central_directory_offset_adjusted, SEEK_SET)
  3495. < 0)
  3496. return ARCHIVE_FATAL;
  3497. found = 0;
  3498. while (!found) {
  3499. if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
  3500. return ARCHIVE_FATAL;
  3501. for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
  3502. switch (p[i + 3]) {
  3503. case 'P': i += 3; break;
  3504. case 'K': i += 2; break;
  3505. case 001: i += 1; break;
  3506. case 002:
  3507. if (memcmp(p + i, "PK\001\002", 4) == 0) {
  3508. p += i;
  3509. found = 1;
  3510. } else
  3511. i += 4;
  3512. break;
  3513. case 005: i += 1; break;
  3514. case 006:
  3515. if (memcmp(p + i, "PK\005\006", 4) == 0) {
  3516. p += i;
  3517. found = 1;
  3518. } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
  3519. p += i;
  3520. found = 1;
  3521. } else
  3522. i += 1;
  3523. break;
  3524. default: i += 4; break;
  3525. }
  3526. }
  3527. __archive_read_consume(a, i);
  3528. }
  3529. correction = archive_filter_bytes(&a->archive, 0)
  3530. - zip->central_directory_offset;
  3531. __archive_rb_tree_init(&zip->tree, &rb_ops);
  3532. __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
  3533. zip->central_directory_entries_total = 0;
  3534. while (1) {
  3535. struct zip_entry *zip_entry;
  3536. size_t filename_length, extra_length, comment_length;
  3537. uint32_t external_attributes;
  3538. const char *name, *r;
  3539. if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
  3540. return ARCHIVE_FATAL;
  3541. if (memcmp(p, "PK\006\006", 4) == 0
  3542. || memcmp(p, "PK\005\006", 4) == 0) {
  3543. break;
  3544. } else if (memcmp(p, "PK\001\002", 4) != 0) {
  3545. archive_set_error(&a->archive,
  3546. -1, "Invalid central directory signature");
  3547. return ARCHIVE_FATAL;
  3548. }
  3549. if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
  3550. return ARCHIVE_FATAL;
  3551. zip_entry = calloc(1, sizeof(struct zip_entry));
  3552. if (zip_entry == NULL) {
  3553. archive_set_error(&a->archive, ENOMEM,
  3554. "Can't allocate zip entry");
  3555. return ARCHIVE_FATAL;
  3556. }
  3557. zip_entry->next = zip->zip_entries;
  3558. zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
  3559. zip->zip_entries = zip_entry;
  3560. zip->central_directory_entries_total++;
  3561. /* version = p[4]; */
  3562. zip_entry->system = p[5];
  3563. /* version_required = archive_le16dec(p + 6); */
  3564. zip_entry->zip_flags = archive_le16dec(p + 8);
  3565. if (zip_entry->zip_flags
  3566. & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
  3567. zip->has_encrypted_entries = 1;
  3568. }
  3569. zip_entry->compression = (char)archive_le16dec(p + 10);
  3570. zip_entry->mtime = zip_time(p + 12);
  3571. zip_entry->crc32 = archive_le32dec(p + 16);
  3572. if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
  3573. zip_entry->decdat = p[13];
  3574. else
  3575. zip_entry->decdat = p[19];
  3576. zip_entry->compressed_size = archive_le32dec(p + 20);
  3577. zip_entry->uncompressed_size = archive_le32dec(p + 24);
  3578. filename_length = archive_le16dec(p + 28);
  3579. extra_length = archive_le16dec(p + 30);
  3580. comment_length = archive_le16dec(p + 32);
  3581. /* disk_start = archive_le16dec(p + 34);
  3582. * Better be zero.
  3583. * internal_attributes = archive_le16dec(p + 36);
  3584. * text bit */
  3585. external_attributes = archive_le32dec(p + 38);
  3586. zip_entry->local_header_offset =
  3587. archive_le32dec(p + 42) + correction;
  3588. /* If we can't guess the mode, leave it zero here;
  3589. when we read the local file header we might get
  3590. more information. */
  3591. if (zip_entry->system == 3) {
  3592. zip_entry->mode = external_attributes >> 16;
  3593. } else if (zip_entry->system == 0) {
  3594. // Interpret MSDOS directory bit
  3595. if (0x10 == (external_attributes & 0x10)) {
  3596. zip_entry->mode = AE_IFDIR | 0775;
  3597. } else {
  3598. zip_entry->mode = AE_IFREG | 0664;
  3599. }
  3600. if (0x01 == (external_attributes & 0x01)) {
  3601. // Read-only bit; strip write permissions
  3602. zip_entry->mode &= 0555;
  3603. }
  3604. } else {
  3605. zip_entry->mode = 0;
  3606. }
  3607. /* We're done with the regular data; get the filename and
  3608. * extra data. */
  3609. __archive_read_consume(a, 46);
  3610. p = __archive_read_ahead(a, filename_length + extra_length,
  3611. NULL);
  3612. if (p == NULL) {
  3613. archive_set_error(&a->archive,
  3614. ARCHIVE_ERRNO_FILE_FORMAT,
  3615. "Truncated ZIP file header");
  3616. return ARCHIVE_FATAL;
  3617. }
  3618. if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
  3619. extra_length, zip_entry)) {
  3620. return ARCHIVE_FATAL;
  3621. }
  3622. /*
  3623. * Mac resource fork files are stored under the
  3624. * "__MACOSX/" directory, so we should check if
  3625. * it is.
  3626. */
  3627. if (!zip->process_mac_extensions) {
  3628. /* Treat every entry as a regular entry. */
  3629. __archive_rb_tree_insert_node(&zip->tree,
  3630. &zip_entry->node);
  3631. } else {
  3632. name = p;
  3633. r = rsrc_basename(name, filename_length);
  3634. if (filename_length >= 9 &&
  3635. strncmp("__MACOSX/", name, 9) == 0) {
  3636. /* If this file is not a resource fork nor
  3637. * a directory. We should treat it as a non
  3638. * resource fork file to expose it. */
  3639. if (name[filename_length-1] != '/' &&
  3640. (r - name < 3 || r[0] != '.' ||
  3641. r[1] != '_')) {
  3642. __archive_rb_tree_insert_node(
  3643. &zip->tree, &zip_entry->node);
  3644. /* Expose its parent directories. */
  3645. expose_parent_dirs(zip, name,
  3646. filename_length);
  3647. } else {
  3648. /* This file is a resource fork file or
  3649. * a directory. */
  3650. archive_strncpy(&(zip_entry->rsrcname),
  3651. name, filename_length);
  3652. __archive_rb_tree_insert_node(
  3653. &zip->tree_rsrc, &zip_entry->node);
  3654. }
  3655. } else {
  3656. /* Generate resource fork name to find its
  3657. * resource file at zip->tree_rsrc. */
  3658. /* If this is an entry ending with slash,
  3659. * make the resource for name slash-less
  3660. * as the actual resource fork doesn't end with '/'.
  3661. */
  3662. size_t tmp_length = filename_length;
  3663. if (tmp_length > 0 && name[tmp_length - 1] == '/') {
  3664. tmp_length--;
  3665. r = rsrc_basename(name, tmp_length);
  3666. }
  3667. archive_strcpy(&(zip_entry->rsrcname),
  3668. "__MACOSX/");
  3669. archive_strncat(&(zip_entry->rsrcname),
  3670. name, r - name);
  3671. archive_strcat(&(zip_entry->rsrcname), "._");
  3672. archive_strncat(&(zip_entry->rsrcname),
  3673. name + (r - name),
  3674. tmp_length - (r - name));
  3675. /* Register an entry to RB tree to sort it by
  3676. * file offset. */
  3677. __archive_rb_tree_insert_node(&zip->tree,
  3678. &zip_entry->node);
  3679. }
  3680. }
  3681. /* Skip the comment too ... */
  3682. __archive_read_consume(a,
  3683. filename_length + extra_length + comment_length);
  3684. }
  3685. return ARCHIVE_OK;
  3686. }
  3687. static ssize_t
  3688. zip_get_local_file_header_size(struct archive_read *a, size_t extra)
  3689. {
  3690. const char *p;
  3691. ssize_t filename_length, extra_length;
  3692. if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
  3693. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  3694. "Truncated ZIP file header");
  3695. return (ARCHIVE_WARN);
  3696. }
  3697. p += extra;
  3698. if (memcmp(p, "PK\003\004", 4) != 0) {
  3699. archive_set_error(&a->archive, -1, "Damaged Zip archive");
  3700. return ARCHIVE_WARN;
  3701. }
  3702. filename_length = archive_le16dec(p + 26);
  3703. extra_length = archive_le16dec(p + 28);
  3704. return (30 + filename_length + extra_length);
  3705. }
  3706. static int
  3707. zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
  3708. struct zip_entry *rsrc)
  3709. {
  3710. struct zip *zip = (struct zip *)a->format->data;
  3711. unsigned char *metadata, *mp;
  3712. int64_t offset = archive_filter_bytes(&a->archive, 0);
  3713. size_t remaining_bytes, metadata_bytes;
  3714. ssize_t hsize;
  3715. int ret = ARCHIVE_OK, eof;
  3716. switch(rsrc->compression) {
  3717. case 0: /* No compression. */
  3718. if (rsrc->uncompressed_size != rsrc->compressed_size) {
  3719. archive_set_error(&a->archive,
  3720. ARCHIVE_ERRNO_FILE_FORMAT,
  3721. "Malformed OS X metadata entry: "
  3722. "inconsistent size");
  3723. return (ARCHIVE_FATAL);
  3724. }
  3725. #ifdef HAVE_ZLIB_H
  3726. case 8: /* Deflate compression. */
  3727. #endif
  3728. break;
  3729. default: /* Unsupported compression. */
  3730. /* Return a warning. */
  3731. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  3732. "Unsupported ZIP compression method (%s)",
  3733. compression_name(rsrc->compression));
  3734. /* We can't decompress this entry, but we will
  3735. * be able to skip() it and try the next entry. */
  3736. return (ARCHIVE_WARN);
  3737. }
  3738. if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
  3739. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  3740. "Mac metadata is too large: %jd > 4M bytes",
  3741. (intmax_t)rsrc->uncompressed_size);
  3742. return (ARCHIVE_WARN);
  3743. }
  3744. if (rsrc->compressed_size > (4 * 1024 * 1024)) {
  3745. archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
  3746. "Mac metadata is too large: %jd > 4M bytes",
  3747. (intmax_t)rsrc->compressed_size);
  3748. return (ARCHIVE_WARN);
  3749. }
  3750. metadata = malloc((size_t)rsrc->uncompressed_size);
  3751. if (metadata == NULL) {
  3752. archive_set_error(&a->archive, ENOMEM,
  3753. "Can't allocate memory for Mac metadata");
  3754. return (ARCHIVE_FATAL);
  3755. }
  3756. if (offset < rsrc->local_header_offset)
  3757. __archive_read_consume(a, rsrc->local_header_offset - offset);
  3758. else if (offset != rsrc->local_header_offset) {
  3759. __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
  3760. }
  3761. hsize = zip_get_local_file_header_size(a, 0);
  3762. __archive_read_consume(a, hsize);
  3763. remaining_bytes = (size_t)rsrc->compressed_size;
  3764. metadata_bytes = (size_t)rsrc->uncompressed_size;
  3765. mp = metadata;
  3766. eof = 0;
  3767. while (!eof && remaining_bytes) {
  3768. const unsigned char *p;
  3769. ssize_t bytes_avail;
  3770. size_t bytes_used;
  3771. p = __archive_read_ahead(a, 1, &bytes_avail);
  3772. if (p == NULL) {
  3773. archive_set_error(&a->archive,
  3774. ARCHIVE_ERRNO_FILE_FORMAT,
  3775. "Truncated ZIP file header");
  3776. ret = ARCHIVE_WARN;
  3777. goto exit_mac_metadata;
  3778. }
  3779. if ((size_t)bytes_avail > remaining_bytes)
  3780. bytes_avail = remaining_bytes;
  3781. switch(rsrc->compression) {
  3782. case 0: /* No compression. */
  3783. if ((size_t)bytes_avail > metadata_bytes)
  3784. bytes_avail = metadata_bytes;
  3785. memcpy(mp, p, bytes_avail);
  3786. bytes_used = (size_t)bytes_avail;
  3787. metadata_bytes -= bytes_used;
  3788. mp += bytes_used;
  3789. if (metadata_bytes == 0)
  3790. eof = 1;
  3791. break;
  3792. #ifdef HAVE_ZLIB_H
  3793. case 8: /* Deflate compression. */
  3794. {
  3795. int r;
  3796. ret = zip_deflate_init(a, zip);
  3797. if (ret != ARCHIVE_OK)
  3798. goto exit_mac_metadata;
  3799. zip->stream.next_in =
  3800. (Bytef *)(uintptr_t)(const void *)p;
  3801. zip->stream.avail_in = (uInt)bytes_avail;
  3802. zip->stream.total_in = 0;
  3803. zip->stream.next_out = mp;
  3804. zip->stream.avail_out = (uInt)metadata_bytes;
  3805. zip->stream.total_out = 0;
  3806. r = inflate(&zip->stream, 0);
  3807. switch (r) {
  3808. case Z_OK:
  3809. break;
  3810. case Z_STREAM_END:
  3811. eof = 1;
  3812. break;
  3813. case Z_MEM_ERROR:
  3814. archive_set_error(&a->archive, ENOMEM,
  3815. "Out of memory for ZIP decompression");
  3816. ret = ARCHIVE_FATAL;
  3817. goto exit_mac_metadata;
  3818. default:
  3819. archive_set_error(&a->archive,
  3820. ARCHIVE_ERRNO_MISC,
  3821. "ZIP decompression failed (%d)", r);
  3822. ret = ARCHIVE_FATAL;
  3823. goto exit_mac_metadata;
  3824. }
  3825. bytes_used = zip->stream.total_in;
  3826. metadata_bytes -= zip->stream.total_out;
  3827. mp += zip->stream.total_out;
  3828. break;
  3829. }
  3830. #endif
  3831. default:
  3832. bytes_used = 0;
  3833. break;
  3834. }
  3835. __archive_read_consume(a, bytes_used);
  3836. remaining_bytes -= bytes_used;
  3837. }
  3838. archive_entry_copy_mac_metadata(entry, metadata,
  3839. (size_t)rsrc->uncompressed_size - metadata_bytes);
  3840. exit_mac_metadata:
  3841. __archive_read_seek(a, offset, SEEK_SET);
  3842. zip->decompress_init = 0;
  3843. free(metadata);
  3844. return (ret);
  3845. }
  3846. static int
  3847. archive_read_format_zip_seekable_read_header(struct archive_read *a,
  3848. struct archive_entry *entry)
  3849. {
  3850. struct zip *zip = (struct zip *)a->format->data;
  3851. struct zip_entry *rsrc;
  3852. int64_t offset;
  3853. int r, ret = ARCHIVE_OK;
  3854. /*
  3855. * It should be sufficient to call archive_read_next_header() for
  3856. * a reader to determine if an entry is encrypted or not. If the
  3857. * encryption of an entry is only detectable when calling
  3858. * archive_read_data(), so be it. We'll do the same check there
  3859. * as well.
  3860. */
  3861. if (zip->has_encrypted_entries ==
  3862. ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
  3863. zip->has_encrypted_entries = 0;
  3864. a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
  3865. if (a->archive.archive_format_name == NULL)
  3866. a->archive.archive_format_name = "ZIP";
  3867. if (zip->zip_entries == NULL) {
  3868. r = slurp_central_directory(a, entry, zip);
  3869. if (r != ARCHIVE_OK)
  3870. return r;
  3871. /* Get first entry whose local header offset is lower than
  3872. * other entries in the archive file. */
  3873. zip->entry =
  3874. (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
  3875. } else if (zip->entry != NULL) {
  3876. /* Get next entry in local header offset order. */
  3877. zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
  3878. &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
  3879. }
  3880. if (zip->entry == NULL)
  3881. return ARCHIVE_EOF;
  3882. if (zip->entry->rsrcname.s)
  3883. rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
  3884. &zip->tree_rsrc, zip->entry->rsrcname.s);
  3885. else
  3886. rsrc = NULL;
  3887. if (zip->cctx_valid)
  3888. archive_decrypto_aes_ctr_release(&zip->cctx);
  3889. if (zip->hctx_valid)
  3890. archive_hmac_sha1_cleanup(&zip->hctx);
  3891. zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
  3892. __archive_read_reset_passphrase(a);
  3893. /* File entries are sorted by the header offset, we should mostly
  3894. * use __archive_read_consume to advance a read point to avoid
  3895. * redundant data reading. */
  3896. offset = archive_filter_bytes(&a->archive, 0);
  3897. if (offset < zip->entry->local_header_offset)
  3898. __archive_read_consume(a,
  3899. zip->entry->local_header_offset - offset);
  3900. else if (offset != zip->entry->local_header_offset) {
  3901. __archive_read_seek(a, zip->entry->local_header_offset,
  3902. SEEK_SET);
  3903. }
  3904. zip->unconsumed = 0;
  3905. r = zip_read_local_file_header(a, entry, zip);
  3906. if (r != ARCHIVE_OK)
  3907. return r;
  3908. if (rsrc) {
  3909. int ret2 = zip_read_mac_metadata(a, entry, rsrc);
  3910. if (ret2 < ret)
  3911. ret = ret2;
  3912. }
  3913. return (ret);
  3914. }
  3915. /*
  3916. * We're going to seek for the next header anyway, so we don't
  3917. * need to bother doing anything here.
  3918. */
  3919. static int
  3920. archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
  3921. {
  3922. struct zip *zip;
  3923. zip = (struct zip *)(a->format->data);
  3924. zip->unconsumed = 0;
  3925. return (ARCHIVE_OK);
  3926. }
  3927. int
  3928. archive_read_support_format_zip_seekable(struct archive *_a)
  3929. {
  3930. struct archive_read *a = (struct archive_read *)_a;
  3931. struct zip *zip;
  3932. int r;
  3933. archive_check_magic(_a, ARCHIVE_READ_MAGIC,
  3934. ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
  3935. zip = calloc(1, sizeof(*zip));
  3936. if (zip == NULL) {
  3937. archive_set_error(&a->archive, ENOMEM,
  3938. "Can't allocate zip data");
  3939. return (ARCHIVE_FATAL);
  3940. }
  3941. #ifdef HAVE_COPYFILE_H
  3942. /* Set this by default on Mac OS. */
  3943. zip->process_mac_extensions = 1;
  3944. #endif
  3945. /*
  3946. * Until enough data has been read, we cannot tell about
  3947. * any encrypted entries yet.
  3948. */
  3949. zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
  3950. zip->crc32func = real_crc32;
  3951. r = __archive_read_register_format(a,
  3952. zip,
  3953. "zip",
  3954. archive_read_format_zip_seekable_bid,
  3955. archive_read_format_zip_options,
  3956. archive_read_format_zip_seekable_read_header,
  3957. archive_read_format_zip_read_data,
  3958. archive_read_format_zip_read_data_skip_seekable,
  3959. NULL,
  3960. archive_read_format_zip_cleanup,
  3961. archive_read_support_format_zip_capabilities_seekable,
  3962. archive_read_format_zip_has_encrypted_entries);
  3963. if (r != ARCHIVE_OK)
  3964. free(zip);
  3965. return (ARCHIVE_OK);
  3966. }
  3967. /*# vim:set noet:*/