my_zipfile.py 80 KB

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