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