__init__.py 82 KB

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