zipfile.py 79 KB

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