zipfile.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442
  1. """
  2. Read and write ZIP files.
  3. XXX references to utf-8 need further investigation.
  4. """
  5. import binascii
  6. import functools
  7. import importlib.util
  8. import io
  9. import itertools
  10. import os
  11. import posixpath
  12. import shutil
  13. import stat
  14. import struct
  15. import sys
  16. import threading
  17. import time
  18. import contextlib
  19. try:
  20. import zlib # We may need its compression method
  21. crc32 = zlib.crc32
  22. except ImportError:
  23. zlib = None
  24. crc32 = binascii.crc32
  25. try:
  26. import bz2 # We may need its compression method
  27. except ImportError:
  28. bz2 = None
  29. try:
  30. import lzma # We may need its compression method
  31. except ImportError:
  32. lzma = None
  33. __all__ = ["BadZipFile", "BadZipfile", "error",
  34. "ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA",
  35. "is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile",
  36. "Path"]
  37. class BadZipFile(Exception):
  38. pass
  39. class LargeZipFile(Exception):
  40. """
  41. Raised when writing a zipfile, the zipfile requires ZIP64 extensions
  42. and those extensions are disabled.
  43. """
  44. error = BadZipfile = BadZipFile # Pre-3.2 compatibility names
  45. ZIP64_LIMIT = (1 << 31) - 1
  46. ZIP_FILECOUNT_LIMIT = (1 << 16) - 1
  47. ZIP_MAX_COMMENT = (1 << 16) - 1
  48. # constants for Zip file compression methods
  49. ZIP_STORED = 0
  50. ZIP_DEFLATED = 8
  51. ZIP_BZIP2 = 12
  52. ZIP_LZMA = 14
  53. # Other ZIP compression methods not supported
  54. DEFAULT_VERSION = 20
  55. ZIP64_VERSION = 45
  56. BZIP2_VERSION = 46
  57. LZMA_VERSION = 63
  58. # we recognize (but not necessarily support) all features up to that version
  59. MAX_EXTRACT_VERSION = 63
  60. # Below are some formats and associated data for reading/writing headers using
  61. # the struct module. The names and structures of headers/records are those used
  62. # in the PKWARE description of the ZIP file format:
  63. # http://www.pkware.com/documents/casestudies/APPNOTE.TXT
  64. # (URL valid as of January 2008)
  65. # The "end of central directory" structure, magic number, size, and indices
  66. # (section V.I in the format document)
  67. structEndArchive = b"<4s4H2LH"
  68. stringEndArchive = b"PK\005\006"
  69. sizeEndCentDir = struct.calcsize(structEndArchive)
  70. _ECD_SIGNATURE = 0
  71. _ECD_DISK_NUMBER = 1
  72. _ECD_DISK_START = 2
  73. _ECD_ENTRIES_THIS_DISK = 3
  74. _ECD_ENTRIES_TOTAL = 4
  75. _ECD_SIZE = 5
  76. _ECD_OFFSET = 6
  77. _ECD_COMMENT_SIZE = 7
  78. # These last two indices are not part of the structure as defined in the
  79. # spec, but they are used internally by this module as a convenience
  80. _ECD_COMMENT = 8
  81. _ECD_LOCATION = 9
  82. # The "central directory" structure, magic number, size, and indices
  83. # of entries in the structure (section V.F in the format document)
  84. structCentralDir = "<4s4B4HL2L5H2L"
  85. stringCentralDir = b"PK\001\002"
  86. sizeCentralDir = struct.calcsize(structCentralDir)
  87. # indexes of entries in the central directory structure
  88. _CD_SIGNATURE = 0
  89. _CD_CREATE_VERSION = 1
  90. _CD_CREATE_SYSTEM = 2
  91. _CD_EXTRACT_VERSION = 3
  92. _CD_EXTRACT_SYSTEM = 4
  93. _CD_FLAG_BITS = 5
  94. _CD_COMPRESS_TYPE = 6
  95. _CD_TIME = 7
  96. _CD_DATE = 8
  97. _CD_CRC = 9
  98. _CD_COMPRESSED_SIZE = 10
  99. _CD_UNCOMPRESSED_SIZE = 11
  100. _CD_FILENAME_LENGTH = 12
  101. _CD_EXTRA_FIELD_LENGTH = 13
  102. _CD_COMMENT_LENGTH = 14
  103. _CD_DISK_NUMBER_START = 15
  104. _CD_INTERNAL_FILE_ATTRIBUTES = 16
  105. _CD_EXTERNAL_FILE_ATTRIBUTES = 17
  106. _CD_LOCAL_HEADER_OFFSET = 18
  107. # The "local file header" structure, magic number, size, and indices
  108. # (section V.A in the format document)
  109. structFileHeader = "<4s2B4HL2L2H"
  110. stringFileHeader = b"PK\003\004"
  111. sizeFileHeader = struct.calcsize(structFileHeader)
  112. _FH_SIGNATURE = 0
  113. _FH_EXTRACT_VERSION = 1
  114. _FH_EXTRACT_SYSTEM = 2
  115. _FH_GENERAL_PURPOSE_FLAG_BITS = 3
  116. _FH_COMPRESSION_METHOD = 4
  117. _FH_LAST_MOD_TIME = 5
  118. _FH_LAST_MOD_DATE = 6
  119. _FH_CRC = 7
  120. _FH_COMPRESSED_SIZE = 8
  121. _FH_UNCOMPRESSED_SIZE = 9
  122. _FH_FILENAME_LENGTH = 10
  123. _FH_EXTRA_FIELD_LENGTH = 11
  124. # The "Zip64 end of central directory locator" structure, magic number, and size
  125. structEndArchive64Locator = "<4sLQL"
  126. stringEndArchive64Locator = b"PK\x06\x07"
  127. sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
  128. # The "Zip64 end of central directory" record, magic number, size, and indices
  129. # (section V.G in the format document)
  130. structEndArchive64 = "<4sQ2H2L4Q"
  131. stringEndArchive64 = b"PK\x06\x06"
  132. sizeEndCentDir64 = struct.calcsize(structEndArchive64)
  133. _CD64_SIGNATURE = 0
  134. _CD64_DIRECTORY_RECSIZE = 1
  135. _CD64_CREATE_VERSION = 2
  136. _CD64_EXTRACT_VERSION = 3
  137. _CD64_DISK_NUMBER = 4
  138. _CD64_DISK_NUMBER_START = 5
  139. _CD64_NUMBER_ENTRIES_THIS_DISK = 6
  140. _CD64_NUMBER_ENTRIES_TOTAL = 7
  141. _CD64_DIRECTORY_SIZE = 8
  142. _CD64_OFFSET_START_CENTDIR = 9
  143. _DD_SIGNATURE = 0x08074b50
  144. _EXTRA_FIELD_STRUCT = struct.Struct('<HH')
  145. def _strip_extra(extra, xids):
  146. # Remove Extra Fields with specified IDs.
  147. unpack = _EXTRA_FIELD_STRUCT.unpack
  148. modified = False
  149. buffer = []
  150. start = i = 0
  151. while i + 4 <= len(extra):
  152. xid, xlen = unpack(extra[i : i + 4])
  153. j = i + 4 + xlen
  154. if xid in xids:
  155. if i != start:
  156. buffer.append(extra[start : i])
  157. start = j
  158. modified = True
  159. i = j
  160. if not modified:
  161. return extra
  162. return b''.join(buffer)
  163. def _check_zipfile(fp):
  164. try:
  165. if _EndRecData(fp):
  166. return True # file has correct magic number
  167. except OSError:
  168. pass
  169. return False
  170. def is_zipfile(filename):
  171. """Quickly see if a file is a ZIP file by checking the magic number.
  172. The filename argument may be a file or file-like object too.
  173. """
  174. result = False
  175. try:
  176. if hasattr(filename, "read"):
  177. result = _check_zipfile(fp=filename)
  178. else:
  179. with open(filename, "rb") as fp:
  180. result = _check_zipfile(fp)
  181. except OSError:
  182. pass
  183. return result
  184. def _EndRecData64(fpin, offset, endrec):
  185. """
  186. Read the ZIP64 end-of-archive records and use that to update endrec
  187. """
  188. try:
  189. fpin.seek(offset - sizeEndCentDir64Locator, 2)
  190. except OSError:
  191. # If the seek fails, the file is not large enough to contain a ZIP64
  192. # end-of-archive record, so just return the end record we were given.
  193. return endrec
  194. data = fpin.read(sizeEndCentDir64Locator)
  195. if len(data) != sizeEndCentDir64Locator:
  196. return endrec
  197. sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
  198. if sig != stringEndArchive64Locator:
  199. return endrec
  200. if diskno != 0 or disks > 1:
  201. raise BadZipFile("zipfiles that span multiple disks are not supported")
  202. # Assume no 'zip64 extensible data'
  203. fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2)
  204. data = fpin.read(sizeEndCentDir64)
  205. if len(data) != sizeEndCentDir64:
  206. return endrec
  207. sig, sz, create_version, read_version, disk_num, disk_dir, \
  208. dircount, dircount2, dirsize, diroffset = \
  209. struct.unpack(structEndArchive64, data)
  210. if sig != stringEndArchive64:
  211. return endrec
  212. # Update the original endrec using data from the ZIP64 record
  213. endrec[_ECD_SIGNATURE] = sig
  214. endrec[_ECD_DISK_NUMBER] = disk_num
  215. endrec[_ECD_DISK_START] = disk_dir
  216. endrec[_ECD_ENTRIES_THIS_DISK] = dircount
  217. endrec[_ECD_ENTRIES_TOTAL] = dircount2
  218. endrec[_ECD_SIZE] = dirsize
  219. endrec[_ECD_OFFSET] = diroffset
  220. return endrec
  221. def _EndRecData(fpin):
  222. """Return data from the "End of Central Directory" record, or None.
  223. The data is a list of the nine items in the ZIP "End of central dir"
  224. record followed by a tenth item, the file seek offset of this record."""
  225. # Determine file size
  226. fpin.seek(0, 2)
  227. filesize = fpin.tell()
  228. # Check to see if this is ZIP file with no archive comment (the
  229. # "end of central directory" structure should be the last item in the
  230. # file if this is the case).
  231. try:
  232. fpin.seek(-sizeEndCentDir, 2)
  233. except OSError:
  234. return None
  235. data = fpin.read()
  236. if (len(data) == sizeEndCentDir and
  237. data[0:4] == stringEndArchive and
  238. data[-2:] == b"\000\000"):
  239. # the signature is correct and there's no comment, unpack structure
  240. endrec = struct.unpack(structEndArchive, data)
  241. endrec=list(endrec)
  242. # Append a blank comment and record start offset
  243. endrec.append(b"")
  244. endrec.append(filesize - sizeEndCentDir)
  245. # Try to read the "Zip64 end of central directory" structure
  246. return _EndRecData64(fpin, -sizeEndCentDir, endrec)
  247. # Either this is not a ZIP file, or it is a ZIP file with an archive
  248. # comment. Search the end of the file for the "end of central directory"
  249. # record signature. The comment is the last item in the ZIP file and may be
  250. # up to 64K long. It is assumed that the "end of central directory" magic
  251. # number does not appear in the comment.
  252. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
  253. fpin.seek(maxCommentStart, 0)
  254. data = fpin.read()
  255. start = data.rfind(stringEndArchive)
  256. if start >= 0:
  257. # found the magic number; attempt to unpack and interpret
  258. recData = data[start:start+sizeEndCentDir]
  259. if len(recData) != sizeEndCentDir:
  260. # Zip file is corrupted.
  261. return None
  262. endrec = list(struct.unpack(structEndArchive, recData))
  263. commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
  264. comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
  265. endrec.append(comment)
  266. endrec.append(maxCommentStart + start)
  267. # Try to read the "Zip64 end of central directory" structure
  268. return _EndRecData64(fpin, maxCommentStart + start - filesize,
  269. endrec)
  270. # Unable to find a valid end of central directory structure
  271. return None
  272. class ZipInfo (object):
  273. """Class with attributes describing each file in the ZIP archive."""
  274. __slots__ = (
  275. 'orig_filename',
  276. 'filename',
  277. 'date_time',
  278. 'compress_type',
  279. '_compresslevel',
  280. 'comment',
  281. 'extra',
  282. 'create_system',
  283. 'create_version',
  284. 'extract_version',
  285. 'reserved',
  286. 'flag_bits',
  287. 'volume',
  288. 'internal_attr',
  289. 'external_attr',
  290. 'header_offset',
  291. 'CRC',
  292. 'compress_size',
  293. 'file_size',
  294. '_raw_time',
  295. )
  296. def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
  297. self.orig_filename = filename # Original file name in archive
  298. # Terminate the file name at the first null byte. Null bytes in file
  299. # names are used as tricks by viruses in archives.
  300. null_byte = filename.find(chr(0))
  301. if null_byte >= 0:
  302. filename = filename[0:null_byte]
  303. # This is used to ensure paths in generated ZIP files always use
  304. # forward slashes as the directory separator, as required by the
  305. # ZIP format specification.
  306. if os.sep != "/" and os.sep in filename:
  307. filename = filename.replace(os.sep, "/")
  308. self.filename = filename # Normalized file name
  309. self.date_time = date_time # year, month, day, hour, min, sec
  310. if date_time[0] < 1980:
  311. raise ValueError('ZIP does not support timestamps before 1980')
  312. # Standard values:
  313. self.compress_type = ZIP_STORED # Type of compression for the file
  314. self._compresslevel = None # Level for the compressor
  315. self.comment = b"" # Comment for each file
  316. self.extra = b"" # ZIP extra data
  317. if sys.platform == 'win32':
  318. self.create_system = 0 # System which created ZIP archive
  319. else:
  320. # Assume everything else is unix-y
  321. self.create_system = 3 # System which created ZIP archive
  322. self.create_version = DEFAULT_VERSION # Version which created ZIP archive
  323. self.extract_version = DEFAULT_VERSION # Version needed to extract archive
  324. self.reserved = 0 # Must be zero
  325. self.flag_bits = 0 # ZIP flag bits
  326. self.volume = 0 # Volume number of file header
  327. self.internal_attr = 0 # Internal attributes
  328. self.external_attr = 0 # External file attributes
  329. # Other attributes are set by class ZipFile:
  330. # header_offset Byte offset to the file header
  331. # CRC CRC-32 of the uncompressed file
  332. # compress_size Size of the compressed file
  333. # file_size Size of the uncompressed file
  334. def __repr__(self):
  335. result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)]
  336. if self.compress_type != ZIP_STORED:
  337. result.append(' compress_type=%s' %
  338. compressor_names.get(self.compress_type,
  339. self.compress_type))
  340. hi = self.external_attr >> 16
  341. lo = self.external_attr & 0xFFFF
  342. if hi:
  343. result.append(' filemode=%r' % stat.filemode(hi))
  344. if lo:
  345. result.append(' external_attr=%#x' % lo)
  346. isdir = self.is_dir()
  347. if not isdir or self.file_size:
  348. result.append(' file_size=%r' % self.file_size)
  349. if ((not isdir or self.compress_size) and
  350. (self.compress_type != ZIP_STORED or
  351. self.file_size != self.compress_size)):
  352. result.append(' compress_size=%r' % self.compress_size)
  353. result.append('>')
  354. return ''.join(result)
  355. def FileHeader(self, zip64=None):
  356. """Return the per-file header as a bytes object."""
  357. dt = self.date_time
  358. dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
  359. dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
  360. if self.flag_bits & 0x08:
  361. # Set these to zero because we write them after the file data
  362. CRC = compress_size = file_size = 0
  363. else:
  364. CRC = self.CRC
  365. compress_size = self.compress_size
  366. file_size = self.file_size
  367. extra = self.extra
  368. min_version = 0
  369. if zip64 is None:
  370. zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT
  371. if zip64:
  372. fmt = '<HHQQ'
  373. extra = extra + struct.pack(fmt,
  374. 1, struct.calcsize(fmt)-4, file_size, compress_size)
  375. if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
  376. if not zip64:
  377. raise LargeZipFile("Filesize would require ZIP64 extensions")
  378. # File is larger than what fits into a 4 byte integer,
  379. # fall back to the ZIP64 extension
  380. file_size = 0xffffffff
  381. compress_size = 0xffffffff
  382. min_version = ZIP64_VERSION
  383. if self.compress_type == ZIP_BZIP2:
  384. min_version = max(BZIP2_VERSION, min_version)
  385. elif self.compress_type == ZIP_LZMA:
  386. min_version = max(LZMA_VERSION, min_version)
  387. self.extract_version = max(min_version, self.extract_version)
  388. self.create_version = max(min_version, self.create_version)
  389. filename, flag_bits = self._encodeFilenameFlags()
  390. header = struct.pack(structFileHeader, stringFileHeader,
  391. self.extract_version, self.reserved, flag_bits,
  392. self.compress_type, dostime, dosdate, CRC,
  393. compress_size, file_size,
  394. len(filename), len(extra))
  395. return header + filename + extra
  396. def _encodeFilenameFlags(self):
  397. try:
  398. return self.filename.encode('ascii'), self.flag_bits
  399. except UnicodeEncodeError:
  400. return self.filename.encode('utf-8'), self.flag_bits | 0x800
  401. def _decodeExtra(self):
  402. # Try to decode the extra field.
  403. extra = self.extra
  404. unpack = struct.unpack
  405. while len(extra) >= 4:
  406. tp, ln = unpack('<HH', extra[:4])
  407. if ln+4 > len(extra):
  408. raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln))
  409. if tp == 0x0001:
  410. if ln >= 24:
  411. counts = unpack('<QQQ', extra[4:28])
  412. elif ln == 16:
  413. counts = unpack('<QQ', extra[4:20])
  414. elif ln == 8:
  415. counts = unpack('<Q', extra[4:12])
  416. elif ln == 0:
  417. counts = ()
  418. else:
  419. raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln))
  420. idx = 0
  421. # ZIP64 extension (large files and/or large archives)
  422. if self.file_size in (0xffffffffffffffff, 0xffffffff):
  423. if len(counts) <= idx:
  424. raise BadZipFile(
  425. "Corrupt zip64 extra field. File size not found."
  426. )
  427. self.file_size = counts[idx]
  428. idx += 1
  429. if self.compress_size == 0xFFFFFFFF:
  430. if len(counts) <= idx:
  431. raise BadZipFile(
  432. "Corrupt zip64 extra field. Compress size not found."
  433. )
  434. self.compress_size = counts[idx]
  435. idx += 1
  436. if self.header_offset == 0xffffffff:
  437. if len(counts) <= idx:
  438. raise BadZipFile(
  439. "Corrupt zip64 extra field. Header offset not found."
  440. )
  441. old = self.header_offset
  442. self.header_offset = counts[idx]
  443. idx+=1
  444. extra = extra[ln+4:]
  445. @classmethod
  446. def from_file(cls, filename, arcname=None, *, strict_timestamps=True):
  447. """Construct an appropriate ZipInfo for a file on the filesystem.
  448. filename should be the path to a file or directory on the filesystem.
  449. arcname is the name which it will have within the archive (by default,
  450. this will be the same as filename, but without a drive letter and with
  451. leading path separators removed).
  452. """
  453. if isinstance(filename, os.PathLike):
  454. filename = os.fspath(filename)
  455. st = os.stat(filename)
  456. isdir = stat.S_ISDIR(st.st_mode)
  457. mtime = time.localtime(st.st_mtime)
  458. date_time = mtime[0:6]
  459. if not strict_timestamps and date_time[0] < 1980:
  460. date_time = (1980, 1, 1, 0, 0, 0)
  461. elif not strict_timestamps and date_time[0] > 2107:
  462. date_time = (2107, 12, 31, 23, 59, 59)
  463. # Create ZipInfo instance to store file information
  464. if arcname is None:
  465. arcname = filename
  466. arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
  467. while arcname[0] in (os.sep, os.altsep):
  468. arcname = arcname[1:]
  469. if isdir:
  470. arcname += '/'
  471. zinfo = cls(arcname, date_time)
  472. zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes
  473. if isdir:
  474. zinfo.file_size = 0
  475. zinfo.external_attr |= 0x10 # MS-DOS directory flag
  476. else:
  477. zinfo.file_size = st.st_size
  478. return zinfo
  479. def is_dir(self):
  480. """Return True if this archive member is a directory."""
  481. return self.filename[-1] == '/'
  482. # ZIP encryption uses the CRC32 one-byte primitive for scrambling some
  483. # internal keys. We noticed that a direct implementation is faster than
  484. # relying on binascii.crc32().
  485. _crctable = None
  486. def _gen_crc(crc):
  487. for j in range(8):
  488. if crc & 1:
  489. crc = (crc >> 1) ^ 0xEDB88320
  490. else:
  491. crc >>= 1
  492. return crc
  493. # ZIP supports a password-based form of encryption. Even though known
  494. # plaintext attacks have been found against it, it is still useful
  495. # to be able to get data out of such a file.
  496. #
  497. # Usage:
  498. # zd = _ZipDecrypter(mypwd)
  499. # plain_bytes = zd(cypher_bytes)
  500. def _ZipDecrypter(pwd):
  501. key0 = 305419896
  502. key1 = 591751049
  503. key2 = 878082192
  504. global _crctable
  505. if _crctable is None:
  506. _crctable = list(map(_gen_crc, range(256)))
  507. crctable = _crctable
  508. def crc32(ch, crc):
  509. """Compute the CRC32 primitive on one byte."""
  510. return (crc >> 8) ^ crctable[(crc ^ ch) & 0xFF]
  511. def update_keys(c):
  512. nonlocal key0, key1, key2
  513. key0 = crc32(c, key0)
  514. key1 = (key1 + (key0 & 0xFF)) & 0xFFFFFFFF
  515. key1 = (key1 * 134775813 + 1) & 0xFFFFFFFF
  516. key2 = crc32(key1 >> 24, key2)
  517. for p in pwd:
  518. update_keys(p)
  519. def decrypter(data):
  520. """Decrypt a bytes object."""
  521. result = bytearray()
  522. append = result.append
  523. for c in data:
  524. k = key2 | 2
  525. c ^= ((k * (k^1)) >> 8) & 0xFF
  526. update_keys(c)
  527. append(c)
  528. return bytes(result)
  529. return decrypter
  530. class LZMACompressor:
  531. def __init__(self):
  532. self._comp = None
  533. def _init(self):
  534. props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1})
  535. self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[
  536. lzma._decode_filter_properties(lzma.FILTER_LZMA1, props)
  537. ])
  538. return struct.pack('<BBH', 9, 4, len(props)) + props
  539. def compress(self, data):
  540. if self._comp is None:
  541. return self._init() + self._comp.compress(data)
  542. return self._comp.compress(data)
  543. def flush(self):
  544. if self._comp is None:
  545. return self._init() + self._comp.flush()
  546. return self._comp.flush()
  547. class LZMADecompressor:
  548. def __init__(self):
  549. self._decomp = None
  550. self._unconsumed = b''
  551. self.eof = False
  552. def decompress(self, data):
  553. if self._decomp is None:
  554. self._unconsumed += data
  555. if len(self._unconsumed) <= 4:
  556. return b''
  557. psize, = struct.unpack('<H', self._unconsumed[2:4])
  558. if len(self._unconsumed) <= 4 + psize:
  559. return b''
  560. self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[
  561. lzma._decode_filter_properties(lzma.FILTER_LZMA1,
  562. self._unconsumed[4:4 + psize])
  563. ])
  564. data = self._unconsumed[4 + psize:]
  565. del self._unconsumed
  566. result = self._decomp.decompress(data)
  567. self.eof = self._decomp.eof
  568. return result
  569. compressor_names = {
  570. 0: 'store',
  571. 1: 'shrink',
  572. 2: 'reduce',
  573. 3: 'reduce',
  574. 4: 'reduce',
  575. 5: 'reduce',
  576. 6: 'implode',
  577. 7: 'tokenize',
  578. 8: 'deflate',
  579. 9: 'deflate64',
  580. 10: 'implode',
  581. 12: 'bzip2',
  582. 14: 'lzma',
  583. 18: 'terse',
  584. 19: 'lz77',
  585. 97: 'wavpack',
  586. 98: 'ppmd',
  587. }
  588. def _check_compression(compression):
  589. if compression == ZIP_STORED:
  590. pass
  591. elif compression == ZIP_DEFLATED:
  592. if not zlib:
  593. raise RuntimeError(
  594. "Compression requires the (missing) zlib module")
  595. elif compression == ZIP_BZIP2:
  596. if not bz2:
  597. raise RuntimeError(
  598. "Compression requires the (missing) bz2 module")
  599. elif compression == ZIP_LZMA:
  600. if not lzma:
  601. raise RuntimeError(
  602. "Compression requires the (missing) lzma module")
  603. else:
  604. raise NotImplementedError("That compression method is not supported")
  605. def _get_compressor(compress_type, compresslevel=None):
  606. if compress_type == ZIP_DEFLATED:
  607. if compresslevel is not None:
  608. return zlib.compressobj(compresslevel, zlib.DEFLATED, -15)
  609. return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
  610. elif compress_type == ZIP_BZIP2:
  611. if compresslevel is not None:
  612. return bz2.BZ2Compressor(compresslevel)
  613. return bz2.BZ2Compressor()
  614. # compresslevel is ignored for ZIP_LZMA
  615. elif compress_type == ZIP_LZMA:
  616. return LZMACompressor()
  617. else:
  618. return None
  619. def _get_decompressor(compress_type):
  620. _check_compression(compress_type)
  621. if compress_type == ZIP_STORED:
  622. return None
  623. elif compress_type == ZIP_DEFLATED:
  624. return zlib.decompressobj(-15)
  625. elif compress_type == ZIP_BZIP2:
  626. return bz2.BZ2Decompressor()
  627. elif compress_type == ZIP_LZMA:
  628. return LZMADecompressor()
  629. else:
  630. descr = compressor_names.get(compress_type)
  631. if descr:
  632. raise NotImplementedError("compression type %d (%s)" % (compress_type, descr))
  633. else:
  634. raise NotImplementedError("compression type %d" % (compress_type,))
  635. class _SharedFile:
  636. def __init__(self, file, pos, close, lock, writing):
  637. self._file = file
  638. self._pos = pos
  639. self._close = close
  640. self._lock = lock
  641. self._writing = writing
  642. self.seekable = file.seekable
  643. self.tell = file.tell
  644. def seek(self, offset, whence=0):
  645. with self._lock:
  646. if self._writing():
  647. raise ValueError("Can't reposition in the ZIP file while "
  648. "there is an open writing handle on it. "
  649. "Close the writing handle before trying to read.")
  650. self._file.seek(offset, whence)
  651. self._pos = self._file.tell()
  652. return self._pos
  653. def read(self, n=-1):
  654. with self._lock:
  655. if self._writing():
  656. raise ValueError("Can't read from the ZIP file while there "
  657. "is an open writing handle on it. "
  658. "Close the writing handle before trying to read.")
  659. self._file.seek(self._pos)
  660. data = self._file.read(n)
  661. self._pos = self._file.tell()
  662. return data
  663. def close(self):
  664. if self._file is not None:
  665. fileobj = self._file
  666. self._file = None
  667. self._close(fileobj)
  668. # Provide the tell method for unseekable stream
  669. class _Tellable:
  670. def __init__(self, fp):
  671. self.fp = fp
  672. self.offset = 0
  673. def write(self, data):
  674. n = self.fp.write(data)
  675. self.offset += n
  676. return n
  677. def tell(self):
  678. return self.offset
  679. def flush(self):
  680. self.fp.flush()
  681. def close(self):
  682. self.fp.close()
  683. class ZipExtFile(io.BufferedIOBase):
  684. """File-like object for reading an archive member.
  685. Is returned by ZipFile.open().
  686. """
  687. # Max size supported by decompressor.
  688. MAX_N = 1 << 31 - 1
  689. # Read from compressed files in 4k blocks.
  690. MIN_READ_SIZE = 4096
  691. # Chunk size to read during seek
  692. MAX_SEEK_READ = 1 << 24
  693. def __init__(self, fileobj, mode, zipinfo, pwd=None,
  694. close_fileobj=False):
  695. self._fileobj = fileobj
  696. self._pwd = pwd
  697. self._close_fileobj = close_fileobj
  698. self._compress_type = zipinfo.compress_type
  699. self._compress_left = zipinfo.compress_size
  700. self._left = zipinfo.file_size
  701. self._decompressor = _get_decompressor(self._compress_type)
  702. self._eof = False
  703. self._readbuffer = b''
  704. self._offset = 0
  705. self.newlines = None
  706. self.mode = mode
  707. self.name = zipinfo.filename
  708. if hasattr(zipinfo, 'CRC'):
  709. self._expected_crc = zipinfo.CRC
  710. self._running_crc = crc32(b'')
  711. else:
  712. self._expected_crc = None
  713. self._seekable = False
  714. try:
  715. if fileobj.seekable():
  716. self._orig_compress_start = fileobj.tell()
  717. self._orig_compress_size = zipinfo.compress_size
  718. self._orig_file_size = zipinfo.file_size
  719. self._orig_start_crc = self._running_crc
  720. self._seekable = True
  721. except AttributeError:
  722. pass
  723. self._decrypter = None
  724. if pwd:
  725. if zipinfo.flag_bits & 0x8:
  726. # compare against the file type from extended local headers
  727. check_byte = (zipinfo._raw_time >> 8) & 0xff
  728. else:
  729. # compare against the CRC otherwise
  730. check_byte = (zipinfo.CRC >> 24) & 0xff
  731. h = self._init_decrypter()
  732. if h != check_byte:
  733. raise RuntimeError("Bad password for file %r" % zipinfo.orig_filename)
  734. def _init_decrypter(self):
  735. self._decrypter = _ZipDecrypter(self._pwd)
  736. # The first 12 bytes in the cypher stream is an encryption header
  737. # used to strengthen the algorithm. The first 11 bytes are
  738. # completely random, while the 12th contains the MSB of the CRC,
  739. # or the MSB of the file time depending on the header type
  740. # and is used to check the correctness of the password.
  741. header = self._fileobj.read(12)
  742. self._compress_left -= 12
  743. return self._decrypter(header)[11]
  744. def __repr__(self):
  745. result = ['<%s.%s' % (self.__class__.__module__,
  746. self.__class__.__qualname__)]
  747. if not self.closed:
  748. result.append(' name=%r mode=%r' % (self.name, self.mode))
  749. if self._compress_type != ZIP_STORED:
  750. result.append(' compress_type=%s' %
  751. compressor_names.get(self._compress_type,
  752. self._compress_type))
  753. else:
  754. result.append(' [closed]')
  755. result.append('>')
  756. return ''.join(result)
  757. def readline(self, limit=-1):
  758. """Read and return a line from the stream.
  759. If limit is specified, at most limit bytes will be read.
  760. """
  761. if limit < 0:
  762. # Shortcut common case - newline found in buffer.
  763. i = self._readbuffer.find(b'\n', self._offset) + 1
  764. if i > 0:
  765. line = self._readbuffer[self._offset: i]
  766. self._offset = i
  767. return line
  768. return io.BufferedIOBase.readline(self, limit)
  769. def peek(self, n=1):
  770. """Returns buffered bytes without advancing the position."""
  771. if n > len(self._readbuffer) - self._offset:
  772. chunk = self.read(n)
  773. if len(chunk) > self._offset:
  774. self._readbuffer = chunk + self._readbuffer[self._offset:]
  775. self._offset = 0
  776. else:
  777. self._offset -= len(chunk)
  778. # Return up to 512 bytes to reduce allocation overhead for tight loops.
  779. return self._readbuffer[self._offset: self._offset + 512]
  780. def readable(self):
  781. return True
  782. def read(self, n=-1):
  783. """Read and return up to n bytes.
  784. If the argument is omitted, None, or negative, data is read and returned until EOF is reached.
  785. """
  786. if n is None or n < 0:
  787. buf = self._readbuffer[self._offset:]
  788. self._readbuffer = b''
  789. self._offset = 0
  790. while not self._eof:
  791. buf += self._read1(self.MAX_N)
  792. return buf
  793. end = n + self._offset
  794. if end < len(self._readbuffer):
  795. buf = self._readbuffer[self._offset:end]
  796. self._offset = end
  797. return buf
  798. n = end - len(self._readbuffer)
  799. buf = self._readbuffer[self._offset:]
  800. self._readbuffer = b''
  801. self._offset = 0
  802. while n > 0 and not self._eof:
  803. data = self._read1(n)
  804. if n < len(data):
  805. self._readbuffer = data
  806. self._offset = n
  807. buf += data[:n]
  808. break
  809. buf += data
  810. n -= len(data)
  811. return buf
  812. def _update_crc(self, newdata):
  813. # Update the CRC using the given data.
  814. if self._expected_crc is None:
  815. # No need to compute the CRC if we don't have a reference value
  816. return
  817. self._running_crc = crc32(newdata, self._running_crc)
  818. # Check the CRC if we're at the end of the file
  819. if self._eof and self._running_crc != self._expected_crc:
  820. raise BadZipFile("Bad CRC-32 for file %r" % self.name)
  821. def read1(self, n):
  822. """Read up to n bytes with at most one read() system call."""
  823. if n is None or n < 0:
  824. buf = self._readbuffer[self._offset:]
  825. self._readbuffer = b''
  826. self._offset = 0
  827. while not self._eof:
  828. data = self._read1(self.MAX_N)
  829. if data:
  830. buf += data
  831. break
  832. return buf
  833. end = n + self._offset
  834. if end < len(self._readbuffer):
  835. buf = self._readbuffer[self._offset:end]
  836. self._offset = end
  837. return buf
  838. n = end - len(self._readbuffer)
  839. buf = self._readbuffer[self._offset:]
  840. self._readbuffer = b''
  841. self._offset = 0
  842. if n > 0:
  843. while not self._eof:
  844. data = self._read1(n)
  845. if n < len(data):
  846. self._readbuffer = data
  847. self._offset = n
  848. buf += data[:n]
  849. break
  850. if data:
  851. buf += data
  852. break
  853. return buf
  854. def _read1(self, n):
  855. # Read up to n compressed bytes with at most one read() system call,
  856. # decrypt and decompress them.
  857. if self._eof or n <= 0:
  858. return b''
  859. # Read from file.
  860. if self._compress_type == ZIP_DEFLATED:
  861. ## Handle unconsumed data.
  862. data = self._decompressor.unconsumed_tail
  863. if n > len(data):
  864. data += self._read2(n - len(data))
  865. else:
  866. data = self._read2(n)
  867. if self._compress_type == ZIP_STORED:
  868. self._eof = self._compress_left <= 0
  869. elif self._compress_type == ZIP_DEFLATED:
  870. n = max(n, self.MIN_READ_SIZE)
  871. data = self._decompressor.decompress(data, n)
  872. self._eof = (self._decompressor.eof or
  873. self._compress_left <= 0 and
  874. not self._decompressor.unconsumed_tail)
  875. if self._eof:
  876. data += self._decompressor.flush()
  877. else:
  878. data = self._decompressor.decompress(data)
  879. self._eof = self._decompressor.eof or self._compress_left <= 0
  880. data = data[:self._left]
  881. self._left -= len(data)
  882. if self._left <= 0:
  883. self._eof = True
  884. self._update_crc(data)
  885. return data
  886. def _read2(self, n):
  887. if self._compress_left <= 0:
  888. return b''
  889. n = max(n, self.MIN_READ_SIZE)
  890. n = min(n, self._compress_left)
  891. data = self._fileobj.read(n)
  892. self._compress_left -= len(data)
  893. if not data:
  894. raise EOFError
  895. if self._decrypter is not None:
  896. data = self._decrypter(data)
  897. return data
  898. def close(self):
  899. try:
  900. if self._close_fileobj:
  901. self._fileobj.close()
  902. finally:
  903. super().close()
  904. def seekable(self):
  905. return self._seekable
  906. def seek(self, offset, whence=0):
  907. if not self._seekable:
  908. raise io.UnsupportedOperation("underlying stream is not seekable")
  909. curr_pos = self.tell()
  910. if whence == 0: # Seek from start of file
  911. new_pos = offset
  912. elif whence == 1: # Seek from current position
  913. new_pos = curr_pos + offset
  914. elif whence == 2: # Seek from EOF
  915. new_pos = self._orig_file_size + offset
  916. else:
  917. raise ValueError("whence must be os.SEEK_SET (0), "
  918. "os.SEEK_CUR (1), or os.SEEK_END (2)")
  919. if new_pos > self._orig_file_size:
  920. new_pos = self._orig_file_size
  921. if new_pos < 0:
  922. new_pos = 0
  923. read_offset = new_pos - curr_pos
  924. buff_offset = read_offset + self._offset
  925. if buff_offset >= 0 and buff_offset < len(self._readbuffer):
  926. # Just move the _offset index if the new position is in the _readbuffer
  927. self._offset = buff_offset
  928. read_offset = 0
  929. elif read_offset < 0:
  930. # Position is before the current position. Reset the ZipExtFile
  931. self._fileobj.seek(self._orig_compress_start)
  932. self._running_crc = self._orig_start_crc
  933. self._compress_left = self._orig_compress_size
  934. self._left = self._orig_file_size
  935. self._readbuffer = b''
  936. self._offset = 0
  937. self._decompressor = _get_decompressor(self._compress_type)
  938. self._eof = False
  939. read_offset = new_pos
  940. if self._decrypter is not None:
  941. self._init_decrypter()
  942. while read_offset > 0:
  943. read_len = min(self.MAX_SEEK_READ, read_offset)
  944. self.read(read_len)
  945. read_offset -= read_len
  946. return self.tell()
  947. def tell(self):
  948. if not self._seekable:
  949. raise io.UnsupportedOperation("underlying stream is not seekable")
  950. filepos = self._orig_file_size - self._left - len(self._readbuffer) + self._offset
  951. return filepos
  952. class _ZipWriteFile(io.BufferedIOBase):
  953. def __init__(self, zf, zinfo, zip64):
  954. self._zinfo = zinfo
  955. self._zip64 = zip64
  956. self._zipfile = zf
  957. self._compressor = _get_compressor(zinfo.compress_type,
  958. zinfo._compresslevel)
  959. self._file_size = 0
  960. self._compress_size = 0
  961. self._crc = 0
  962. @property
  963. def _fileobj(self):
  964. return self._zipfile.fp
  965. def writable(self):
  966. return True
  967. def write(self, data):
  968. if self.closed:
  969. raise ValueError('I/O operation on closed file.')
  970. nbytes = len(data)
  971. self._file_size += nbytes
  972. self._crc = crc32(data, self._crc)
  973. if self._compressor:
  974. data = self._compressor.compress(data)
  975. self._compress_size += len(data)
  976. self._fileobj.write(data)
  977. return nbytes
  978. def close(self):
  979. if self.closed:
  980. return
  981. try:
  982. super().close()
  983. # Flush any data from the compressor, and update header info
  984. if self._compressor:
  985. buf = self._compressor.flush()
  986. self._compress_size += len(buf)
  987. self._fileobj.write(buf)
  988. self._zinfo.compress_size = self._compress_size
  989. else:
  990. self._zinfo.compress_size = self._file_size
  991. self._zinfo.CRC = self._crc
  992. self._zinfo.file_size = self._file_size
  993. # Write updated header info
  994. if self._zinfo.flag_bits & 0x08:
  995. # Write CRC and file sizes after the file data
  996. fmt = '<LLQQ' if self._zip64 else '<LLLL'
  997. self._fileobj.write(struct.pack(fmt, _DD_SIGNATURE, self._zinfo.CRC,
  998. self._zinfo.compress_size, self._zinfo.file_size))
  999. self._zipfile.start_dir = self._fileobj.tell()
  1000. else:
  1001. if not self._zip64:
  1002. if self._file_size > ZIP64_LIMIT:
  1003. raise RuntimeError(
  1004. 'File size unexpectedly exceeded ZIP64 limit')
  1005. if self._compress_size > ZIP64_LIMIT:
  1006. raise RuntimeError(
  1007. 'Compressed size unexpectedly exceeded ZIP64 limit')
  1008. # Seek backwards and write file header (which will now include
  1009. # correct CRC and file sizes)
  1010. # Preserve current position in file
  1011. self._zipfile.start_dir = self._fileobj.tell()
  1012. self._fileobj.seek(self._zinfo.header_offset)
  1013. self._fileobj.write(self._zinfo.FileHeader(self._zip64))
  1014. self._fileobj.seek(self._zipfile.start_dir)
  1015. # Successfully written: Add file to our caches
  1016. self._zipfile.filelist.append(self._zinfo)
  1017. self._zipfile.NameToInfo[self._zinfo.filename] = self._zinfo
  1018. finally:
  1019. self._zipfile._writing = False
  1020. class ZipFile:
  1021. """ Class with methods to open, read, write, close, list zip files.
  1022. z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True,
  1023. compresslevel=None)
  1024. file: Either the path to the file, or a file-like object.
  1025. If it is a path, the file will be opened and closed by ZipFile.
  1026. mode: The mode can be either read 'r', write 'w', exclusive create 'x',
  1027. or append 'a'.
  1028. compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib),
  1029. ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma).
  1030. allowZip64: if True ZipFile will create files with ZIP64 extensions when
  1031. needed, otherwise it will raise an exception when this would
  1032. be necessary.
  1033. compresslevel: None (default for the given compression type) or an integer
  1034. specifying the level to pass to the compressor.
  1035. When using ZIP_STORED or ZIP_LZMA this keyword has no effect.
  1036. When using ZIP_DEFLATED integers 0 through 9 are accepted.
  1037. When using ZIP_BZIP2 integers 1 through 9 are accepted.
  1038. """
  1039. fp = None # Set here since __del__ checks it
  1040. _windows_illegal_name_trans_table = None
  1041. def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
  1042. compresslevel=None, *, strict_timestamps=True):
  1043. """Open the ZIP file with mode read 'r', write 'w', exclusive create 'x',
  1044. or append 'a'."""
  1045. if mode not in ('r', 'w', 'x', 'a'):
  1046. raise ValueError("ZipFile requires mode 'r', 'w', 'x', or 'a'")
  1047. _check_compression(compression)
  1048. self._allowZip64 = allowZip64
  1049. self._didModify = False
  1050. self.debug = 0 # Level of printing: 0 through 3
  1051. self.NameToInfo = {} # Find file info given name
  1052. self.filelist = [] # List of ZipInfo instances for archive
  1053. self.compression = compression # Method of compression
  1054. self.compresslevel = compresslevel
  1055. self.mode = mode
  1056. self.pwd = None
  1057. self._comment = b''
  1058. self._strict_timestamps = strict_timestamps
  1059. # Check if we were passed a file-like object
  1060. if isinstance(file, os.PathLike):
  1061. file = os.fspath(file)
  1062. if isinstance(file, str):
  1063. # No, it's a filename
  1064. self._filePassed = 0
  1065. self.filename = file
  1066. modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b',
  1067. 'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'}
  1068. filemode = modeDict[mode]
  1069. while True:
  1070. try:
  1071. self.fp = io.open(file, filemode)
  1072. except OSError:
  1073. if filemode in modeDict:
  1074. filemode = modeDict[filemode]
  1075. continue
  1076. raise
  1077. break
  1078. else:
  1079. self._filePassed = 1
  1080. self.fp = file
  1081. self.filename = getattr(file, 'name', None)
  1082. self._fileRefCnt = 1
  1083. self._lock = threading.RLock()
  1084. self._seekable = True
  1085. self._writing = False
  1086. try:
  1087. if mode == 'r':
  1088. self._RealGetContents()
  1089. elif mode in ('w', 'x'):
  1090. # set the modified flag so central directory gets written
  1091. # even if no files are added to the archive
  1092. self._didModify = True
  1093. try:
  1094. self.start_dir = self.fp.tell()
  1095. except (AttributeError, OSError):
  1096. self.fp = _Tellable(self.fp)
  1097. self.start_dir = 0
  1098. self._seekable = False
  1099. else:
  1100. # Some file-like objects can provide tell() but not seek()
  1101. try:
  1102. self.fp.seek(self.start_dir)
  1103. except (AttributeError, OSError):
  1104. self._seekable = False
  1105. elif mode == 'a':
  1106. try:
  1107. # See if file is a zip file
  1108. self._RealGetContents()
  1109. # seek to start of directory and overwrite
  1110. self.fp.seek(self.start_dir)
  1111. except BadZipFile:
  1112. # file is not a zip file, just append
  1113. self.fp.seek(0, 2)
  1114. # set the modified flag so central directory gets written
  1115. # even if no files are added to the archive
  1116. self._didModify = True
  1117. self.start_dir = self.fp.tell()
  1118. else:
  1119. raise ValueError("Mode must be 'r', 'w', 'x', or 'a'")
  1120. except:
  1121. fp = self.fp
  1122. self.fp = None
  1123. self._fpclose(fp)
  1124. raise
  1125. def __enter__(self):
  1126. return self
  1127. def __exit__(self, type, value, traceback):
  1128. self.close()
  1129. def __repr__(self):
  1130. result = ['<%s.%s' % (self.__class__.__module__,
  1131. self.__class__.__qualname__)]
  1132. if self.fp is not None:
  1133. if self._filePassed:
  1134. result.append(' file=%r' % self.fp)
  1135. elif self.filename is not None:
  1136. result.append(' filename=%r' % self.filename)
  1137. result.append(' mode=%r' % self.mode)
  1138. else:
  1139. result.append(' [closed]')
  1140. result.append('>')
  1141. return ''.join(result)
  1142. def _RealGetContents(self):
  1143. """Read in the table of contents for the ZIP file."""
  1144. fp = self.fp
  1145. try:
  1146. endrec = _EndRecData(fp)
  1147. except OSError:
  1148. raise BadZipFile("File is not a zip file")
  1149. if not endrec:
  1150. raise BadZipFile("File is not a zip file")
  1151. if self.debug > 1:
  1152. print(endrec)
  1153. size_cd = endrec[_ECD_SIZE] # bytes in central directory
  1154. offset_cd = endrec[_ECD_OFFSET] # offset of central directory
  1155. self._comment = endrec[_ECD_COMMENT] # archive comment
  1156. # "concat" is zero, unless zip was concatenated to another file
  1157. concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
  1158. if endrec[_ECD_SIGNATURE] == stringEndArchive64:
  1159. # If Zip64 extension structures are present, account for them
  1160. concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
  1161. if self.debug > 2:
  1162. inferred = concat + offset_cd
  1163. print("given, inferred, offset", offset_cd, inferred, concat)
  1164. # self.start_dir: Position of start of central directory
  1165. self.start_dir = offset_cd + concat
  1166. fp.seek(self.start_dir, 0)
  1167. data = fp.read(size_cd)
  1168. fp = io.BytesIO(data)
  1169. total = 0
  1170. while total < size_cd:
  1171. centdir = fp.read(sizeCentralDir)
  1172. if len(centdir) != sizeCentralDir:
  1173. raise BadZipFile("Truncated central directory")
  1174. centdir = struct.unpack(structCentralDir, centdir)
  1175. if centdir[_CD_SIGNATURE] != stringCentralDir:
  1176. raise BadZipFile("Bad magic number for central directory")
  1177. if self.debug > 2:
  1178. print(centdir)
  1179. filename = fp.read(centdir[_CD_FILENAME_LENGTH])
  1180. flags = centdir[5]
  1181. if flags & 0x800:
  1182. # UTF-8 file names extension
  1183. filename = filename.decode('utf-8')
  1184. else:
  1185. # Historical ZIP filename encoding
  1186. filename = filename.decode('cp437')
  1187. # Create ZipInfo instance to store file information
  1188. x = ZipInfo(filename)
  1189. x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
  1190. x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
  1191. x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
  1192. (x.create_version, x.create_system, x.extract_version, x.reserved,
  1193. x.flag_bits, x.compress_type, t, d,
  1194. x.CRC, x.compress_size, x.file_size) = centdir[1:12]
  1195. if x.extract_version > MAX_EXTRACT_VERSION:
  1196. raise NotImplementedError("zip file version %.1f" %
  1197. (x.extract_version / 10))
  1198. x.volume, x.internal_attr, x.external_attr = centdir[15:18]
  1199. # Convert date/time code to (year, month, day, hour, min, sec)
  1200. x._raw_time = t
  1201. x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
  1202. t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
  1203. x._decodeExtra()
  1204. x.header_offset = x.header_offset + concat
  1205. self.filelist.append(x)
  1206. self.NameToInfo[x.filename] = x
  1207. # update total bytes read from central directory
  1208. total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]
  1209. + centdir[_CD_EXTRA_FIELD_LENGTH]
  1210. + centdir[_CD_COMMENT_LENGTH])
  1211. if self.debug > 2:
  1212. print("total", total)
  1213. def namelist(self):
  1214. """Return a list of file names in the archive."""
  1215. return [data.filename for data in self.filelist]
  1216. def infolist(self):
  1217. """Return a list of class ZipInfo instances for files in the
  1218. archive."""
  1219. return self.filelist
  1220. def printdir(self, file=None):
  1221. """Print a table of contents for the zip file."""
  1222. print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"),
  1223. file=file)
  1224. for zinfo in self.filelist:
  1225. date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
  1226. print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size),
  1227. file=file)
  1228. def testzip(self):
  1229. """Read all the files and check the CRC."""
  1230. chunk_size = 2 ** 20
  1231. for zinfo in self.filelist:
  1232. try:
  1233. # Read by chunks, to avoid an OverflowError or a
  1234. # MemoryError with very large embedded files.
  1235. with self.open(zinfo.filename, "r") as f:
  1236. while f.read(chunk_size): # Check CRC-32
  1237. pass
  1238. except BadZipFile:
  1239. return zinfo.filename
  1240. def getinfo(self, name):
  1241. """Return the instance of ZipInfo given 'name'."""
  1242. info = self.NameToInfo.get(name)
  1243. if info is None:
  1244. raise KeyError(
  1245. 'There is no item named %r in the archive' % name)
  1246. return info
  1247. def setpassword(self, pwd):
  1248. """Set default password for encrypted files."""
  1249. if pwd and not isinstance(pwd, bytes):
  1250. raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
  1251. if pwd:
  1252. self.pwd = pwd
  1253. else:
  1254. self.pwd = None
  1255. @property
  1256. def comment(self):
  1257. """The comment text associated with the ZIP file."""
  1258. return self._comment
  1259. @comment.setter
  1260. def comment(self, comment):
  1261. if not isinstance(comment, bytes):
  1262. raise TypeError("comment: expected bytes, got %s" % type(comment).__name__)
  1263. # check for valid comment length
  1264. if len(comment) > ZIP_MAX_COMMENT:
  1265. import warnings
  1266. warnings.warn('Archive comment is too long; truncating to %d bytes'
  1267. % ZIP_MAX_COMMENT, stacklevel=2)
  1268. comment = comment[:ZIP_MAX_COMMENT]
  1269. self._comment = comment
  1270. self._didModify = True
  1271. def read(self, name, pwd=None):
  1272. """Return file bytes for name."""
  1273. with self.open(name, "r", pwd) as fp:
  1274. return fp.read()
  1275. def open(self, name, mode="r", pwd=None, *, force_zip64=False):
  1276. """Return file-like object for 'name'.
  1277. name is a string for the file name within the ZIP file, or a ZipInfo
  1278. object.
  1279. mode should be 'r' to read a file already in the ZIP file, or 'w' to
  1280. write to a file newly added to the archive.
  1281. pwd is the password to decrypt files (only used for reading).
  1282. When writing, if the file size is not known in advance but may exceed
  1283. 2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large
  1284. files. If the size is known in advance, it is best to pass a ZipInfo
  1285. instance for name, with zinfo.file_size set.
  1286. """
  1287. if mode not in {"r", "w"}:
  1288. raise ValueError('open() requires mode "r" or "w"')
  1289. if pwd and not isinstance(pwd, bytes):
  1290. raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
  1291. if pwd and (mode == "w"):
  1292. raise ValueError("pwd is only supported for reading files")
  1293. if not self.fp:
  1294. raise ValueError(
  1295. "Attempt to use ZIP archive that was already closed")
  1296. # Make sure we have an info object
  1297. if isinstance(name, ZipInfo):
  1298. # 'name' is already an info object
  1299. zinfo = name
  1300. elif mode == 'w':
  1301. zinfo = ZipInfo(name)
  1302. zinfo.compress_type = self.compression
  1303. zinfo._compresslevel = self.compresslevel
  1304. else:
  1305. # Get info object for name
  1306. zinfo = self.getinfo(name)
  1307. if mode == 'w':
  1308. return self._open_to_write(zinfo, force_zip64=force_zip64)
  1309. if self._writing:
  1310. raise ValueError("Can't read from the ZIP file while there "
  1311. "is an open writing handle on it. "
  1312. "Close the writing handle before trying to read.")
  1313. # Open for reading:
  1314. self._fileRefCnt += 1
  1315. zef_file = _SharedFile(self.fp, zinfo.header_offset,
  1316. self._fpclose, self._lock, lambda: self._writing)
  1317. try:
  1318. # Skip the file header:
  1319. fheader = zef_file.read(sizeFileHeader)
  1320. if len(fheader) != sizeFileHeader:
  1321. raise BadZipFile("Truncated file header")
  1322. fheader = struct.unpack(structFileHeader, fheader)
  1323. if fheader[_FH_SIGNATURE] != stringFileHeader:
  1324. raise BadZipFile("Bad magic number for file header")
  1325. fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
  1326. if fheader[_FH_EXTRA_FIELD_LENGTH]:
  1327. zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
  1328. if zinfo.flag_bits & 0x20:
  1329. # Zip 2.7: compressed patched data
  1330. raise NotImplementedError("compressed patched data (flag bit 5)")
  1331. if zinfo.flag_bits & 0x40:
  1332. # strong encryption
  1333. raise NotImplementedError("strong encryption (flag bit 6)")
  1334. if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800:
  1335. # UTF-8 filename
  1336. fname_str = fname.decode("utf-8")
  1337. else:
  1338. fname_str = fname.decode("cp437")
  1339. if fname_str != zinfo.orig_filename:
  1340. raise BadZipFile(
  1341. 'File name in directory %r and header %r differ.'
  1342. % (zinfo.orig_filename, fname))
  1343. # check for encrypted flag & handle password
  1344. is_encrypted = zinfo.flag_bits & 0x1
  1345. if is_encrypted:
  1346. if not pwd:
  1347. pwd = self.pwd
  1348. if not pwd:
  1349. raise RuntimeError("File %r is encrypted, password "
  1350. "required for extraction" % name)
  1351. else:
  1352. pwd = None
  1353. return ZipExtFile(zef_file, mode, zinfo, pwd, True)
  1354. except:
  1355. zef_file.close()
  1356. raise
  1357. def _open_to_write(self, zinfo, force_zip64=False):
  1358. if force_zip64 and not self._allowZip64:
  1359. raise ValueError(
  1360. "force_zip64 is True, but allowZip64 was False when opening "
  1361. "the ZIP file."
  1362. )
  1363. if self._writing:
  1364. raise ValueError("Can't write to the ZIP file while there is "
  1365. "another write handle open on it. "
  1366. "Close the first handle before opening another.")
  1367. # Sizes and CRC are overwritten with correct data after processing the file
  1368. if not hasattr(zinfo, 'file_size'):
  1369. zinfo.file_size = 0
  1370. zinfo.compress_size = 0
  1371. zinfo.CRC = 0
  1372. zinfo.flag_bits = 0x00
  1373. if zinfo.compress_type == ZIP_LZMA:
  1374. # Compressed data includes an end-of-stream (EOS) marker
  1375. zinfo.flag_bits |= 0x02
  1376. if not self._seekable:
  1377. zinfo.flag_bits |= 0x08
  1378. if not zinfo.external_attr:
  1379. zinfo.external_attr = 0o600 << 16 # permissions: ?rw-------
  1380. # Compressed size can be larger than uncompressed size
  1381. zip64 = self._allowZip64 and \
  1382. (force_zip64 or zinfo.file_size * 1.05 > ZIP64_LIMIT)
  1383. if self._seekable:
  1384. self.fp.seek(self.start_dir)
  1385. zinfo.header_offset = self.fp.tell()
  1386. self._writecheck(zinfo)
  1387. self._didModify = True
  1388. self.fp.write(zinfo.FileHeader(zip64))
  1389. self._writing = True
  1390. return _ZipWriteFile(self, zinfo, zip64)
  1391. def extract(self, member, path=None, pwd=None):
  1392. """Extract a member from the archive to the current working directory,
  1393. using its full name. Its file information is extracted as accurately
  1394. as possible. `member' may be a filename or a ZipInfo object. You can
  1395. specify a different directory using `path'.
  1396. """
  1397. if path is None:
  1398. path = os.getcwd()
  1399. else:
  1400. path = os.fspath(path)
  1401. return self._extract_member(member, path, pwd)
  1402. def extractall(self, path=None, members=None, pwd=None):
  1403. """Extract all members from the archive to the current working
  1404. directory. `path' specifies a different directory to extract to.
  1405. `members' is optional and must be a subset of the list returned
  1406. by namelist().
  1407. """
  1408. if members is None:
  1409. members = self.namelist()
  1410. if path is None:
  1411. path = os.getcwd()
  1412. else:
  1413. path = os.fspath(path)
  1414. for zipinfo in members:
  1415. self._extract_member(zipinfo, path, pwd)
  1416. @classmethod
  1417. def _sanitize_windows_name(cls, arcname, pathsep):
  1418. """Replace bad characters and remove trailing dots from parts."""
  1419. table = cls._windows_illegal_name_trans_table
  1420. if not table:
  1421. illegal = ':<>|"?*'
  1422. table = str.maketrans(illegal, '_' * len(illegal))
  1423. cls._windows_illegal_name_trans_table = table
  1424. arcname = arcname.translate(table)
  1425. # remove trailing dots
  1426. arcname = (x.rstrip('.') for x in arcname.split(pathsep))
  1427. # rejoin, removing empty parts.
  1428. arcname = pathsep.join(x for x in arcname if x)
  1429. return arcname
  1430. def _extract_member(self, member, targetpath, pwd):
  1431. """Extract the ZipInfo object 'member' to a physical
  1432. file on the path targetpath.
  1433. """
  1434. if not isinstance(member, ZipInfo):
  1435. member = self.getinfo(member)
  1436. # build the destination pathname, replacing
  1437. # forward slashes to platform specific separators.
  1438. arcname = member.filename.replace('/', os.path.sep)
  1439. if os.path.altsep:
  1440. arcname = arcname.replace(os.path.altsep, os.path.sep)
  1441. # interpret absolute pathname as relative, remove drive letter or
  1442. # UNC path, redundant separators, "." and ".." components.
  1443. arcname = os.path.splitdrive(arcname)[1]
  1444. invalid_path_parts = ('', os.path.curdir, os.path.pardir)
  1445. arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
  1446. if x not in invalid_path_parts)
  1447. if os.path.sep == '\\':
  1448. # filter illegal characters on Windows
  1449. arcname = self._sanitize_windows_name(arcname, os.path.sep)
  1450. targetpath = os.path.join(targetpath, arcname)
  1451. targetpath = os.path.normpath(targetpath)
  1452. # Create all upper directories if necessary.
  1453. upperdirs = os.path.dirname(targetpath)
  1454. if upperdirs and not os.path.exists(upperdirs):
  1455. os.makedirs(upperdirs)
  1456. if member.is_dir():
  1457. if not os.path.isdir(targetpath):
  1458. os.mkdir(targetpath)
  1459. return targetpath
  1460. with self.open(member, pwd=pwd) as source, \
  1461. open(targetpath, "wb") as target:
  1462. shutil.copyfileobj(source, target)
  1463. return targetpath
  1464. def _writecheck(self, zinfo):
  1465. """Check for errors before writing a file to the archive."""
  1466. if zinfo.filename in self.NameToInfo:
  1467. import warnings
  1468. warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
  1469. if self.mode not in ('w', 'x', 'a'):
  1470. raise ValueError("write() requires mode 'w', 'x', or 'a'")
  1471. if not self.fp:
  1472. raise ValueError(
  1473. "Attempt to write ZIP archive that was already closed")
  1474. _check_compression(zinfo.compress_type)
  1475. if not self._allowZip64:
  1476. requires_zip64 = None
  1477. if len(self.filelist) >= ZIP_FILECOUNT_LIMIT:
  1478. requires_zip64 = "Files count"
  1479. elif zinfo.file_size > ZIP64_LIMIT:
  1480. requires_zip64 = "Filesize"
  1481. elif zinfo.header_offset > ZIP64_LIMIT:
  1482. requires_zip64 = "Zipfile size"
  1483. if requires_zip64:
  1484. raise LargeZipFile(requires_zip64 +
  1485. " would require ZIP64 extensions")
  1486. def write(self, filename, arcname=None,
  1487. compress_type=None, compresslevel=None):
  1488. """Put the bytes from filename into the archive under the name
  1489. arcname."""
  1490. if not self.fp:
  1491. raise ValueError(
  1492. "Attempt to write to ZIP archive that was already closed")
  1493. if self._writing:
  1494. raise ValueError(
  1495. "Can't write to ZIP archive while an open writing handle exists"
  1496. )
  1497. zinfo = ZipInfo.from_file(filename, arcname,
  1498. strict_timestamps=self._strict_timestamps)
  1499. if zinfo.is_dir():
  1500. zinfo.compress_size = 0
  1501. zinfo.CRC = 0
  1502. else:
  1503. if compress_type is not None:
  1504. zinfo.compress_type = compress_type
  1505. else:
  1506. zinfo.compress_type = self.compression
  1507. if compresslevel is not None:
  1508. zinfo._compresslevel = compresslevel
  1509. else:
  1510. zinfo._compresslevel = self.compresslevel
  1511. if zinfo.is_dir():
  1512. with self._lock:
  1513. if self._seekable:
  1514. self.fp.seek(self.start_dir)
  1515. zinfo.header_offset = self.fp.tell() # Start of header bytes
  1516. if zinfo.compress_type == ZIP_LZMA:
  1517. # Compressed data includes an end-of-stream (EOS) marker
  1518. zinfo.flag_bits |= 0x02
  1519. self._writecheck(zinfo)
  1520. self._didModify = True
  1521. self.filelist.append(zinfo)
  1522. self.NameToInfo[zinfo.filename] = zinfo
  1523. self.fp.write(zinfo.FileHeader(False))
  1524. self.start_dir = self.fp.tell()
  1525. else:
  1526. with open(filename, "rb") as src, self.open(zinfo, 'w') as dest:
  1527. shutil.copyfileobj(src, dest, 1024*8)
  1528. def writestr(self, zinfo_or_arcname, data,
  1529. compress_type=None, compresslevel=None):
  1530. """Write a file into the archive. The contents is 'data', which
  1531. may be either a 'str' or a 'bytes' instance; if it is a 'str',
  1532. it is encoded as UTF-8 first.
  1533. 'zinfo_or_arcname' is either a ZipInfo instance or
  1534. the name of the file in the archive."""
  1535. if isinstance(data, str):
  1536. data = data.encode("utf-8")
  1537. if not isinstance(zinfo_or_arcname, ZipInfo):
  1538. zinfo = ZipInfo(filename=zinfo_or_arcname,
  1539. date_time=time.localtime(time.time())[:6])
  1540. zinfo.compress_type = self.compression
  1541. zinfo._compresslevel = self.compresslevel
  1542. if zinfo.filename[-1] == '/':
  1543. zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
  1544. zinfo.external_attr |= 0x10 # MS-DOS directory flag
  1545. else:
  1546. zinfo.external_attr = 0o600 << 16 # ?rw-------
  1547. else:
  1548. zinfo = zinfo_or_arcname
  1549. if not self.fp:
  1550. raise ValueError(
  1551. "Attempt to write to ZIP archive that was already closed")
  1552. if self._writing:
  1553. raise ValueError(
  1554. "Can't write to ZIP archive while an open writing handle exists."
  1555. )
  1556. if compress_type is not None:
  1557. zinfo.compress_type = compress_type
  1558. if compresslevel is not None:
  1559. zinfo._compresslevel = compresslevel
  1560. zinfo.file_size = len(data) # Uncompressed size
  1561. with self._lock:
  1562. with self.open(zinfo, mode='w') as dest:
  1563. dest.write(data)
  1564. def __del__(self):
  1565. """Call the "close()" method in case the user forgot."""
  1566. self.close()
  1567. def close(self):
  1568. """Close the file, and for mode 'w', 'x' and 'a' write the ending
  1569. records."""
  1570. if self.fp is None:
  1571. return
  1572. if self._writing:
  1573. raise ValueError("Can't close the ZIP file while there is "
  1574. "an open writing handle on it. "
  1575. "Close the writing handle before closing the zip.")
  1576. try:
  1577. if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records
  1578. with self._lock:
  1579. if self._seekable:
  1580. self.fp.seek(self.start_dir)
  1581. self._write_end_record()
  1582. finally:
  1583. fp = self.fp
  1584. self.fp = None
  1585. self._fpclose(fp)
  1586. def _write_end_record(self):
  1587. for zinfo in self.filelist: # write central directory
  1588. dt = zinfo.date_time
  1589. dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
  1590. dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
  1591. extra = []
  1592. if zinfo.file_size > ZIP64_LIMIT \
  1593. or zinfo.compress_size > ZIP64_LIMIT:
  1594. extra.append(zinfo.file_size)
  1595. extra.append(zinfo.compress_size)
  1596. file_size = 0xffffffff
  1597. compress_size = 0xffffffff
  1598. else:
  1599. file_size = zinfo.file_size
  1600. compress_size = zinfo.compress_size
  1601. if zinfo.header_offset > ZIP64_LIMIT:
  1602. extra.append(zinfo.header_offset)
  1603. header_offset = 0xffffffff
  1604. else:
  1605. header_offset = zinfo.header_offset
  1606. extra_data = zinfo.extra
  1607. min_version = 0
  1608. if extra:
  1609. # Append a ZIP64 field to the extra's
  1610. extra_data = _strip_extra(extra_data, (1,))
  1611. extra_data = struct.pack(
  1612. '<HH' + 'Q'*len(extra),
  1613. 1, 8*len(extra), *extra) + extra_data
  1614. min_version = ZIP64_VERSION
  1615. if zinfo.compress_type == ZIP_BZIP2:
  1616. min_version = max(BZIP2_VERSION, min_version)
  1617. elif zinfo.compress_type == ZIP_LZMA:
  1618. min_version = max(LZMA_VERSION, min_version)
  1619. extract_version = max(min_version, zinfo.extract_version)
  1620. create_version = max(min_version, zinfo.create_version)
  1621. try:
  1622. filename, flag_bits = zinfo._encodeFilenameFlags()
  1623. centdir = struct.pack(structCentralDir,
  1624. stringCentralDir, create_version,
  1625. zinfo.create_system, extract_version, zinfo.reserved,
  1626. flag_bits, zinfo.compress_type, dostime, dosdate,
  1627. zinfo.CRC, compress_size, file_size,
  1628. len(filename), len(extra_data), len(zinfo.comment),
  1629. 0, zinfo.internal_attr, zinfo.external_attr,
  1630. header_offset)
  1631. except DeprecationWarning:
  1632. print((structCentralDir, stringCentralDir, create_version,
  1633. zinfo.create_system, extract_version, zinfo.reserved,
  1634. zinfo.flag_bits, zinfo.compress_type, dostime, dosdate,
  1635. zinfo.CRC, compress_size, file_size,
  1636. len(zinfo.filename), len(extra_data), len(zinfo.comment),
  1637. 0, zinfo.internal_attr, zinfo.external_attr,
  1638. header_offset), file=sys.stderr)
  1639. raise
  1640. self.fp.write(centdir)
  1641. self.fp.write(filename)
  1642. self.fp.write(extra_data)
  1643. self.fp.write(zinfo.comment)
  1644. pos2 = self.fp.tell()
  1645. # Write end-of-zip-archive record
  1646. centDirCount = len(self.filelist)
  1647. centDirSize = pos2 - self.start_dir
  1648. centDirOffset = self.start_dir
  1649. requires_zip64 = None
  1650. if centDirCount > ZIP_FILECOUNT_LIMIT:
  1651. requires_zip64 = "Files count"
  1652. elif centDirOffset > ZIP64_LIMIT:
  1653. requires_zip64 = "Central directory offset"
  1654. elif centDirSize > ZIP64_LIMIT:
  1655. requires_zip64 = "Central directory size"
  1656. if requires_zip64:
  1657. # Need to write the ZIP64 end-of-archive records
  1658. if not self._allowZip64:
  1659. raise LargeZipFile(requires_zip64 +
  1660. " would require ZIP64 extensions")
  1661. zip64endrec = struct.pack(
  1662. structEndArchive64, stringEndArchive64,
  1663. 44, 45, 45, 0, 0, centDirCount, centDirCount,
  1664. centDirSize, centDirOffset)
  1665. self.fp.write(zip64endrec)
  1666. zip64locrec = struct.pack(
  1667. structEndArchive64Locator,
  1668. stringEndArchive64Locator, 0, pos2, 1)
  1669. self.fp.write(zip64locrec)
  1670. centDirCount = min(centDirCount, 0xFFFF)
  1671. centDirSize = min(centDirSize, 0xFFFFFFFF)
  1672. centDirOffset = min(centDirOffset, 0xFFFFFFFF)
  1673. endrec = struct.pack(structEndArchive, stringEndArchive,
  1674. 0, 0, centDirCount, centDirCount,
  1675. centDirSize, centDirOffset, len(self._comment))
  1676. self.fp.write(endrec)
  1677. self.fp.write(self._comment)
  1678. if self.mode == "a":
  1679. self.fp.truncate()
  1680. self.fp.flush()
  1681. def _fpclose(self, fp):
  1682. assert self._fileRefCnt > 0
  1683. self._fileRefCnt -= 1
  1684. if not self._fileRefCnt and not self._filePassed:
  1685. fp.close()
  1686. class PyZipFile(ZipFile):
  1687. """Class to create ZIP archives with Python library files and packages."""
  1688. def __init__(self, file, mode="r", compression=ZIP_STORED,
  1689. allowZip64=True, optimize=-1):
  1690. ZipFile.__init__(self, file, mode=mode, compression=compression,
  1691. allowZip64=allowZip64)
  1692. self._optimize = optimize
  1693. def writepy(self, pathname, basename="", filterfunc=None):
  1694. """Add all files from "pathname" to the ZIP archive.
  1695. If pathname is a package directory, search the directory and
  1696. all package subdirectories recursively for all *.py and enter
  1697. the modules into the archive. If pathname is a plain
  1698. directory, listdir *.py and enter all modules. Else, pathname
  1699. must be a Python *.py file and the module will be put into the
  1700. archive. Added modules are always module.pyc.
  1701. This method will compile the module.py into module.pyc if
  1702. necessary.
  1703. If filterfunc(pathname) is given, it is called with every argument.
  1704. When it is False, the file or directory is skipped.
  1705. """
  1706. pathname = os.fspath(pathname)
  1707. if filterfunc and not filterfunc(pathname):
  1708. if self.debug:
  1709. label = 'path' if os.path.isdir(pathname) else 'file'
  1710. print('%s %r skipped by filterfunc' % (label, pathname))
  1711. return
  1712. dir, name = os.path.split(pathname)
  1713. if os.path.isdir(pathname):
  1714. initname = os.path.join(pathname, "__init__.py")
  1715. if os.path.isfile(initname):
  1716. # This is a package directory, add it
  1717. if basename:
  1718. basename = "%s/%s" % (basename, name)
  1719. else:
  1720. basename = name
  1721. if self.debug:
  1722. print("Adding package in", pathname, "as", basename)
  1723. fname, arcname = self._get_codename(initname[0:-3], basename)
  1724. if self.debug:
  1725. print("Adding", arcname)
  1726. self.write(fname, arcname)
  1727. dirlist = sorted(os.listdir(pathname))
  1728. dirlist.remove("__init__.py")
  1729. # Add all *.py files and package subdirectories
  1730. for filename in dirlist:
  1731. path = os.path.join(pathname, filename)
  1732. root, ext = os.path.splitext(filename)
  1733. if os.path.isdir(path):
  1734. if os.path.isfile(os.path.join(path, "__init__.py")):
  1735. # This is a package directory, add it
  1736. self.writepy(path, basename,
  1737. filterfunc=filterfunc) # Recursive call
  1738. elif ext == ".py":
  1739. if filterfunc and not filterfunc(path):
  1740. if self.debug:
  1741. print('file %r skipped by filterfunc' % path)
  1742. continue
  1743. fname, arcname = self._get_codename(path[0:-3],
  1744. basename)
  1745. if self.debug:
  1746. print("Adding", arcname)
  1747. self.write(fname, arcname)
  1748. else:
  1749. # This is NOT a package directory, add its files at top level
  1750. if self.debug:
  1751. print("Adding files from directory", pathname)
  1752. for filename in sorted(os.listdir(pathname)):
  1753. path = os.path.join(pathname, filename)
  1754. root, ext = os.path.splitext(filename)
  1755. if ext == ".py":
  1756. if filterfunc and not filterfunc(path):
  1757. if self.debug:
  1758. print('file %r skipped by filterfunc' % path)
  1759. continue
  1760. fname, arcname = self._get_codename(path[0:-3],
  1761. basename)
  1762. if self.debug:
  1763. print("Adding", arcname)
  1764. self.write(fname, arcname)
  1765. else:
  1766. if pathname[-3:] != ".py":
  1767. raise RuntimeError(
  1768. 'Files added with writepy() must end with ".py"')
  1769. fname, arcname = self._get_codename(pathname[0:-3], basename)
  1770. if self.debug:
  1771. print("Adding file", arcname)
  1772. self.write(fname, arcname)
  1773. def _get_codename(self, pathname, basename):
  1774. """Return (filename, archivename) for the path.
  1775. Given a module name path, return the correct file path and
  1776. archive name, compiling if necessary. For example, given
  1777. /python/lib/string, return (/python/lib/string.pyc, string).
  1778. """
  1779. def _compile(file, optimize=-1):
  1780. import py_compile
  1781. if self.debug:
  1782. print("Compiling", file)
  1783. try:
  1784. py_compile.compile(file, doraise=True, optimize=optimize)
  1785. except py_compile.PyCompileError as err:
  1786. print(err.msg)
  1787. return False
  1788. return True
  1789. file_py = pathname + ".py"
  1790. file_pyc = pathname + ".pyc"
  1791. pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='')
  1792. pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1)
  1793. pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2)
  1794. if self._optimize == -1:
  1795. # legacy mode: use whatever file is present
  1796. if (os.path.isfile(file_pyc) and
  1797. os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
  1798. # Use .pyc file.
  1799. arcname = fname = file_pyc
  1800. elif (os.path.isfile(pycache_opt0) and
  1801. os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime):
  1802. # Use the __pycache__/*.pyc file, but write it to the legacy pyc
  1803. # file name in the archive.
  1804. fname = pycache_opt0
  1805. arcname = file_pyc
  1806. elif (os.path.isfile(pycache_opt1) and
  1807. os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime):
  1808. # Use the __pycache__/*.pyc file, but write it to the legacy pyc
  1809. # file name in the archive.
  1810. fname = pycache_opt1
  1811. arcname = file_pyc
  1812. elif (os.path.isfile(pycache_opt2) and
  1813. os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime):
  1814. # Use the __pycache__/*.pyc file, but write it to the legacy pyc
  1815. # file name in the archive.
  1816. fname = pycache_opt2
  1817. arcname = file_pyc
  1818. else:
  1819. # Compile py into PEP 3147 pyc file.
  1820. if _compile(file_py):
  1821. if sys.flags.optimize == 0:
  1822. fname = pycache_opt0
  1823. elif sys.flags.optimize == 1:
  1824. fname = pycache_opt1
  1825. else:
  1826. fname = pycache_opt2
  1827. arcname = file_pyc
  1828. else:
  1829. fname = arcname = file_py
  1830. else:
  1831. # new mode: use given optimization level
  1832. if self._optimize == 0:
  1833. fname = pycache_opt0
  1834. arcname = file_pyc
  1835. else:
  1836. arcname = file_pyc
  1837. if self._optimize == 1:
  1838. fname = pycache_opt1
  1839. elif self._optimize == 2:
  1840. fname = pycache_opt2
  1841. else:
  1842. msg = "invalid value for 'optimize': {!r}".format(self._optimize)
  1843. raise ValueError(msg)
  1844. if not (os.path.isfile(fname) and
  1845. os.stat(fname).st_mtime >= os.stat(file_py).st_mtime):
  1846. if not _compile(file_py, optimize=self._optimize):
  1847. fname = arcname = file_py
  1848. archivename = os.path.split(arcname)[1]
  1849. if basename:
  1850. archivename = "%s/%s" % (basename, archivename)
  1851. return (fname, archivename)
  1852. def _parents(path):
  1853. """
  1854. Given a path with elements separated by
  1855. posixpath.sep, generate all parents of that path.
  1856. >>> list(_parents('b/d'))
  1857. ['b']
  1858. >>> list(_parents('/b/d/'))
  1859. ['/b']
  1860. >>> list(_parents('b/d/f/'))
  1861. ['b/d', 'b']
  1862. >>> list(_parents('b'))
  1863. []
  1864. >>> list(_parents(''))
  1865. []
  1866. """
  1867. return itertools.islice(_ancestry(path), 1, None)
  1868. def _ancestry(path):
  1869. """
  1870. Given a path with elements separated by
  1871. posixpath.sep, generate all elements of that path
  1872. >>> list(_ancestry('b/d'))
  1873. ['b/d', 'b']
  1874. >>> list(_ancestry('/b/d/'))
  1875. ['/b/d', '/b']
  1876. >>> list(_ancestry('b/d/f/'))
  1877. ['b/d/f', 'b/d', 'b']
  1878. >>> list(_ancestry('b'))
  1879. ['b']
  1880. >>> list(_ancestry(''))
  1881. []
  1882. """
  1883. path = path.rstrip(posixpath.sep)
  1884. while path and path != posixpath.sep:
  1885. yield path
  1886. path, tail = posixpath.split(path)
  1887. _dedupe = dict.fromkeys
  1888. """Deduplicate an iterable in original order"""
  1889. def _difference(minuend, subtrahend):
  1890. """
  1891. Return items in minuend not in subtrahend, retaining order
  1892. with O(1) lookup.
  1893. """
  1894. return itertools.filterfalse(set(subtrahend).__contains__, minuend)
  1895. class CompleteDirs(ZipFile):
  1896. """
  1897. A ZipFile subclass that ensures that implied directories
  1898. are always included in the namelist.
  1899. """
  1900. @staticmethod
  1901. def _implied_dirs(names):
  1902. parents = itertools.chain.from_iterable(map(_parents, names))
  1903. as_dirs = (p + posixpath.sep for p in parents)
  1904. return _dedupe(_difference(as_dirs, names))
  1905. def namelist(self):
  1906. names = super(CompleteDirs, self).namelist()
  1907. return names + list(self._implied_dirs(names))
  1908. def _name_set(self):
  1909. return set(self.namelist())
  1910. def resolve_dir(self, name):
  1911. """
  1912. If the name represents a directory, return that name
  1913. as a directory (with the trailing slash).
  1914. """
  1915. names = self._name_set()
  1916. dirname = name + '/'
  1917. dir_match = name not in names and dirname in names
  1918. return dirname if dir_match else name
  1919. @classmethod
  1920. def make(cls, source):
  1921. """
  1922. Given a source (filename or zipfile), return an
  1923. appropriate CompleteDirs subclass.
  1924. """
  1925. if isinstance(source, CompleteDirs):
  1926. return source
  1927. if not isinstance(source, ZipFile):
  1928. return cls(source)
  1929. # Only allow for FastPath when supplied zipfile is read-only
  1930. if 'r' not in source.mode:
  1931. cls = CompleteDirs
  1932. res = cls.__new__(cls)
  1933. vars(res).update(vars(source))
  1934. return res
  1935. class FastLookup(CompleteDirs):
  1936. """
  1937. ZipFile subclass to ensure implicit
  1938. dirs exist and are resolved rapidly.
  1939. """
  1940. def namelist(self):
  1941. with contextlib.suppress(AttributeError):
  1942. return self.__names
  1943. self.__names = super(FastLookup, self).namelist()
  1944. return self.__names
  1945. def _name_set(self):
  1946. with contextlib.suppress(AttributeError):
  1947. return self.__lookup
  1948. self.__lookup = super(FastLookup, self)._name_set()
  1949. return self.__lookup
  1950. class Path:
  1951. """
  1952. A pathlib-compatible interface for zip files.
  1953. Consider a zip file with this structure::
  1954. .
  1955. ├── a.txt
  1956. └── b
  1957. ├── c.txt
  1958. └── d
  1959. └── e.txt
  1960. >>> data = io.BytesIO()
  1961. >>> zf = ZipFile(data, 'w')
  1962. >>> zf.writestr('a.txt', 'content of a')
  1963. >>> zf.writestr('b/c.txt', 'content of c')
  1964. >>> zf.writestr('b/d/e.txt', 'content of e')
  1965. >>> zf.filename = 'abcde.zip'
  1966. Path accepts the zipfile object itself or a filename
  1967. >>> root = Path(zf)
  1968. From there, several path operations are available.
  1969. Directory iteration (including the zip file itself):
  1970. >>> a, b = root.iterdir()
  1971. >>> a
  1972. Path('abcde.zip', 'a.txt')
  1973. >>> b
  1974. Path('abcde.zip', 'b/')
  1975. name property:
  1976. >>> b.name
  1977. 'b'
  1978. join with divide operator:
  1979. >>> c = b / 'c.txt'
  1980. >>> c
  1981. Path('abcde.zip', 'b/c.txt')
  1982. >>> c.name
  1983. 'c.txt'
  1984. Read text:
  1985. >>> c.read_text()
  1986. 'content of c'
  1987. existence:
  1988. >>> c.exists()
  1989. True
  1990. >>> (b / 'missing.txt').exists()
  1991. False
  1992. Coercion to string:
  1993. >>> str(c)
  1994. 'abcde.zip/b/c.txt'
  1995. """
  1996. __repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
  1997. def __init__(self, root, at=""):
  1998. self.root = FastLookup.make(root)
  1999. self.at = at
  2000. @property
  2001. def open(self):
  2002. return functools.partial(self.root.open, self.at)
  2003. @property
  2004. def name(self):
  2005. return posixpath.basename(self.at.rstrip("/"))
  2006. def read_text(self, *args, **kwargs):
  2007. with self.open() as strm:
  2008. return io.TextIOWrapper(strm, *args, **kwargs).read()
  2009. def read_bytes(self):
  2010. with self.open() as strm:
  2011. return strm.read()
  2012. def _is_child(self, path):
  2013. return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
  2014. def _next(self, at):
  2015. return Path(self.root, at)
  2016. def is_dir(self):
  2017. return not self.at or self.at.endswith("/")
  2018. def is_file(self):
  2019. return not self.is_dir()
  2020. def exists(self):
  2021. return self.at in self.root._name_set()
  2022. def iterdir(self):
  2023. if not self.is_dir():
  2024. raise ValueError("Can't listdir a file")
  2025. subs = map(self._next, self.root.namelist())
  2026. return filter(self._is_child, subs)
  2027. def __str__(self):
  2028. return posixpath.join(self.root.filename, self.at)
  2029. def __repr__(self):
  2030. return self.__repr.format(self=self)
  2031. def joinpath(self, add):
  2032. next = posixpath.join(self.at, add)
  2033. return self._next(self.root.resolve_dir(next))
  2034. __truediv__ = joinpath
  2035. @property
  2036. def parent(self):
  2037. parent_at = posixpath.dirname(self.at.rstrip('/'))
  2038. if parent_at:
  2039. parent_at += '/'
  2040. return self._next(parent_at)
  2041. def main(args=None):
  2042. import argparse
  2043. description = 'A simple command-line interface for zipfile module.'
  2044. parser = argparse.ArgumentParser(description=description)
  2045. group = parser.add_mutually_exclusive_group(required=True)
  2046. group.add_argument('-l', '--list', metavar='<zipfile>',
  2047. help='Show listing of a zipfile')
  2048. group.add_argument('-e', '--extract', nargs=2,
  2049. metavar=('<zipfile>', '<output_dir>'),
  2050. help='Extract zipfile into target dir')
  2051. group.add_argument('-c', '--create', nargs='+',
  2052. metavar=('<name>', '<file>'),
  2053. help='Create zipfile from sources')
  2054. group.add_argument('-t', '--test', metavar='<zipfile>',
  2055. help='Test if a zipfile is valid')
  2056. args = parser.parse_args(args)
  2057. if args.test is not None:
  2058. src = args.test
  2059. with ZipFile(src, 'r') as zf:
  2060. badfile = zf.testzip()
  2061. if badfile:
  2062. print("The following enclosed file is corrupted: {!r}".format(badfile))
  2063. print("Done testing")
  2064. elif args.list is not None:
  2065. src = args.list
  2066. with ZipFile(src, 'r') as zf:
  2067. zf.printdir()
  2068. elif args.extract is not None:
  2069. src, curdir = args.extract
  2070. with ZipFile(src, 'r') as zf:
  2071. zf.extractall(curdir)
  2072. elif args.create is not None:
  2073. zip_name = args.create.pop(0)
  2074. files = args.create
  2075. def addToZip(zf, path, zippath):
  2076. if os.path.isfile(path):
  2077. zf.write(path, zippath, ZIP_DEFLATED)
  2078. elif os.path.isdir(path):
  2079. if zippath:
  2080. zf.write(path, zippath)
  2081. for nm in sorted(os.listdir(path)):
  2082. addToZip(zf,
  2083. os.path.join(path, nm), os.path.join(zippath, nm))
  2084. # else: ignore
  2085. with ZipFile(zip_name, 'w') as zf:
  2086. for path in files:
  2087. zippath = os.path.basename(path)
  2088. if not zippath:
  2089. zippath = os.path.basename(os.path.dirname(path))
  2090. if zippath in ('', os.curdir, os.pardir):
  2091. zippath = ''
  2092. addToZip(zf, path, zippath)
  2093. if __name__ == "__main__":
  2094. main()