Debian Codegraph @

src/python/backports/zstd/zipfile/__init__.py

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