Debian Codegraph @

cpython27/Lib/zipfile.py

raw symbols SCIP
1 """
2 Read and write ZIP files.
3 """
4 import struct, os, time, sys, shutil
5 import binascii, cStringIO, stat
6 import io
7 import re
8 import string
9
10 try:
11 import zlib # We may need its compression method
12 crc32 = zlib.crc32
13 except ImportError:
14 zlib = None
15 crc32 = binascii.crc32
16
17 __all__ = ["BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "is_zipfile",
18 "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile" ]
19
20 class BadZipfile(Exception):
21 pass
22
23
24 class LargeZipFile(Exception):
25 """
26 Raised when writing a zipfile, the zipfile requires ZIP64 extensions
27 and those extensions are disabled.
28 """
29
30 error = BadZipfile # The exception raised by this module
31
32 ZIP64_LIMIT = (1 << 31) - 1
33 ZIP_FILECOUNT_LIMIT = (1 << 16) - 1
34 ZIP_MAX_COMMENT = (1 << 16) - 1
35
36 # constants for Zip file compression methods
37 ZIP_STORED = 0
38 ZIP_DEFLATED = 8
39 # Other ZIP compression methods not supported
40
41 # Below are some formats and associated data for reading/writing headers using
42 # the struct module. The names and structures of headers/records are those used
43 # in the PKWARE description of the ZIP file format:
44 # http://www.pkware.com/documents/casestudies/APPNOTE.TXT
45 # (URL valid as of January 2008)
46
47 # The "end of central directory" structure, magic number, size, and indices
48 # (section V.I in the format document)
49 structEndArchive = "<4s4H2LH"
50 stringEndArchive = "PK\005\006"
51 sizeEndCentDir = struct.calcsize(structEndArchive)
52
53 _ECD_SIGNATURE = 0
54 _ECD_DISK_NUMBER = 1
55 _ECD_DISK_START = 2
56 _ECD_ENTRIES_THIS_DISK = 3
57 _ECD_ENTRIES_TOTAL = 4
58 _ECD_SIZE = 5
59 _ECD_OFFSET = 6
60 _ECD_COMMENT_SIZE = 7
61 # These last two indices are not part of the structure as defined in the
62 # spec, but they are used internally by this module as a convenience
63 _ECD_COMMENT = 8
64 _ECD_LOCATION = 9
65
66 # The "central directory" structure, magic number, size, and indices
67 # of entries in the structure (section V.F in the format document)
68 structCentralDir = "<4s4B4HL2L5H2L"
69 stringCentralDir = "PK\001\002"
70 sizeCentralDir = struct.calcsize(structCentralDir)
71
72 # indexes of entries in the central directory structure
73 _CD_SIGNATURE = 0
74 _CD_CREATE_VERSION = 1
75 _CD_CREATE_SYSTEM = 2
76 _CD_EXTRACT_VERSION = 3
77 _CD_EXTRACT_SYSTEM = 4
78 _CD_FLAG_BITS = 5
79 _CD_COMPRESS_TYPE = 6
80 _CD_TIME = 7
81 _CD_DATE = 8
82 _CD_CRC = 9
83 _CD_COMPRESSED_SIZE = 10
84 _CD_UNCOMPRESSED_SIZE = 11
85 _CD_FILENAME_LENGTH = 12
86 _CD_EXTRA_FIELD_LENGTH = 13
87 _CD_COMMENT_LENGTH = 14
88 _CD_DISK_NUMBER_START = 15
89 _CD_INTERNAL_FILE_ATTRIBUTES = 16
90 _CD_EXTERNAL_FILE_ATTRIBUTES = 17
91 _CD_LOCAL_HEADER_OFFSET = 18
92
93 # The "local file header" structure, magic number, size, and indices
94 # (section V.A in the format document)
95 structFileHeader = "<4s2B4HL2L2H"
96 stringFileHeader = "PK\003\004"
97 sizeFileHeader = struct.calcsize(structFileHeader)
98
99 _FH_SIGNATURE = 0
100 _FH_EXTRACT_VERSION = 1
101 _FH_EXTRACT_SYSTEM = 2
102 _FH_GENERAL_PURPOSE_FLAG_BITS = 3
103 _FH_COMPRESSION_METHOD = 4
104 _FH_LAST_MOD_TIME = 5
105 _FH_LAST_MOD_DATE = 6
106 _FH_CRC = 7
107 _FH_COMPRESSED_SIZE = 8
108 _FH_UNCOMPRESSED_SIZE = 9
109 _FH_FILENAME_LENGTH = 10
110 _FH_EXTRA_FIELD_LENGTH = 11
111
112 # The "Zip64 end of central directory locator" structure, magic number, and size
113 structEndArchive64Locator = "<4sLQL"
114 stringEndArchive64Locator = "PK\x06\x07"
115 sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
116
117 # The "Zip64 end of central directory" record, magic number, size, and indices
118 # (section V.G in the format document)
119 structEndArchive64 = "<4sQ2H2L4Q"
120 stringEndArchive64 = "PK\x06\x06"
121 sizeEndCentDir64 = struct.calcsize(structEndArchive64)
122
123 _CD64_SIGNATURE = 0
124 _CD64_DIRECTORY_RECSIZE = 1
125 _CD64_CREATE_VERSION = 2
126 _CD64_EXTRACT_VERSION = 3
127 _CD64_DISK_NUMBER = 4
128 _CD64_DISK_NUMBER_START = 5
129 _CD64_NUMBER_ENTRIES_THIS_DISK = 6
130 _CD64_NUMBER_ENTRIES_TOTAL = 7
131 _CD64_DIRECTORY_SIZE = 8
132 _CD64_OFFSET_START_CENTDIR = 9
133
134 _DD_SIGNATURE = 0x08074b50
135
136 _EXTRA_FIELD_STRUCT = struct.Struct('<HH')
137
138 def _strip_extra(extra, xids):
139 # Remove Extra Fields with specified IDs.
140 unpack = _EXTRA_FIELD_STRUCT.unpack
141 modified = False
142 buffer = []
143 start = i = 0
144 while i + 4 <= len(extra):
145 xid, xlen = unpack(extra[i : i + 4])
146 j = i + 4 + xlen
147 if xid in xids:
148 if i != start:
149 buffer.append(extra[start : i])
150 start = j
151 modified = True
152 i = j
153 if not modified:
154 return extra
155 return b''.join(buffer)
156
157 def _check_zipfile(fp):
158 try:
159 if _EndRecData(fp):
160 return True # file has correct magic number
161 except IOError:
162 pass
163 return False
164
165 def is_zipfile(filename):
166 """Quickly see if a file is a ZIP file by checking the magic number.
167
168 The filename argument may be a file or file-like object too.
169 """
170 result = False
171 try:
172 if hasattr(filename, "read"):
173 result = _check_zipfile(fp=filename)
174 else:
175 with open(filename, "rb") as fp:
176 result = _check_zipfile(fp)
177 except IOError:
178 pass
179 return result
180
181 def _EndRecData64(fpin, offset, endrec):
182 """
183 Read the ZIP64 end-of-archive records and use that to update endrec
184 """
185 try:
186 fpin.seek(offset - sizeEndCentDir64Locator, 2)
187 except IOError:
188 # If the seek fails, the file is not large enough to contain a ZIP64
189 # end-of-archive record, so just return the end record we were given.
190 return endrec
191
192 data = fpin.read(sizeEndCentDir64Locator)
193 if len(data) != sizeEndCentDir64Locator:
194 return endrec
195 sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
196 if sig != stringEndArchive64Locator:
197 return endrec
198
199 if diskno != 0 or disks != 1:
200 raise BadZipfile("zipfiles that span multiple disks are not supported")
201
202 # Assume no 'zip64 extensible data'
203 fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2)
204 data = fpin.read(sizeEndCentDir64)
205 if len(data) != sizeEndCentDir64:
206 return endrec
207 sig, sz, create_version, read_version, disk_num, disk_dir, \
208 dircount, dircount2, dirsize, diroffset = \
209 struct.unpack(structEndArchive64, data)
210 if sig != stringEndArchive64:
211 return endrec
212
213 # Update the original endrec using data from the ZIP64 record
214 endrec[_ECD_SIGNATURE] = sig
215 endrec[_ECD_DISK_NUMBER] = disk_num
216 endrec[_ECD_DISK_START] = disk_dir
217 endrec[_ECD_ENTRIES_THIS_DISK] = dircount
218 endrec[_ECD_ENTRIES_TOTAL] = dircount2
219 endrec[_ECD_SIZE] = dirsize
220 endrec[_ECD_OFFSET] = diroffset
221 return endrec
222
223
224 def _EndRecData(fpin):
225 """Return data from the "End of Central Directory" record, or None.
226
227 The data is a list of the nine items in the ZIP "End of central dir"
228 record followed by a tenth item, the file seek offset of this record."""
229
230 # Determine file size
231 fpin.seek(0, 2)
232 filesize = fpin.tell()
233
234 # Check to see if this is ZIP file with no archive comment (the
235 # "end of central directory" structure should be the last item in the
236 # file if this is the case).
237 try:
238 fpin.seek(-sizeEndCentDir, 2)
239 except IOError:
240 return None
241 data = fpin.read()
242 if (len(data) == sizeEndCentDir and
243 data[0:4] == stringEndArchive and
244 data[-2:] == b"\000\000"):
245 # the signature is correct and there's no comment, unpack structure
246 endrec = struct.unpack(structEndArchive, data)
247 endrec=list(endrec)
248
249 # Append a blank comment and record start offset
250 endrec.append("")
251 endrec.append(filesize - sizeEndCentDir)
252
253 # Try to read the "Zip64 end of central directory" structure
254 return _EndRecData64(fpin, -sizeEndCentDir, endrec)
255
256 # Either this is not a ZIP file, or it is a ZIP file with an archive
257 # comment. Search the end of the file for the "end of central directory"
258 # record signature. The comment is the last item in the ZIP file and may be
259 # up to 64K long. It is assumed that the "end of central directory" magic
260 # number does not appear in the comment.
261 maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
262 fpin.seek(maxCommentStart, 0)
263 data = fpin.read()
264 start = data.rfind(stringEndArchive)
265 if start >= 0:
266 # found the magic number; attempt to unpack and interpret
267 recData = data[start:start+sizeEndCentDir]
268 if len(recData) != sizeEndCentDir:
269 # Zip file is corrupted.
270 return None
271 endrec = list(struct.unpack(structEndArchive, recData))
272 commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
273 comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
274 endrec.append(comment)
275 endrec.append(maxCommentStart + start)
276
277 # Try to read the "Zip64 end of central directory" structure
278 return _EndRecData64(fpin, maxCommentStart + start - filesize,
279 endrec)
280
281 # Unable to find a valid end of central directory structure
282 return None
283
284
285 class ZipInfo (object):
286 """Class with attributes describing each file in the ZIP archive."""
287
288 __slots__ = (
289 'orig_filename',
290 'filename',
291 'date_time',
292 'compress_type',
293 'comment',
294 'extra',
295 'create_system',
296 'create_version',
297 'extract_version',
298 'reserved',
299 'flag_bits',
300 'volume',
301 'internal_attr',
302 'external_attr',
303 'header_offset',
304 'CRC',
305 'compress_size',
306 'file_size',
307 '_raw_time',
308 )
309
310 def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
311 self.orig_filename = filename # Original file name in archive
312
313 # Terminate the file name at the first null byte. Null bytes in file
314 # names are used as tricks by viruses in archives.
315 null_byte = filename.find(chr(0))
316 if null_byte >= 0:
317 filename = filename[0:null_byte]
318 # This is used to ensure paths in generated ZIP files always use
319 # forward slashes as the directory separator, as required by the
320 # ZIP format specification.
321 if os.sep != "/" and os.sep in filename:
322 filename = filename.replace(os.sep, "/")
323
324 self.filename = filename # Normalized file name
325 self.date_time = date_time # year, month, day, hour, min, sec
326
327 if date_time[0] < 1980:
328 raise ValueError('ZIP does not support timestamps before 1980')
329
330 # Standard values:
331 self.compress_type = ZIP_STORED # Type of compression for the file
332 self.comment = "" # Comment for each file
333 self.extra = "" # ZIP extra data
334 if sys.platform == 'win32':
335 self.create_system = 0 # System which created ZIP archive
336 else:
337 # Assume everything else is unix-y
338 self.create_system = 3 # System which created ZIP archive
339 self.create_version = 20 # Version which created ZIP archive
340 self.extract_version = 20 # Version needed to extract archive
341 self.reserved = 0 # Must be zero
342 self.flag_bits = 0 # ZIP flag bits
343 self.volume = 0 # Volume number of file header
344 self.internal_attr = 0 # Internal attributes
345 self.external_attr = 0 # External file attributes
346 # Other attributes are set by class ZipFile:
347 # header_offset Byte offset to the file header
348 # CRC CRC-32 of the uncompressed file
349 # compress_size Size of the compressed file
350 # file_size Size of the uncompressed file
351
352 def FileHeader(self, zip64=None):
353 """Return the per-file header as a string."""
354 dt = self.date_time
355 dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
356 dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
357 if self.flag_bits & 0x08:
358 # Set these to zero because we write them after the file data
359 CRC = compress_size = file_size = 0
360 else:
361 CRC = self.CRC
362 compress_size = self.compress_size
363 file_size = self.file_size
364
365 extra = self.extra
366
367 if zip64 is None:
368 zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT
369 if zip64:
370 fmt = '<HHQQ'
371 extra = extra + struct.pack(fmt,
372 1, struct.calcsize(fmt)-4, file_size, compress_size)
373 if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
374 if not zip64:
375 raise LargeZipFile("Filesize would require ZIP64 extensions")
376 # File is larger than what fits into a 4 byte integer,
377 # fall back to the ZIP64 extension
378 file_size = 0xffffffff
379 compress_size = 0xffffffff
380 self.extract_version = max(45, self.extract_version)
381 self.create_version = max(45, self.extract_version)
382
383 filename, flag_bits = self._encodeFilenameFlags()
384 header = struct.pack(structFileHeader, stringFileHeader,
385 self.extract_version, self.reserved, flag_bits,
386 self.compress_type, dostime, dosdate, CRC,
387 compress_size, file_size,
388 len(filename), len(extra))
389 return header + filename + extra
390
391 def _encodeFilenameFlags(self):
392 if isinstance(self.filename, unicode):
393 try:
394 return self.filename.encode('ascii'), self.flag_bits
395 except UnicodeEncodeError:
396 return self.filename.encode('utf-8'), self.flag_bits | 0x800
397 else:
398 return self.filename, self.flag_bits
399
400 def _decodeFilename(self):
401 if self.flag_bits & 0x800:
402 return self.filename.decode('utf-8')
403 else:
404 return self.filename
405
406 def _decodeExtra(self):
407 # Try to decode the extra field.
408 extra = self.extra
409 unpack = struct.unpack
410 while len(extra) >= 4:
411 tp, ln = unpack('<HH', extra[:4])
412 if tp == 1:
413 if ln >= 24:
414 counts = unpack('<QQQ', extra[4:28])
415 elif ln == 16:
416 counts = unpack('<QQ', extra[4:20])
417 elif ln == 8:
418 counts = unpack('<Q', extra[4:12])
419 elif ln == 0:
420 counts = ()
421 else:
422 raise RuntimeError, "Corrupt extra field %s"%(ln,)
423
424 idx = 0
425
426 # ZIP64 extension (large files and/or large archives)
427 if self.file_size in (0xffffffffffffffffL, 0xffffffffL):
428 self.file_size = counts[idx]
429 idx += 1
430
431 if self.compress_size == 0xFFFFFFFFL:
432 self.compress_size = counts[idx]
433 idx += 1
434
435 if self.header_offset == 0xffffffffL:
436 old = self.header_offset
437 self.header_offset = counts[idx]
438 idx+=1
439
440 extra = extra[ln+4:]
441
442
443 class _ZipDecrypter:
444 """Class to handle decryption of files stored within a ZIP archive.
445
446 ZIP supports a password-based form of encryption. Even though known
447 plaintext attacks have been found against it, it is still useful
448 to be able to get data out of such a file.
449
450 Usage:
451 zd = _ZipDecrypter(mypwd)
452 plain_char = zd(cypher_char)
453 plain_text = map(zd, cypher_text)
454 """
455
456 def _GenerateCRCTable():
457 """Generate a CRC-32 table.
458
459 ZIP encryption uses the CRC32 one-byte primitive for scrambling some
460 internal keys. We noticed that a direct implementation is faster than
461 relying on binascii.crc32().
462 """
463 poly = 0xedb88320
464 table = [0] * 256
465 for i in range(256):
466 crc = i
467 for j in range(8):
468 if crc & 1:
469 crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly
470 else:
471 crc = ((crc >> 1) & 0x7FFFFFFF)
472 table[i] = crc
473 return table
474 crctable = _GenerateCRCTable()
475
476 def _crc32(self, ch, crc):
477 """Compute the CRC32 primitive on one byte."""
478 return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
479
480 def __init__(self, pwd):
481 self.key0 = 305419896
482 self.key1 = 591751049
483 self.key2 = 878082192
484 for p in pwd:
485 self._UpdateKeys(p)
486
487 def _UpdateKeys(self, c):
488 self.key0 = self._crc32(c, self.key0)
489 self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295
490 self.key1 = (self.key1 * 134775813 + 1) & 4294967295
491 self.key2 = self._crc32(chr((self.key1 >> 24) & 255), self.key2)
492
493 def __call__(self, c):
494 """Decrypt a single character."""
495 c = ord(c)
496 k = self.key2 | 2
497 c = c ^ (((k * (k^1)) >> 8) & 255)
498 c = chr(c)
499 self._UpdateKeys(c)
500 return c
501
502
503 compressor_names = {
504 0: 'store',
505 1: 'shrink',
506 2: 'reduce',
507 3: 'reduce',
508 4: 'reduce',
509 5: 'reduce',
510 6: 'implode',
511 7: 'tokenize',
512 8: 'deflate',
513 9: 'deflate64',
514 10: 'implode',
515 12: 'bzip2',
516 14: 'lzma',
517 18: 'terse',
518 19: 'lz77',
519 97: 'wavpack',
520 98: 'ppmd',
521 }
522
523
524 class ZipExtFile(io.BufferedIOBase):
525 """File-like object for reading an archive member.
526 Is returned by ZipFile.open().
527 """
528
529 # Max size supported by decompressor.
530 MAX_N = 1 << 31 - 1
531
532 # Read from compressed files in 4k blocks.
533 MIN_READ_SIZE = 4096
534
535 # Search for universal newlines or line chunks.
536 PATTERN = re.compile(r'^(?P<chunk>[^\r\n]+)|(?P<newline>\n|\r\n?)')
537
538 def __init__(self, fileobj, mode, zipinfo, decrypter=None,
539 close_fileobj=False):
540 self._fileobj = fileobj
541 self._decrypter = decrypter
542 self._close_fileobj = close_fileobj
543
544 self._compress_type = zipinfo.compress_type
545 self._compress_size = zipinfo.compress_size
546 self._compress_left = zipinfo.compress_size
547
548 if self._compress_type == ZIP_DEFLATED:
549 self._decompressor = zlib.decompressobj(-15)
550 elif self._compress_type != ZIP_STORED:
551 descr = compressor_names.get(self._compress_type)
552 if descr:
553 raise NotImplementedError("compression type %d (%s)" % (self._compress_type, descr))
554 else:
555 raise NotImplementedError("compression type %d" % (self._compress_type,))
556 self._unconsumed = ''
557
558 self._readbuffer = ''
559 self._offset = 0
560
561 self._universal = 'U' in mode
562 self.newlines = None
563
564 # Adjust read size for encrypted files since the first 12 bytes
565 # are for the encryption/password information.
566 if self._decrypter is not None:
567 self._compress_left -= 12
568
569 self.mode = mode
570 self.name = zipinfo.filename
571
572 if hasattr(zipinfo, 'CRC'):
573 self._expected_crc = zipinfo.CRC
574 self._running_crc = crc32(b'') & 0xffffffff
575 else:
576 self._expected_crc = None
577
578 def readline(self, limit=-1):
579 """Read and return a line from the stream.
580
581 If limit is specified, at most limit bytes will be read.
582 """
583
584 if not self._universal and limit < 0:
585 # Shortcut common case - newline found in buffer.
586 i = self._readbuffer.find('\n', self._offset) + 1
587 if i > 0:
588 line = self._readbuffer[self._offset: i]
589 self._offset = i
590 return line
591
592 if not self._universal:
593 return io.BufferedIOBase.readline(self, limit)
594
595 line = ''
596 while limit < 0 or len(line) < limit:
597 readahead = self.peek(2)
598 if readahead == '':
599 return line
600
601 #
602 # Search for universal newlines or line chunks.
603 #
604 # The pattern returns either a line chunk or a newline, but not
605 # both. Combined with peek(2), we are assured that the sequence
606 # '\r\n' is always retrieved completely and never split into
607 # separate newlines - '\r', '\n' due to coincidental readaheads.
608 #
609 match = self.PATTERN.search(readahead)
610 newline = match.group('newline')
611 if newline is not None:
612 if self.newlines is None:
613 self.newlines = []
614 if newline not in self.newlines:
615 self.newlines.append(newline)
616 self._offset += len(newline)
617 return line + '\n'
618
619 chunk = match.group('chunk')
620 if limit >= 0:
621 chunk = chunk[: limit - len(line)]
622
623 self._offset += len(chunk)
624 line += chunk
625
626 return line
627
628 def peek(self, n=1):
629 """Returns buffered bytes without advancing the position."""
630 if n > len(self._readbuffer) - self._offset:
631 chunk = self.read(n)
632 if len(chunk) > self._offset:
633 self._readbuffer = chunk + self._readbuffer[self._offset:]
634 self._offset = 0
635 else:
636 self._offset -= len(chunk)
637
638 # Return up to 512 bytes to reduce allocation overhead for tight loops.
639 return self._readbuffer[self._offset: self._offset + 512]
640
641 def readable(self):
642 return True
643
644 def read(self, n=-1):
645 """Read and return up to n bytes.
646 If the argument is omitted, None, or negative, data is read and returned until EOF is reached..
647 """
648 buf = ''
649 if n is None:
650 n = -1
651 while True:
652 if n < 0:
653 data = self.read1(n)
654 elif n > len(buf):
655 data = self.read1(n - len(buf))
656 else:
657 return buf
658 if len(data) == 0:
659 return buf
660 buf += data
661
662 def _update_crc(self, newdata, eof):
663 # Update the CRC using the given data.
664 if self._expected_crc is None:
665 # No need to compute the CRC if we don't have a reference value
666 return
667 self._running_crc = crc32(newdata, self._running_crc) & 0xffffffff
668 # Check the CRC if we're at the end of the file
669 if eof and self._running_crc != self._expected_crc:
670 raise BadZipfile("Bad CRC-32 for file %r" % self.name)
671
672 def read1(self, n):
673 """Read up to n bytes with at most one read() system call."""
674
675 # Simplify algorithm (branching) by transforming negative n to large n.
676 if n < 0 or n is None:
677 n = self.MAX_N
678
679 # Bytes available in read buffer.
680 len_readbuffer = len(self._readbuffer) - self._offset
681
682 # Read from file.
683 if self._compress_left > 0 and n > len_readbuffer + len(self._unconsumed):
684 nbytes = n - len_readbuffer - len(self._unconsumed)
685 nbytes = max(nbytes, self.MIN_READ_SIZE)
686 nbytes = min(nbytes, self._compress_left)
687
688 data = self._fileobj.read(nbytes)
689 self._compress_left -= len(data)
690
691 if data and self._decrypter is not None:
692 data = ''.join(map(self._decrypter, data))
693
694 if self._compress_type == ZIP_STORED:
695 self._update_crc(data, eof=(self._compress_left==0))
696 self._readbuffer = self._readbuffer[self._offset:] + data
697 self._offset = 0
698 else:
699 # Prepare deflated bytes for decompression.
700 self._unconsumed += data
701
702 # Handle unconsumed data.
703 if (len(self._unconsumed) > 0 and n > len_readbuffer and
704 self._compress_type == ZIP_DEFLATED):
705 data = self._decompressor.decompress(
706 self._unconsumed,
707 max(n - len_readbuffer, self.MIN_READ_SIZE)
708 )
709
710 self._unconsumed = self._decompressor.unconsumed_tail
711 eof = len(self._unconsumed) == 0 and self._compress_left == 0
712 if eof:
713 data += self._decompressor.flush()
714
715 self._update_crc(data, eof=eof)
716 self._readbuffer = self._readbuffer[self._offset:] + data
717 self._offset = 0
718
719 # Read from buffer.
720 data = self._readbuffer[self._offset: self._offset + n]
721 self._offset += len(data)
722 return data
723
724 def close(self):
725 try :
726 if self._close_fileobj:
727 self._fileobj.close()
728 finally:
729 super(ZipExtFile, self).close()
730
731
732 class ZipFile(object):
733 """ Class with methods to open, read, write, close, list zip files.
734
735 z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=False)
736
737 file: Either the path to the file, or a file-like object.
738 If it is a path, the file will be opened and closed by ZipFile.
739 mode: The mode can be either read "r", write "w" or append "a".
740 compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib).
741 allowZip64: if True ZipFile will create files with ZIP64 extensions when
742 needed, otherwise it will raise an exception when this would
743 be necessary.
744
745 """
746
747 fp = None # Set here since __del__ checks it
748
749 def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False):
750 """Open the ZIP file with mode read "r", write "w" or append "a"."""
751 if mode not in ("r", "w", "a"):
752 raise RuntimeError('ZipFile() requires mode "r", "w", or "a"')
753
754 if compression == ZIP_STORED:
755 pass
756 elif compression == ZIP_DEFLATED:
757 if not zlib:
758 raise RuntimeError,\
759 "Compression requires the (missing) zlib module"
760 else:
761 raise RuntimeError, "That compression method is not supported"
762
763 self._allowZip64 = allowZip64
764 self._didModify = False
765 self.debug = 0 # Level of printing: 0 through 3
766 self.NameToInfo = {} # Find file info given name
767 self.filelist = [] # List of ZipInfo instances for archive
768 self.compression = compression # Method of compression
769 self.mode = key = mode.replace('b', '')[0]
770 self.pwd = None
771 self._comment = ''
772
773 # Check if we were passed a file-like object
774 if isinstance(file, basestring):
775 self._filePassed = 0
776 self.filename = file
777 modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}
778 try:
779 self.fp = open(file, modeDict[mode])
780 except IOError:
781 if mode == 'a':
782 mode = key = 'w'
783 self.fp = open(file, modeDict[mode])
784 else:
785 raise
786 else:
787 self._filePassed = 1
788 self.fp = file
789 self.filename = getattr(file, 'name', None)
790
791 try:
792 if key == 'r':
793 self._RealGetContents()
794 elif key == 'w':
795 # set the modified flag so central directory gets written
796 # even if no files are added to the archive
797 self._didModify = True
798 elif key == 'a':
799 try:
800 # See if file is a zip file
801 self._RealGetContents()
802 # seek to start of directory and overwrite
803 self.fp.seek(self.start_dir, 0)
804 except BadZipfile:
805 # file is not a zip file, just append
806 self.fp.seek(0, 2)
807
808 # set the modified flag so central directory gets written
809 # even if no files are added to the archive
810 self._didModify = True
811 else:
812 raise RuntimeError('Mode must be "r", "w" or "a"')
813 except:
814 fp = self.fp
815 self.fp = None
816 if not self._filePassed:
817 fp.close()
818 raise
819
820 def __enter__(self):
821 return self
822
823 def __exit__(self, type, value, traceback):
824 self.close()
825
826 def _RealGetContents(self):
827 """Read in the table of contents for the ZIP file."""
828 fp = self.fp
829 try:
830 endrec = _EndRecData(fp)
831 except IOError:
832 raise BadZipfile("File is not a zip file")
833 if not endrec:
834 raise BadZipfile, "File is not a zip file"
835 if self.debug > 1:
836 print endrec
837 size_cd = endrec[_ECD_SIZE] # bytes in central directory
838 offset_cd = endrec[_ECD_OFFSET] # offset of central directory
839 self._comment = endrec[_ECD_COMMENT] # archive comment
840
841 # "concat" is zero, unless zip was concatenated to another file
842 concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
843 if endrec[_ECD_SIGNATURE] == stringEndArchive64:
844 # If Zip64 extension structures are present, account for them
845 concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
846
847 if self.debug > 2:
848 inferred = concat + offset_cd
849 print "given, inferred, offset", offset_cd, inferred, concat
850 # self.start_dir: Position of start of central directory
851 self.start_dir = offset_cd + concat
852 fp.seek(self.start_dir, 0)
853 data = fp.read(size_cd)
854 fp = cStringIO.StringIO(data)
855 total = 0
856 while total < size_cd:
857 centdir = fp.read(sizeCentralDir)
858 if len(centdir) != sizeCentralDir:
859 raise BadZipfile("Truncated central directory")
860 centdir = struct.unpack(structCentralDir, centdir)
861 if centdir[_CD_SIGNATURE] != stringCentralDir:
862 raise BadZipfile("Bad magic number for central directory")
863 if self.debug > 2:
864 print centdir
865 filename = fp.read(centdir[_CD_FILENAME_LENGTH])
866 # Create ZipInfo instance to store file information
867 x = ZipInfo(filename)
868 x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
869 x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
870 x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
871 (x.create_version, x.create_system, x.extract_version, x.reserved,
872 x.flag_bits, x.compress_type, t, d,
873 x.CRC, x.compress_size, x.file_size) = centdir[1:12]
874 x.volume, x.internal_attr, x.external_attr = centdir[15:18]
875 # Convert date/time code to (year, month, day, hour, min, sec)
876 x._raw_time = t
877 x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
878 t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
879
880 x._decodeExtra()
881 x.header_offset = x.header_offset + concat
882 x.filename = x._decodeFilename()
883 self.filelist.append(x)
884 self.NameToInfo[x.filename] = x
885
886 # update total bytes read from central directory
887 total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]
888 + centdir[_CD_EXTRA_FIELD_LENGTH]
889 + centdir[_CD_COMMENT_LENGTH])
890
891 if self.debug > 2:
892 print "total", total
893
894
895 def namelist(self):
896 """Return a list of file names in the archive."""
897 l = []
898 for data in self.filelist:
899 l.append(data.filename)
900 return l
901
902 def infolist(self):
903 """Return a list of class ZipInfo instances for files in the
904 archive."""
905 return self.filelist
906
907 def printdir(self):
908 """Print a table of contents for the zip file."""
909 print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
910 for zinfo in self.filelist:
911 date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
912 print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
913
914 def testzip(self):
915 """Read all the files and check the CRC."""
916 chunk_size = 2 ** 20
917 for zinfo in self.filelist:
918 try:
919 # Read by chunks, to avoid an OverflowError or a
920 # MemoryError with very large embedded files.
921 with self.open(zinfo.filename, "r") as f:
922 while f.read(chunk_size): # Check CRC-32
923 pass
924 except BadZipfile:
925 return zinfo.filename
926
927 def getinfo(self, name):
928 """Return the instance of ZipInfo given 'name'."""
929 info = self.NameToInfo.get(name)
930 if info is None:
931 raise KeyError(
932 'There is no item named %r in the archive' % name)
933
934 return info
935
936 def setpassword(self, pwd):
937 """Set default password for encrypted files."""
938 self.pwd = pwd
939
940 @property
941 def comment(self):
942 """The comment text associated with the ZIP file."""
943 return self._comment
944
945 @comment.setter
946 def comment(self, comment):
947 # check for valid comment length
948 if len(comment) > ZIP_MAX_COMMENT:
949 import warnings
950 warnings.warn('Archive comment is too long; truncating to %d bytes'
951 % ZIP_MAX_COMMENT, stacklevel=2)
952 comment = comment[:ZIP_MAX_COMMENT]
953 self._comment = comment
954 self._didModify = True
955
956 def read(self, name, pwd=None):
957 """Return file bytes (as a string) for name."""
958 return self.open(name, "r", pwd).read()
959
960 def open(self, name, mode="r", pwd=None):
961 """Return file-like object for 'name'."""
962 if mode not in ("r", "U", "rU"):
963 raise RuntimeError, 'open() requires mode "r", "U", or "rU"'
964 if not self.fp:
965 raise RuntimeError, \
966 "Attempt to read ZIP archive that was already closed"
967
968 # Only open a new file for instances where we were not
969 # given a file object in the constructor
970 if self._filePassed:
971 zef_file = self.fp
972 should_close = False
973 else:
974 zef_file = open(self.filename, 'rb')
975 should_close = True
976
977 try:
978 # Make sure we have an info object
979 if isinstance(name, ZipInfo):
980 # 'name' is already an info object
981 zinfo = name
982 else:
983 # Get info object for name
984 zinfo = self.getinfo(name)
985
986 zef_file.seek(zinfo.header_offset, 0)
987
988 # Skip the file header:
989 fheader = zef_file.read(sizeFileHeader)
990 if len(fheader) != sizeFileHeader:
991 raise BadZipfile("Truncated file header")
992 fheader = struct.unpack(structFileHeader, fheader)
993 if fheader[_FH_SIGNATURE] != stringFileHeader:
994 raise BadZipfile("Bad magic number for file header")
995
996 fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
997 if fheader[_FH_EXTRA_FIELD_LENGTH]:
998 zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
999
1000 if fname != zinfo.orig_filename:
1001 raise BadZipfile, \
1002 'File name in directory "%s" and header "%s" differ.' % (
1003 zinfo.orig_filename, fname)
1004
1005 # check for encrypted flag & handle password
1006 is_encrypted = zinfo.flag_bits & 0x1
1007 zd = None
1008 if is_encrypted:
1009 if not pwd:
1010 pwd = self.pwd
1011 if not pwd:
1012 raise RuntimeError, "File %s is encrypted, " \
1013 "password required for extraction" % name
1014
1015 zd = _ZipDecrypter(pwd)
1016 # The first 12 bytes in the cypher stream is an encryption header
1017 # used to strengthen the algorithm. The first 11 bytes are
1018 # completely random, while the 12th contains the MSB of the CRC,
1019 # or the MSB of the file time depending on the header type
1020 # and is used to check the correctness of the password.
1021 bytes = zef_file.read(12)
1022 h = map(zd, bytes[0:12])
1023 if zinfo.flag_bits & 0x8:
1024 # compare against the file type from extended local headers
1025 check_byte = (zinfo._raw_time >> 8) & 0xff
1026 else:
1027 # compare against the CRC otherwise
1028 check_byte = (zinfo.CRC >> 24) & 0xff
1029 if ord(h[11]) != check_byte:
1030 raise RuntimeError("Bad password for file", name)
1031
1032 return ZipExtFile(zef_file, mode, zinfo, zd,
1033 close_fileobj=should_close)
1034 except:
1035 if should_close:
1036 zef_file.close()
1037 raise
1038
1039 def extract(self, member, path=None, pwd=None):
1040 """Extract a member from the archive to the current working directory,
1041 using its full name. Its file information is extracted as accurately
1042 as possible. `member' may be a filename or a ZipInfo object. You can
1043 specify a different directory using `path'.
1044 """
1045 if not isinstance(member, ZipInfo):
1046 member = self.getinfo(member)
1047
1048 if path is None:
1049 path = os.getcwd()
1050
1051 return self._extract_member(member, path, pwd)
1052
1053 def extractall(self, path=None, members=None, pwd=None):
1054 """Extract all members from the archive to the current working
1055 directory. `path' specifies a different directory to extract to.
1056 `members' is optional and must be a subset of the list returned
1057 by namelist().
1058 """
1059 if members is None:
1060 members = self.namelist()
1061
1062 for zipinfo in members:
1063 self.extract(zipinfo, path, pwd)
1064
1065 def _extract_member(self, member, targetpath, pwd):
1066 """Extract the ZipInfo object 'member' to a physical
1067 file on the path targetpath.
1068 """
1069 # build the destination pathname, replacing
1070 # forward slashes to platform specific separators.
1071 arcname = member.filename.replace('/', os.path.sep)
1072
1073 if os.path.altsep:
1074 arcname = arcname.replace(os.path.altsep, os.path.sep)
1075 # interpret absolute pathname as relative, remove drive letter or
1076 # UNC path, redundant separators, "." and ".." components.
1077 arcname = os.path.splitdrive(arcname)[1]
1078 arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
1079 if x not in ('', os.path.curdir, os.path.pardir))
1080 if os.path.sep == '\\':
1081 # filter illegal characters on Windows
1082 illegal = ':<>|"?*'
1083 if isinstance(arcname, unicode):
1084 table = {ord(c): ord('_') for c in illegal}
1085 else:
1086 table = string.maketrans(illegal, '_' * len(illegal))
1087 arcname = arcname.translate(table)
1088 # remove trailing dots
1089 arcname = (x.rstrip('.') for x in arcname.split(os.path.sep))
1090 arcname = os.path.sep.join(x for x in arcname if x)
1091
1092 targetpath = os.path.join(targetpath, arcname)
1093 targetpath = os.path.normpath(targetpath)
1094
1095 # Create all upper directories if necessary.
1096 upperdirs = os.path.dirname(targetpath)
1097 if upperdirs and not os.path.exists(upperdirs):
1098 os.makedirs(upperdirs)
1099
1100 if member.filename[-1] == '/':
1101 if not os.path.isdir(targetpath):
1102 os.mkdir(targetpath)
1103 return targetpath
1104
1105 with self.open(member, pwd=pwd) as source, \
1106 file(targetpath, "wb") as target:
1107 shutil.copyfileobj(source, target)
1108
1109 return targetpath
1110
1111 def _writecheck(self, zinfo):
1112 """Check for errors before writing a file to the archive."""
1113 if zinfo.filename in self.NameToInfo:
1114 import warnings
1115 warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
1116 if self.mode not in ("w", "a"):
1117 raise RuntimeError, 'write() requires mode "w" or "a"'
1118 if not self.fp:
1119 raise RuntimeError, \
1120 "Attempt to write ZIP archive that was already closed"
1121 if zinfo.compress_type == ZIP_DEFLATED and not zlib:
1122 raise RuntimeError, \
1123 "Compression requires the (missing) zlib module"
1124 if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED):
1125 raise RuntimeError, \
1126 "That compression method is not supported"
1127 if not self._allowZip64:
1128 requires_zip64 = None
1129 if len(self.filelist) >= ZIP_FILECOUNT_LIMIT:
1130 requires_zip64 = "Files count"
1131 elif zinfo.file_size > ZIP64_LIMIT:
1132 requires_zip64 = "Filesize"
1133 elif zinfo.header_offset > ZIP64_LIMIT:
1134 requires_zip64 = "Zipfile size"
1135 if requires_zip64:
1136 raise LargeZipFile(requires_zip64 +
1137 " would require ZIP64 extensions")
1138
1139 def write(self, filename, arcname=None, compress_type=None):
1140 """Put the bytes from filename into the archive under the name
1141 arcname."""
1142 if not self.fp:
1143 raise RuntimeError(
1144 "Attempt to write to ZIP archive that was already closed")
1145
1146 st = os.stat(filename)
1147 isdir = stat.S_ISDIR(st.st_mode)
1148 mtime = time.localtime(st.st_mtime)
1149 date_time = mtime[0:6]
1150 # Create ZipInfo instance to store file information
1151 if arcname is None:
1152 arcname = filename
1153 arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
1154 while arcname[0] in (os.sep, os.altsep):
1155 arcname = arcname[1:]
1156 if isdir:
1157 arcname += '/'
1158 zinfo = ZipInfo(arcname, date_time)
1159 zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes
1160 if isdir:
1161 zinfo.compress_type = ZIP_STORED
1162 elif compress_type is None:
1163 zinfo.compress_type = self.compression
1164 else:
1165 zinfo.compress_type = compress_type
1166
1167 zinfo.file_size = st.st_size
1168 zinfo.flag_bits = 0x00
1169 zinfo.header_offset = self.fp.tell() # Start of header bytes
1170
1171 self._writecheck(zinfo)
1172 self._didModify = True
1173
1174 if isdir:
1175 zinfo.file_size = 0
1176 zinfo.compress_size = 0
1177 zinfo.CRC = 0
1178 zinfo.external_attr |= 0x10 # MS-DOS directory flag
1179 self.filelist.append(zinfo)
1180 self.NameToInfo[zinfo.filename] = zinfo
1181 self.fp.write(zinfo.FileHeader(False))
1182 return
1183
1184 with open(filename, "rb") as fp:
1185 # Must overwrite CRC and sizes with correct data later
1186 zinfo.CRC = CRC = 0
1187 zinfo.compress_size = compress_size = 0
1188 # Compressed size can be larger than uncompressed size
1189 zip64 = self._allowZip64 and \
1190 zinfo.file_size * 1.05 > ZIP64_LIMIT
1191 self.fp.write(zinfo.FileHeader(zip64))
1192 if zinfo.compress_type == ZIP_DEFLATED:
1193 cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
1194 zlib.DEFLATED, -15)
1195 else:
1196 cmpr = None
1197 file_size = 0
1198 while 1:
1199 buf = fp.read(1024 * 8)
1200 if not buf:
1201 break
1202 file_size = file_size + len(buf)
1203 CRC = crc32(buf, CRC) & 0xffffffff
1204 if cmpr:
1205 buf = cmpr.compress(buf)
1206 compress_size = compress_size + len(buf)
1207 self.fp.write(buf)
1208 if cmpr:
1209 buf = cmpr.flush()
1210 compress_size = compress_size + len(buf)
1211 self.fp.write(buf)
1212 zinfo.compress_size = compress_size
1213 else:
1214 zinfo.compress_size = file_size
1215 zinfo.CRC = CRC
1216 zinfo.file_size = file_size
1217 if not zip64 and self._allowZip64:
1218 if file_size > ZIP64_LIMIT:
1219 raise RuntimeError('File size has increased during compressing')
1220 if compress_size > ZIP64_LIMIT:
1221 raise RuntimeError('Compressed size larger than uncompressed size')
1222 # Seek backwards and write file header (which will now include
1223 # correct CRC and file sizes)
1224 position = self.fp.tell() # Preserve current position in file
1225 self.fp.seek(zinfo.header_offset, 0)
1226 self.fp.write(zinfo.FileHeader(zip64))
1227 self.fp.seek(position, 0)
1228 self.filelist.append(zinfo)
1229 self.NameToInfo[zinfo.filename] = zinfo
1230
1231 def writestr(self, zinfo_or_arcname, bytes, compress_type=None):
1232 """Write a file into the archive. The contents is the string
1233 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or
1234 the name of the file in the archive."""
1235 if not isinstance(zinfo_or_arcname, ZipInfo):
1236 zinfo = ZipInfo(filename=zinfo_or_arcname,
1237 date_time=time.localtime(time.time())[:6])
1238
1239 zinfo.compress_type = self.compression
1240 if zinfo.filename[-1] == '/':
1241 zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
1242 zinfo.external_attr |= 0x10 # MS-DOS directory flag
1243 else:
1244 zinfo.external_attr = 0o600 << 16 # ?rw-------
1245 else:
1246 zinfo = zinfo_or_arcname
1247
1248 if not self.fp:
1249 raise RuntimeError(
1250 "Attempt to write to ZIP archive that was already closed")
1251
1252 if compress_type is not None:
1253 zinfo.compress_type = compress_type
1254
1255 zinfo.file_size = len(bytes) # Uncompressed size
1256 zinfo.header_offset = self.fp.tell() # Start of header bytes
1257 self._writecheck(zinfo)
1258 self._didModify = True
1259 zinfo.CRC = crc32(bytes) & 0xffffffff # CRC-32 checksum
1260 if zinfo.compress_type == ZIP_DEFLATED:
1261 co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
1262 zlib.DEFLATED, -15)
1263 bytes = co.compress(bytes) + co.flush()
1264 zinfo.compress_size = len(bytes) # Compressed size
1265 else:
1266 zinfo.compress_size = zinfo.file_size
1267 zip64 = zinfo.file_size > ZIP64_LIMIT or \
1268 zinfo.compress_size > ZIP64_LIMIT
1269 if zip64 and not self._allowZip64:
1270 raise LargeZipFile("Filesize would require ZIP64 extensions")
1271 self.fp.write(zinfo.FileHeader(zip64))
1272 self.fp.write(bytes)
1273 if zinfo.flag_bits & 0x08:
1274 # Write CRC and file sizes after the file data
1275 fmt = '<LLQQ' if zip64 else '<LLLL'
1276 self.fp.write(struct.pack(fmt, _DD_SIGNATURE, zinfo.CRC,
1277 zinfo.compress_size, zinfo.file_size))
1278 self.fp.flush()
1279 self.filelist.append(zinfo)
1280 self.NameToInfo[zinfo.filename] = zinfo
1281
1282 def __del__(self):
1283 """Call the "close()" method in case the user forgot."""
1284 self.close()
1285
1286 def close(self):
1287 """Close the file, and for mode "w" and "a" write the ending
1288 records."""
1289 if self.fp is None:
1290 return
1291
1292 try:
1293 if self.mode in ("w", "a") and self._didModify: # write ending records
1294 pos1 = self.fp.tell()
1295 for zinfo in self.filelist: # write central directory
1296 dt = zinfo.date_time
1297 dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
1298 dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
1299 extra = []
1300 if zinfo.file_size > ZIP64_LIMIT \
1301 or zinfo.compress_size > ZIP64_LIMIT:
1302 extra.append(zinfo.file_size)
1303 extra.append(zinfo.compress_size)
1304 file_size = 0xffffffff
1305 compress_size = 0xffffffff
1306 else:
1307 file_size = zinfo.file_size
1308 compress_size = zinfo.compress_size
1309
1310 if zinfo.header_offset > ZIP64_LIMIT:
1311 extra.append(zinfo.header_offset)
1312 header_offset = 0xffffffffL
1313 else:
1314 header_offset = zinfo.header_offset
1315
1316 extra_data = zinfo.extra
1317 if extra:
1318 # Append a ZIP64 field to the extra's
1319 extra_data = _strip_extra(extra_data, (1,))
1320 extra_data = struct.pack(
1321 '<HH' + 'Q'*len(extra),
1322 1, 8*len(extra), *extra) + extra_data
1323
1324 extract_version = max(45, zinfo.extract_version)
1325 create_version = max(45, zinfo.create_version)
1326 else:
1327 extract_version = zinfo.extract_version
1328 create_version = zinfo.create_version
1329
1330 try:
1331 filename, flag_bits = zinfo._encodeFilenameFlags()
1332 centdir = struct.pack(structCentralDir,
1333 stringCentralDir, create_version,
1334 zinfo.create_system, extract_version, zinfo.reserved,
1335 flag_bits, zinfo.compress_type, dostime, dosdate,
1336 zinfo.CRC, compress_size, file_size,
1337 len(filename), len(extra_data), len(zinfo.comment),
1338 0, zinfo.internal_attr, zinfo.external_attr,
1339 header_offset)
1340 except DeprecationWarning:
1341 print >>sys.stderr, (structCentralDir,
1342 stringCentralDir, create_version,
1343 zinfo.create_system, extract_version, zinfo.reserved,
1344 zinfo.flag_bits, zinfo.compress_type, dostime, dosdate,
1345 zinfo.CRC, compress_size, file_size,
1346 len(zinfo.filename), len(extra_data), len(zinfo.comment),
1347 0, zinfo.internal_attr, zinfo.external_attr,
1348 header_offset)
1349 raise
1350 self.fp.write(centdir)
1351 self.fp.write(filename)
1352 self.fp.write(extra_data)
1353 self.fp.write(zinfo.comment)
1354
1355 pos2 = self.fp.tell()
1356 # Write end-of-zip-archive record
1357 centDirCount = len(self.filelist)
1358 centDirSize = pos2 - pos1
1359 centDirOffset = pos1
1360 requires_zip64 = None
1361 if centDirCount > ZIP_FILECOUNT_LIMIT:
1362 requires_zip64 = "Files count"
1363 elif centDirOffset > ZIP64_LIMIT:
1364 requires_zip64 = "Central directory offset"
1365 elif centDirSize > ZIP64_LIMIT:
1366 requires_zip64 = "Central directory size"
1367 if requires_zip64:
1368 # Need to write the ZIP64 end-of-archive records
1369 if not self._allowZip64:
1370 raise LargeZipFile(requires_zip64 +
1371 " would require ZIP64 extensions")
1372 zip64endrec = struct.pack(
1373 structEndArchive64, stringEndArchive64,
1374 44, 45, 45, 0, 0, centDirCount, centDirCount,
1375 centDirSize, centDirOffset)
1376 self.fp.write(zip64endrec)
1377
1378 zip64locrec = struct.pack(
1379 structEndArchive64Locator,
1380 stringEndArchive64Locator, 0, pos2, 1)
1381 self.fp.write(zip64locrec)
1382 centDirCount = min(centDirCount, 0xFFFF)
1383 centDirSize = min(centDirSize, 0xFFFFFFFF)
1384 centDirOffset = min(centDirOffset, 0xFFFFFFFF)
1385
1386 endrec = struct.pack(structEndArchive, stringEndArchive,
1387 0, 0, centDirCount, centDirCount,
1388 centDirSize, centDirOffset, len(self._comment))
1389 self.fp.write(endrec)
1390 self.fp.write(self._comment)
1391 self.fp.flush()
1392 finally:
1393 fp = self.fp
1394 self.fp = None
1395 if not self._filePassed:
1396 fp.close()
1397
1398
1399 class PyZipFile(ZipFile):
1400 """Class to create ZIP archives with Python library files and packages."""
1401
1402 def writepy(self, pathname, basename = ""):
1403 """Add all files from "pathname" to the ZIP archive.
1404
1405 If pathname is a package directory, search the directory and
1406 all package subdirectories recursively for all *.py and enter
1407 the modules into the archive. If pathname is a plain
1408 directory, listdir *.py and enter all modules. Else, pathname
1409 must be a Python *.py file and the module will be put into the
1410 archive. Added modules are always module.pyo or module.pyc.
1411 This method will compile the module.py into module.pyc if
1412 necessary.
1413 """
1414 dir, name = os.path.split(pathname)
1415 if os.path.isdir(pathname):
1416 initname = os.path.join(pathname, "__init__.py")
1417 if os.path.isfile(initname):
1418 # This is a package directory, add it
1419 if basename:
1420 basename = "%s/%s" % (basename, name)
1421 else:
1422 basename = name
1423 if self.debug:
1424 print "Adding package in", pathname, "as", basename
1425 fname, arcname = self._get_codename(initname[0:-3], basename)
1426 if self.debug:
1427 print "Adding", arcname
1428 self.write(fname, arcname)
1429 dirlist = os.listdir(pathname)
1430 dirlist.remove("__init__.py")
1431 # Add all *.py files and package subdirectories
1432 for filename in dirlist:
1433 path = os.path.join(pathname, filename)
1434 root, ext = os.path.splitext(filename)
1435 if os.path.isdir(path):
1436 if os.path.isfile(os.path.join(path, "__init__.py")):
1437 # This is a package directory, add it
1438 self.writepy(path, basename) # Recursive call
1439 elif ext == ".py":
1440 fname, arcname = self._get_codename(path[0:-3],
1441 basename)
1442 if self.debug:
1443 print "Adding", arcname
1444 self.write(fname, arcname)
1445 else:
1446 # This is NOT a package directory, add its files at top level
1447 if self.debug:
1448 print "Adding files from directory", pathname
1449 for filename in os.listdir(pathname):
1450 path = os.path.join(pathname, filename)
1451 root, ext = os.path.splitext(filename)
1452 if ext == ".py":
1453 fname, arcname = self._get_codename(path[0:-3],
1454 basename)
1455 if self.debug:
1456 print "Adding", arcname
1457 self.write(fname, arcname)
1458 else:
1459 if pathname[-3:] != ".py":
1460 raise RuntimeError, \
1461 'Files added with writepy() must end with ".py"'
1462 fname, arcname = self._get_codename(pathname[0:-3], basename)
1463 if self.debug:
1464 print "Adding file", arcname
1465 self.write(fname, arcname)
1466
1467 def _get_codename(self, pathname, basename):
1468 """Return (filename, archivename) for the path.
1469
1470 Given a module name path, return the correct file path and
1471 archive name, compiling if necessary. For example, given
1472 /python/lib/string, return (/python/lib/string.pyc, string).
1473 """
1474 file_py = pathname + ".py"
1475 file_pyc = pathname + ".pyc"
1476 file_pyo = pathname + ".pyo"
1477 if os.path.isfile(file_pyo) and \
1478 os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime:
1479 fname = file_pyo # Use .pyo file
1480 elif not os.path.isfile(file_pyc) or \
1481 os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime:
1482 import py_compile
1483 if self.debug:
1484 print "Compiling", file_py
1485 try:
1486 py_compile.compile(file_py, file_pyc, None, True)
1487 except py_compile.PyCompileError,err:
1488 print err.msg
1489 fname = file_pyc
1490 else:
1491 fname = file_pyc
1492 archivename = os.path.split(fname)[1]
1493 if basename:
1494 archivename = "%s/%s" % (basename, archivename)
1495 return (fname, archivename)
1496
1497
1498 def main(args = None):
1499 import textwrap
1500 USAGE=textwrap.dedent("""\
1501 Usage:
1502 zipfile.py -l zipfile.zip # Show listing of a zipfile
1503 zipfile.py -t zipfile.zip # Test if a zipfile is valid
1504 zipfile.py -e zipfile.zip target # Extract zipfile into target dir
1505 zipfile.py -c zipfile.zip src ... # Create zipfile from sources
1506 """)
1507 if args is None:
1508 args = sys.argv[1:]
1509
1510 if not args or args[0] not in ('-l', '-c', '-e', '-t'):
1511 print USAGE
1512 sys.exit(1)
1513
1514 if args[0] == '-l':
1515 if len(args) != 2:
1516 print USAGE
1517 sys.exit(1)
1518 with ZipFile(args[1], 'r') as zf:
1519 zf.printdir()
1520
1521 elif args[0] == '-t':
1522 if len(args) != 2:
1523 print USAGE
1524 sys.exit(1)
1525 with ZipFile(args[1], 'r') as zf:
1526 badfile = zf.testzip()
1527 if badfile:
1528 print("The following enclosed file is corrupted: {!r}".format(badfile))
1529 print "Done testing"
1530
1531 elif args[0] == '-e':
1532 if len(args) != 3:
1533 print USAGE
1534 sys.exit(1)
1535
1536 with ZipFile(args[1], 'r') as zf:
1537 zf.extractall(args[2])
1538
1539 elif args[0] == '-c':
1540 if len(args) < 3:
1541 print USAGE
1542 sys.exit(1)
1543
1544 def addToZip(zf, path, zippath):
1545 if os.path.isfile(path):
1546 zf.write(path, zippath, ZIP_DEFLATED)
1547 elif os.path.isdir(path):
1548 if zippath:
1549 zf.write(path, zippath)
1550 for nm in os.listdir(path):
1551 addToZip(zf,
1552 os.path.join(path, nm), os.path.join(zippath, nm))
1553 # else: ignore
1554
1555 with ZipFile(args[1], 'w', allowZip64=True) as zf:
1556 for path in args[2:]:
1557 zippath = os.path.basename(path)
1558 if not zippath:
1559 zippath = os.path.basename(os.path.dirname(path))
1560 if zippath in ('', os.curdir, os.pardir):
1561 zippath = ''
1562 addToZip(zf, path, zippath)
1563
1564 if __name__ == "__main__":
1565 main()