Debian Codegraph @

lib-python/3/zipfile.py

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