__init__.py 86 KB

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