Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 1 | """ |
| 2 | Read and write ZIP files. |
| 3 | """ |
Martin v. Löwis | 0075690 | 2006-02-05 17:09:41 +0000 | [diff] [blame] | 4 | import struct, os, time, sys |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 5 | import binascii, cStringIO |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 6 | |
| 7 | try: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 8 | import zlib # We may need its compression method |
Guido van Rossum | 9c673f3 | 2001-04-10 15:37:12 +0000 | [diff] [blame] | 9 | except ImportError: |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 10 | zlib = None |
| 11 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 12 | __all__ = ["BadZipfile", "error", "ZIP_STORED", "ZIP_DEFLATED", "is_zipfile", |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 13 | "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile" ] |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 14 | |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 15 | class BadZipfile(Exception): |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 16 | pass |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 17 | |
| 18 | |
| 19 | class LargeZipFile(Exception): |
| 20 | """ |
| 21 | Raised when writing a zipfile, the zipfile requires ZIP64 extensions |
| 22 | and those extensions are disabled. |
| 23 | """ |
| 24 | |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 25 | error = BadZipfile # The exception raised by this module |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 26 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 27 | ZIP64_LIMIT= (1 << 31) - 1 |
| 28 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 29 | # constants for Zip file compression methods |
| 30 | ZIP_STORED = 0 |
| 31 | ZIP_DEFLATED = 8 |
| 32 | # Other ZIP compression methods not supported |
| 33 | |
| 34 | # Here are some struct module formats for reading headers |
| 35 | structEndArchive = "<4s4H2lH" # 9 items, end of archive, 22 bytes |
| 36 | stringEndArchive = "PK\005\006" # magic number for end of archive record |
Brett Cannon | ff450f7 | 2004-07-10 19:09:20 +0000 | [diff] [blame] | 37 | structCentralDir = "<4s4B4HlLL5HLl"# 19 items, central directory, 46 bytes |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 38 | stringCentralDir = "PK\001\002" # magic number for central directory |
Brett Cannon | ff450f7 | 2004-07-10 19:09:20 +0000 | [diff] [blame] | 39 | structFileHeader = "<4s2B4HlLL2H" # 12 items, file header record, 30 bytes |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 40 | stringFileHeader = "PK\003\004" # magic number for file header |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 41 | structEndArchive64Locator = "<4slql" # 4 items, locate Zip64 header, 20 bytes |
| 42 | stringEndArchive64Locator = "PK\x06\x07" # magic token for locator header |
| 43 | structEndArchive64 = "<4sqhhllqqqq" # 10 items, end of archive (Zip64), 56 bytes |
| 44 | stringEndArchive64 = "PK\x06\x06" # magic token for Zip64 header |
| 45 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 46 | |
Fred Drake | 3e038e5 | 2001-02-28 17:56:26 +0000 | [diff] [blame] | 47 | # indexes of entries in the central directory structure |
| 48 | _CD_SIGNATURE = 0 |
| 49 | _CD_CREATE_VERSION = 1 |
| 50 | _CD_CREATE_SYSTEM = 2 |
| 51 | _CD_EXTRACT_VERSION = 3 |
| 52 | _CD_EXTRACT_SYSTEM = 4 # is this meaningful? |
| 53 | _CD_FLAG_BITS = 5 |
| 54 | _CD_COMPRESS_TYPE = 6 |
| 55 | _CD_TIME = 7 |
| 56 | _CD_DATE = 8 |
| 57 | _CD_CRC = 9 |
| 58 | _CD_COMPRESSED_SIZE = 10 |
| 59 | _CD_UNCOMPRESSED_SIZE = 11 |
| 60 | _CD_FILENAME_LENGTH = 12 |
| 61 | _CD_EXTRA_FIELD_LENGTH = 13 |
| 62 | _CD_COMMENT_LENGTH = 14 |
| 63 | _CD_DISK_NUMBER_START = 15 |
| 64 | _CD_INTERNAL_FILE_ATTRIBUTES = 16 |
| 65 | _CD_EXTERNAL_FILE_ATTRIBUTES = 17 |
| 66 | _CD_LOCAL_HEADER_OFFSET = 18 |
| 67 | |
| 68 | # indexes of entries in the local file header structure |
| 69 | _FH_SIGNATURE = 0 |
| 70 | _FH_EXTRACT_VERSION = 1 |
| 71 | _FH_EXTRACT_SYSTEM = 2 # is this meaningful? |
| 72 | _FH_GENERAL_PURPOSE_FLAG_BITS = 3 |
| 73 | _FH_COMPRESSION_METHOD = 4 |
| 74 | _FH_LAST_MOD_TIME = 5 |
| 75 | _FH_LAST_MOD_DATE = 6 |
| 76 | _FH_CRC = 7 |
| 77 | _FH_COMPRESSED_SIZE = 8 |
| 78 | _FH_UNCOMPRESSED_SIZE = 9 |
| 79 | _FH_FILENAME_LENGTH = 10 |
| 80 | _FH_EXTRA_FIELD_LENGTH = 11 |
| 81 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 82 | def is_zipfile(filename): |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 83 | """Quickly see if file is a ZIP file by checking the magic number.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 84 | try: |
| 85 | fpin = open(filename, "rb") |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 86 | endrec = _EndRecData(fpin) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 87 | fpin.close() |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 88 | if endrec: |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 89 | return True # file has correct magic number |
Fred Drake | 7e47380 | 2001-05-11 19:52:57 +0000 | [diff] [blame] | 90 | except IOError: |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 91 | pass |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 92 | return False |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 93 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 94 | def _EndRecData64(fpin, offset, endrec): |
| 95 | """ |
| 96 | Read the ZIP64 end-of-archive records and use that to update endrec |
| 97 | """ |
| 98 | locatorSize = struct.calcsize(structEndArchive64Locator) |
| 99 | fpin.seek(offset - locatorSize, 2) |
| 100 | data = fpin.read(locatorSize) |
| 101 | sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data) |
| 102 | if sig != stringEndArchive64Locator: |
| 103 | return endrec |
| 104 | |
| 105 | if diskno != 0 or disks != 1: |
| 106 | raise BadZipfile("zipfiles that span multiple disks are not supported") |
| 107 | |
| 108 | # Assume no 'zip64 extensible data' |
| 109 | endArchiveSize = struct.calcsize(structEndArchive64) |
| 110 | fpin.seek(offset - locatorSize - endArchiveSize, 2) |
| 111 | data = fpin.read(endArchiveSize) |
| 112 | sig, sz, create_version, read_version, disk_num, disk_dir, \ |
| 113 | dircount, dircount2, dirsize, diroffset = \ |
| 114 | struct.unpack(structEndArchive64, data) |
| 115 | if sig != stringEndArchive64: |
| 116 | return endrec |
| 117 | |
| 118 | # Update the original endrec using data from the ZIP64 record |
| 119 | endrec[1] = disk_num |
| 120 | endrec[2] = disk_dir |
| 121 | endrec[3] = dircount |
| 122 | endrec[4] = dircount2 |
| 123 | endrec[5] = dirsize |
| 124 | endrec[6] = diroffset |
| 125 | return endrec |
| 126 | |
| 127 | |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 128 | def _EndRecData(fpin): |
| 129 | """Return data from the "End of Central Directory" record, or None. |
| 130 | |
| 131 | The data is a list of the nine items in the ZIP "End of central dir" |
| 132 | record followed by a tenth item, the file seek offset of this record.""" |
| 133 | fpin.seek(-22, 2) # Assume no archive comment. |
| 134 | filesize = fpin.tell() + 22 # Get file size |
| 135 | data = fpin.read() |
| 136 | if data[0:4] == stringEndArchive and data[-2:] == "\000\000": |
| 137 | endrec = struct.unpack(structEndArchive, data) |
| 138 | endrec = list(endrec) |
| 139 | endrec.append("") # Append the archive comment |
| 140 | endrec.append(filesize - 22) # Append the record start offset |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 141 | if endrec[-4] == -1 or endrec[-4] == 0xffffffff: |
| 142 | return _EndRecData64(fpin, -22, endrec) |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 143 | return endrec |
| 144 | # Search the last END_BLOCK bytes of the file for the record signature. |
| 145 | # The comment is appended to the ZIP file and has a 16 bit length. |
| 146 | # So the comment may be up to 64K long. We limit the search for the |
| 147 | # signature to a few Kbytes at the end of the file for efficiency. |
| 148 | # also, the signature must not appear in the comment. |
| 149 | END_BLOCK = min(filesize, 1024 * 4) |
| 150 | fpin.seek(filesize - END_BLOCK, 0) |
| 151 | data = fpin.read() |
| 152 | start = data.rfind(stringEndArchive) |
| 153 | if start >= 0: # Correct signature string was found |
| 154 | endrec = struct.unpack(structEndArchive, data[start:start+22]) |
| 155 | endrec = list(endrec) |
| 156 | comment = data[start+22:] |
| 157 | if endrec[7] == len(comment): # Comment length checks out |
| 158 | # Append the archive comment and start offset |
| 159 | endrec.append(comment) |
| 160 | endrec.append(filesize - END_BLOCK + start) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 161 | if endrec[-4] == -1 or endrec[-4] == 0xffffffff: |
| 162 | return _EndRecData64(fpin, - END_BLOCK + start, endrec) |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 163 | return endrec |
| 164 | return # Error, return None |
| 165 | |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 166 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 167 | class ZipInfo (object): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 168 | """Class with attributes describing each file in the ZIP archive.""" |
| 169 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 170 | __slots__ = ( |
| 171 | 'orig_filename', |
| 172 | 'filename', |
| 173 | 'date_time', |
| 174 | 'compress_type', |
| 175 | 'comment', |
| 176 | 'extra', |
| 177 | 'create_system', |
| 178 | 'create_version', |
| 179 | 'extract_version', |
| 180 | 'reserved', |
| 181 | 'flag_bits', |
| 182 | 'volume', |
| 183 | 'internal_attr', |
| 184 | 'external_attr', |
| 185 | 'header_offset', |
| 186 | 'CRC', |
| 187 | 'compress_size', |
| 188 | 'file_size', |
| 189 | ) |
| 190 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 191 | 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] | 192 | self.orig_filename = filename # Original file name in archive |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 193 | |
| 194 | # Terminate the file name at the first null byte. Null bytes in file |
| 195 | # names are used as tricks by viruses in archives. |
Greg Ward | 8e36d28 | 2003-06-18 00:53:06 +0000 | [diff] [blame] | 196 | null_byte = filename.find(chr(0)) |
| 197 | if null_byte >= 0: |
| 198 | filename = filename[0:null_byte] |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 199 | # This is used to ensure paths in generated ZIP files always use |
| 200 | # forward slashes as the directory separator, as required by the |
| 201 | # ZIP format specification. |
| 202 | if os.sep != "/" and os.sep in filename: |
Greg Ward | 8e36d28 | 2003-06-18 00:53:06 +0000 | [diff] [blame] | 203 | filename = filename.replace(os.sep, "/") |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 204 | |
Greg Ward | 8e36d28 | 2003-06-18 00:53:06 +0000 | [diff] [blame] | 205 | self.filename = filename # Normalized file name |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 206 | self.date_time = date_time # year, month, day, hour, min, sec |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 207 | # Standard values: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 208 | self.compress_type = ZIP_STORED # Type of compression for the file |
| 209 | self.comment = "" # Comment for each file |
| 210 | self.extra = "" # ZIP extra data |
Martin v. Löwis | 0075690 | 2006-02-05 17:09:41 +0000 | [diff] [blame] | 211 | if sys.platform == 'win32': |
| 212 | self.create_system = 0 # System which created ZIP archive |
| 213 | else: |
| 214 | # Assume everything else is unix-y |
| 215 | self.create_system = 3 # System which created ZIP archive |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 216 | self.create_version = 20 # Version which created ZIP archive |
| 217 | self.extract_version = 20 # Version needed to extract archive |
| 218 | self.reserved = 0 # Must be zero |
| 219 | self.flag_bits = 0 # ZIP flag bits |
| 220 | self.volume = 0 # Volume number of file header |
| 221 | self.internal_attr = 0 # Internal attributes |
| 222 | self.external_attr = 0 # External file attributes |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 223 | # Other attributes are set by class ZipFile: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 224 | # header_offset Byte offset to the file header |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 225 | # CRC CRC-32 of the uncompressed file |
| 226 | # compress_size Size of the compressed file |
| 227 | # file_size Size of the uncompressed file |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 228 | |
| 229 | def FileHeader(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 230 | """Return the per-file header as a string.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 231 | dt = self.date_time |
| 232 | dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] |
Tim Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 233 | dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 234 | if self.flag_bits & 0x08: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 235 | # Set these to zero because we write them after the file data |
| 236 | CRC = compress_size = file_size = 0 |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 237 | else: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 238 | CRC = self.CRC |
| 239 | compress_size = self.compress_size |
| 240 | file_size = self.file_size |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 241 | |
| 242 | extra = self.extra |
| 243 | |
| 244 | if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT: |
| 245 | # File is larger than what fits into a 4 byte integer, |
| 246 | # fall back to the ZIP64 extension |
| 247 | fmt = '<hhqq' |
| 248 | extra = extra + struct.pack(fmt, |
| 249 | 1, struct.calcsize(fmt)-4, file_size, compress_size) |
| 250 | file_size = 0xffffffff # -1 |
| 251 | compress_size = 0xffffffff # -1 |
| 252 | self.extract_version = max(45, self.extract_version) |
| 253 | self.create_version = max(45, self.extract_version) |
| 254 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 255 | header = struct.pack(structFileHeader, stringFileHeader, |
| 256 | self.extract_version, self.reserved, self.flag_bits, |
| 257 | self.compress_type, dostime, dosdate, CRC, |
| 258 | compress_size, file_size, |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 259 | len(self.filename), len(extra)) |
| 260 | return header + self.filename + extra |
| 261 | |
| 262 | def _decodeExtra(self): |
| 263 | # Try to decode the extra field. |
| 264 | extra = self.extra |
| 265 | unpack = struct.unpack |
| 266 | while extra: |
| 267 | tp, ln = unpack('<hh', extra[:4]) |
| 268 | if tp == 1: |
| 269 | if ln >= 24: |
| 270 | counts = unpack('<qqq', extra[4:28]) |
| 271 | elif ln == 16: |
| 272 | counts = unpack('<qq', extra[4:20]) |
| 273 | elif ln == 8: |
| 274 | counts = unpack('<q', extra[4:12]) |
| 275 | elif ln == 0: |
| 276 | counts = () |
| 277 | else: |
| 278 | raise RuntimeError, "Corrupt extra field %s"%(ln,) |
| 279 | |
| 280 | idx = 0 |
| 281 | |
| 282 | # ZIP64 extension (large files and/or large archives) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 283 | if self.file_size == -1 or self.file_size == 0xFFFFFFFF: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 284 | self.file_size = counts[idx] |
| 285 | idx += 1 |
| 286 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 287 | if self.compress_size == -1 or self.compress_size == 0xFFFFFFFF: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 288 | self.compress_size = counts[idx] |
| 289 | idx += 1 |
| 290 | |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 291 | if self.header_offset == -1 or self.header_offset == 0xffffffff: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 292 | old = self.header_offset |
| 293 | self.header_offset = counts[idx] |
| 294 | idx+=1 |
| 295 | |
| 296 | extra = extra[ln+4:] |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 297 | |
| 298 | |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 299 | class _ZipDecrypter: |
| 300 | """Class to handle decryption of files stored within a ZIP archive. |
| 301 | |
| 302 | ZIP supports a password-based form of encryption. Even though known |
| 303 | plaintext attacks have been found against it, it is still useful |
| 304 | for low-level securicy. |
| 305 | |
| 306 | Usage: |
| 307 | zd = _ZipDecrypter(mypwd) |
| 308 | plain_char = zd(cypher_char) |
| 309 | plain_text = map(zd, cypher_text) |
| 310 | """ |
| 311 | |
| 312 | def _GenerateCRCTable(): |
| 313 | """Generate a CRC-32 table. |
| 314 | |
| 315 | ZIP encryption uses the CRC32 one-byte primitive for scrambling some |
| 316 | internal keys. We noticed that a direct implementation is faster than |
| 317 | relying on binascii.crc32(). |
| 318 | """ |
| 319 | poly = 0xedb88320 |
| 320 | table = [0] * 256 |
| 321 | for i in range(256): |
| 322 | crc = i |
| 323 | for j in range(8): |
| 324 | if crc & 1: |
| 325 | crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly |
| 326 | else: |
| 327 | crc = ((crc >> 1) & 0x7FFFFFFF) |
| 328 | table[i] = crc |
| 329 | return table |
| 330 | crctable = _GenerateCRCTable() |
| 331 | |
| 332 | def _crc32(self, ch, crc): |
| 333 | """Compute the CRC32 primitive on one byte.""" |
| 334 | return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] |
| 335 | |
| 336 | def __init__(self, pwd): |
| 337 | self.key0 = 305419896 |
| 338 | self.key1 = 591751049 |
| 339 | self.key2 = 878082192 |
| 340 | for p in pwd: |
| 341 | self._UpdateKeys(p) |
| 342 | |
| 343 | def _UpdateKeys(self, c): |
| 344 | self.key0 = self._crc32(c, self.key0) |
| 345 | self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295 |
| 346 | self.key1 = (self.key1 * 134775813 + 1) & 4294967295 |
| 347 | self.key2 = self._crc32(chr((self.key1 >> 24) & 255), self.key2) |
| 348 | |
| 349 | def __call__(self, c): |
| 350 | """Decrypt a single character.""" |
| 351 | c = ord(c) |
| 352 | k = self.key2 | 2 |
| 353 | c = c ^ (((k * (k^1)) >> 8) & 255) |
| 354 | c = chr(c) |
| 355 | self._UpdateKeys(c) |
| 356 | return c |
| 357 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 358 | class ZipFile: |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 359 | """ Class with methods to open, read, write, close, list zip files. |
| 360 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 361 | z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True) |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 362 | |
Fred Drake | 3d9091e | 2001-03-26 15:49:24 +0000 | [diff] [blame] | 363 | file: Either the path to the file, or a file-like object. |
| 364 | If it is a path, the file will be opened and closed by ZipFile. |
| 365 | mode: The mode can be either read "r", write "w" or append "a". |
| 366 | compression: ZIP_STORED (no compression) or ZIP_DEFLATED (requires zlib). |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 367 | allowZip64: if True ZipFile will create files with ZIP64 extensions when |
| 368 | needed, otherwise it will raise an exception when this would |
| 369 | be necessary. |
| 370 | |
Fred Drake | 3d9091e | 2001-03-26 15:49:24 +0000 | [diff] [blame] | 371 | """ |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 372 | |
Fred Drake | 90eac28 | 2001-02-28 05:29:34 +0000 | [diff] [blame] | 373 | fp = None # Set here since __del__ checks it |
| 374 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 375 | def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=False): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 376 | """Open the ZIP file with mode read "r", write "w" or append "a".""" |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 377 | self._allowZip64 = allowZip64 |
| 378 | self._didModify = False |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 379 | if compression == ZIP_STORED: |
| 380 | pass |
| 381 | elif compression == ZIP_DEFLATED: |
| 382 | if not zlib: |
| 383 | raise RuntimeError,\ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 384 | "Compression requires the (missing) zlib module" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 385 | else: |
| 386 | raise RuntimeError, "That compression method is not supported" |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 387 | self.debug = 0 # Level of printing: 0 through 3 |
| 388 | self.NameToInfo = {} # Find file info given name |
| 389 | self.filelist = [] # List of ZipInfo instances for archive |
| 390 | self.compression = compression # Method of compression |
Raymond Hettinger | 2ca7c19 | 2005-02-16 09:27:49 +0000 | [diff] [blame] | 391 | self.mode = key = mode.replace('b', '')[0] |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 392 | self.pwd = None |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 393 | |
Fred Drake | 3d9091e | 2001-03-26 15:49:24 +0000 | [diff] [blame] | 394 | # Check if we were passed a file-like object |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 395 | if isinstance(file, basestring): |
Fred Drake | 3d9091e | 2001-03-26 15:49:24 +0000 | [diff] [blame] | 396 | self._filePassed = 0 |
| 397 | self.filename = file |
| 398 | modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 399 | try: |
| 400 | self.fp = open(file, modeDict[mode]) |
| 401 | except IOError: |
| 402 | if mode == 'a': |
| 403 | mode = key = 'w' |
| 404 | self.fp = open(file, modeDict[mode]) |
| 405 | else: |
| 406 | raise |
Fred Drake | 3d9091e | 2001-03-26 15:49:24 +0000 | [diff] [blame] | 407 | else: |
| 408 | self._filePassed = 1 |
| 409 | self.fp = file |
| 410 | self.filename = getattr(file, 'name', None) |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 411 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 412 | if key == 'r': |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 413 | self._GetContents() |
| 414 | elif key == 'w': |
Fred Drake | 3d9091e | 2001-03-26 15:49:24 +0000 | [diff] [blame] | 415 | pass |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 416 | elif key == 'a': |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 417 | try: # See if file is a zip file |
| 418 | self._RealGetContents() |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 419 | # seek to start of directory and overwrite |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 420 | self.fp.seek(self.start_dir, 0) |
| 421 | except BadZipfile: # file is not a zip file, just append |
| 422 | self.fp.seek(0, 2) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 423 | else: |
Tim Peters | 7d3bad6 | 2001-04-04 18:56:49 +0000 | [diff] [blame] | 424 | if not self._filePassed: |
| 425 | self.fp.close() |
| 426 | self.fp = None |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 427 | raise RuntimeError, 'Mode must be "r", "w" or "a"' |
| 428 | |
| 429 | def _GetContents(self): |
Tim Peters | 7d3bad6 | 2001-04-04 18:56:49 +0000 | [diff] [blame] | 430 | """Read the directory, making sure we close the file if the format |
| 431 | is bad.""" |
| 432 | try: |
| 433 | self._RealGetContents() |
| 434 | except BadZipfile: |
| 435 | if not self._filePassed: |
| 436 | self.fp.close() |
| 437 | self.fp = None |
| 438 | raise |
| 439 | |
| 440 | def _RealGetContents(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 441 | """Read in the table of contents for the ZIP file.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 442 | fp = self.fp |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 443 | endrec = _EndRecData(fp) |
| 444 | if not endrec: |
| 445 | raise BadZipfile, "File is not a zip file" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 446 | if self.debug > 1: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 447 | print(endrec) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 448 | size_cd = endrec[5] # bytes in central directory |
| 449 | offset_cd = endrec[6] # offset of central directory |
Martin v. Löwis | 6f6873b | 2002-10-13 13:54:50 +0000 | [diff] [blame] | 450 | self.comment = endrec[8] # archive comment |
| 451 | # endrec[9] is the offset of the "End of Central Dir" record |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 452 | if endrec[9] > ZIP64_LIMIT: |
| 453 | x = endrec[9] - size_cd - 56 - 20 |
| 454 | else: |
| 455 | x = endrec[9] - size_cd |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 456 | # "concat" is zero, unless zip was concatenated to another file |
| 457 | concat = x - offset_cd |
| 458 | if self.debug > 2: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 459 | print("given, inferred, offset", offset_cd, x, concat) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 460 | # self.start_dir: Position of start of central directory |
| 461 | self.start_dir = offset_cd + concat |
| 462 | fp.seek(self.start_dir, 0) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 463 | data = fp.read(size_cd) |
| 464 | fp = cStringIO.StringIO(data) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 465 | total = 0 |
| 466 | while total < size_cd: |
| 467 | centdir = fp.read(46) |
| 468 | total = total + 46 |
| 469 | if centdir[0:4] != stringCentralDir: |
| 470 | raise BadZipfile, "Bad magic number for central directory" |
| 471 | centdir = struct.unpack(structCentralDir, centdir) |
| 472 | if self.debug > 2: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 473 | print(centdir) |
Fred Drake | 3e038e5 | 2001-02-28 17:56:26 +0000 | [diff] [blame] | 474 | filename = fp.read(centdir[_CD_FILENAME_LENGTH]) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 475 | # Create ZipInfo instance to store file information |
| 476 | x = ZipInfo(filename) |
Fred Drake | 3e038e5 | 2001-02-28 17:56:26 +0000 | [diff] [blame] | 477 | x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH]) |
| 478 | x.comment = fp.read(centdir[_CD_COMMENT_LENGTH]) |
| 479 | total = (total + centdir[_CD_FILENAME_LENGTH] |
| 480 | + centdir[_CD_EXTRA_FIELD_LENGTH] |
| 481 | + centdir[_CD_COMMENT_LENGTH]) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 482 | x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET] |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 483 | (x.create_version, x.create_system, x.extract_version, x.reserved, |
| 484 | x.flag_bits, x.compress_type, t, d, |
| 485 | x.CRC, x.compress_size, x.file_size) = centdir[1:12] |
| 486 | x.volume, x.internal_attr, x.external_attr = centdir[15:18] |
| 487 | # Convert date/time code to (year, month, day, hour, min, sec) |
| 488 | x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, |
Fred Drake | 414ca66 | 2000-06-13 18:49:53 +0000 | [diff] [blame] | 489 | t>>11, (t>>5)&0x3F, (t&0x1F) * 2 ) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 490 | |
| 491 | x._decodeExtra() |
| 492 | x.header_offset = x.header_offset + concat |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 493 | self.filelist.append(x) |
| 494 | self.NameToInfo[x.filename] = x |
| 495 | if self.debug > 2: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 496 | print("total", total) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 497 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 498 | |
| 499 | def namelist(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 500 | """Return a list of file names in the archive.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 501 | l = [] |
| 502 | for data in self.filelist: |
| 503 | l.append(data.filename) |
| 504 | return l |
| 505 | |
| 506 | def infolist(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 507 | """Return a list of class ZipInfo instances for files in the |
| 508 | archive.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 509 | return self.filelist |
| 510 | |
| 511 | def printdir(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 512 | """Print a table of contents for the zip file.""" |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 513 | print("%-46s %19s %12s" % ("File Name", "Modified ", "Size")) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 514 | for zinfo in self.filelist: |
| 515 | date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 516 | print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 517 | |
| 518 | def testzip(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 519 | """Read all the files and check the CRC.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 520 | for zinfo in self.filelist: |
| 521 | try: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 522 | self.read(zinfo.filename) # Check CRC-32 |
Raymond Hettinger | c0fac96 | 2003-06-27 22:25:03 +0000 | [diff] [blame] | 523 | except BadZipfile: |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 524 | return zinfo.filename |
| 525 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 526 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 527 | def getinfo(self, name): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 528 | """Return the instance of ZipInfo given 'name'.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 529 | return self.NameToInfo[name] |
| 530 | |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 531 | def setpassword(self, pwd): |
| 532 | """Set default password for encrypted files.""" |
| 533 | self.pwd = pwd |
| 534 | |
| 535 | def read(self, name, pwd=None): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 536 | """Return file bytes (as a string) for name.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 537 | if self.mode not in ("r", "a"): |
| 538 | raise RuntimeError, 'read() requires mode "r" or "a"' |
| 539 | if not self.fp: |
| 540 | raise RuntimeError, \ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 541 | "Attempt to read ZIP archive that was already closed" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 542 | zinfo = self.getinfo(name) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 543 | is_encrypted = zinfo.flag_bits & 0x1 |
| 544 | if is_encrypted: |
| 545 | if not pwd: |
| 546 | pwd = self.pwd |
| 547 | if not pwd: |
| 548 | raise RuntimeError, "File %s is encrypted, " \ |
| 549 | "password required for extraction" % name |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 550 | filepos = self.fp.tell() |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 551 | |
| 552 | self.fp.seek(zinfo.header_offset, 0) |
| 553 | |
| 554 | # Skip the file header: |
| 555 | fheader = self.fp.read(30) |
| 556 | if fheader[0:4] != stringFileHeader: |
| 557 | raise BadZipfile, "Bad magic number for file header" |
| 558 | |
| 559 | fheader = struct.unpack(structFileHeader, fheader) |
| 560 | fname = self.fp.read(fheader[_FH_FILENAME_LENGTH]) |
| 561 | if fheader[_FH_EXTRA_FIELD_LENGTH]: |
| 562 | self.fp.read(fheader[_FH_EXTRA_FIELD_LENGTH]) |
| 563 | |
| 564 | if fname != zinfo.orig_filename: |
| 565 | raise BadZipfile, \ |
| 566 | 'File name in directory "%s" and header "%s" differ.' % ( |
| 567 | zinfo.orig_filename, fname) |
| 568 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 569 | bytes = self.fp.read(zinfo.compress_size) |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 570 | # Go with decryption |
| 571 | if is_encrypted: |
| 572 | zd = _ZipDecrypter(pwd) |
| 573 | # The first 12 bytes in the cypher stream is an encryption header |
| 574 | # used to strengthen the algorithm. The first 11 bytes are |
| 575 | # completely random, while the 12th contains the MSB of the CRC, |
| 576 | # and is used to check the correctness of the password. |
| 577 | h = map(zd, bytes[0:12]) |
| 578 | if ord(h[11]) != ((zinfo.CRC>>24)&255): |
| 579 | raise RuntimeError, "Bad password for file %s" % name |
| 580 | bytes = "".join(map(zd, bytes[12:])) |
| 581 | # Go with decompression |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 582 | self.fp.seek(filepos, 0) |
| 583 | if zinfo.compress_type == ZIP_STORED: |
| 584 | pass |
| 585 | elif zinfo.compress_type == ZIP_DEFLATED: |
| 586 | if not zlib: |
| 587 | raise RuntimeError, \ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 588 | "De-compression requires the (missing) zlib module" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 589 | # zlib compress/decompress code by Jeremy Hylton of CNRI |
| 590 | dc = zlib.decompressobj(-15) |
| 591 | bytes = dc.decompress(bytes) |
| 592 | # need to feed in unused pad byte so that zlib won't choke |
| 593 | ex = dc.decompress('Z') + dc.flush() |
| 594 | if ex: |
| 595 | bytes = bytes + ex |
| 596 | else: |
| 597 | raise BadZipfile, \ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 598 | "Unsupported compression method %d for file %s" % \ |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 599 | (zinfo.compress_type, name) |
| 600 | crc = binascii.crc32(bytes) |
| 601 | if crc != zinfo.CRC: |
| 602 | raise BadZipfile, "Bad CRC-32 for file %s" % name |
| 603 | return bytes |
| 604 | |
| 605 | def _writecheck(self, zinfo): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 606 | """Check for errors before writing a file to the archive.""" |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 607 | if zinfo.filename in self.NameToInfo: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 608 | if self.debug: # Warning for duplicate names |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 609 | print("Duplicate name:", zinfo.filename) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 610 | if self.mode not in ("w", "a"): |
| 611 | raise RuntimeError, 'write() requires mode "w" or "a"' |
| 612 | if not self.fp: |
| 613 | raise RuntimeError, \ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 614 | "Attempt to write ZIP archive that was already closed" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 615 | if zinfo.compress_type == ZIP_DEFLATED and not zlib: |
| 616 | raise RuntimeError, \ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 617 | "Compression requires the (missing) zlib module" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 618 | if zinfo.compress_type not in (ZIP_STORED, ZIP_DEFLATED): |
| 619 | raise RuntimeError, \ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 620 | "That compression method is not supported" |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 621 | if zinfo.file_size > ZIP64_LIMIT: |
| 622 | if not self._allowZip64: |
| 623 | raise LargeZipFile("Filesize would require ZIP64 extensions") |
| 624 | if zinfo.header_offset > ZIP64_LIMIT: |
| 625 | if not self._allowZip64: |
| 626 | raise LargeZipFile("Zipfile size would require ZIP64 extensions") |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 627 | |
| 628 | def write(self, filename, arcname=None, compress_type=None): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 629 | """Put the bytes from filename into the archive under the name |
| 630 | arcname.""" |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 631 | st = os.stat(filename) |
Raymond Hettinger | 32200ae | 2002-06-01 19:51:15 +0000 | [diff] [blame] | 632 | mtime = time.localtime(st.st_mtime) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 633 | date_time = mtime[0:6] |
| 634 | # Create ZipInfo instance to store file information |
| 635 | if arcname is None: |
Georg Brandl | 8f7c54e | 2006-02-20 08:40:38 +0000 | [diff] [blame] | 636 | arcname = filename |
| 637 | arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) |
| 638 | while arcname[0] in (os.sep, os.altsep): |
| 639 | arcname = arcname[1:] |
| 640 | zinfo = ZipInfo(arcname, date_time) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 641 | zinfo.external_attr = (st[0] & 0xFFFF) << 16 # Unix attributes |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 642 | if compress_type is None: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 643 | zinfo.compress_type = self.compression |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 644 | else: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 645 | zinfo.compress_type = compress_type |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 646 | |
| 647 | zinfo.file_size = st.st_size |
Finn Bock | 03a3bb8 | 2001-09-05 18:40:33 +0000 | [diff] [blame] | 648 | zinfo.flag_bits = 0x00 |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 649 | zinfo.header_offset = self.fp.tell() # Start of header bytes |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 650 | |
| 651 | self._writecheck(zinfo) |
| 652 | self._didModify = True |
| 653 | fp = open(filename, "rb") |
Finn Bock | 03a3bb8 | 2001-09-05 18:40:33 +0000 | [diff] [blame] | 654 | # Must overwrite CRC and sizes with correct data later |
| 655 | zinfo.CRC = CRC = 0 |
| 656 | zinfo.compress_size = compress_size = 0 |
| 657 | zinfo.file_size = file_size = 0 |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 658 | self.fp.write(zinfo.FileHeader()) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 659 | if zinfo.compress_type == ZIP_DEFLATED: |
| 660 | cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, |
| 661 | zlib.DEFLATED, -15) |
| 662 | else: |
| 663 | cmpr = None |
| 664 | while 1: |
| 665 | buf = fp.read(1024 * 8) |
| 666 | if not buf: |
| 667 | break |
| 668 | file_size = file_size + len(buf) |
| 669 | CRC = binascii.crc32(buf, CRC) |
| 670 | if cmpr: |
| 671 | buf = cmpr.compress(buf) |
| 672 | compress_size = compress_size + len(buf) |
| 673 | self.fp.write(buf) |
| 674 | fp.close() |
| 675 | if cmpr: |
| 676 | buf = cmpr.flush() |
| 677 | compress_size = compress_size + len(buf) |
| 678 | self.fp.write(buf) |
| 679 | zinfo.compress_size = compress_size |
| 680 | else: |
| 681 | zinfo.compress_size = file_size |
| 682 | zinfo.CRC = CRC |
| 683 | zinfo.file_size = file_size |
Finn Bock | 03a3bb8 | 2001-09-05 18:40:33 +0000 | [diff] [blame] | 684 | # Seek backwards and write CRC and file sizes |
Tim Peters | b64bec3 | 2001-09-18 02:26:39 +0000 | [diff] [blame] | 685 | position = self.fp.tell() # Preserve current position in file |
Finn Bock | 03a3bb8 | 2001-09-05 18:40:33 +0000 | [diff] [blame] | 686 | self.fp.seek(zinfo.header_offset + 14, 0) |
Brett Cannon | ff450f7 | 2004-07-10 19:09:20 +0000 | [diff] [blame] | 687 | self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size, |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 688 | zinfo.file_size)) |
Finn Bock | 03a3bb8 | 2001-09-05 18:40:33 +0000 | [diff] [blame] | 689 | self.fp.seek(position, 0) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 690 | self.filelist.append(zinfo) |
| 691 | self.NameToInfo[zinfo.filename] = zinfo |
| 692 | |
Just van Rossum | b083cb3 | 2002-12-12 12:23:32 +0000 | [diff] [blame] | 693 | def writestr(self, zinfo_or_arcname, bytes): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 694 | """Write a file into the archive. The contents is the string |
Just van Rossum | b083cb3 | 2002-12-12 12:23:32 +0000 | [diff] [blame] | 695 | 'bytes'. 'zinfo_or_arcname' is either a ZipInfo instance or |
| 696 | the name of the file in the archive.""" |
| 697 | if not isinstance(zinfo_or_arcname, ZipInfo): |
| 698 | zinfo = ZipInfo(filename=zinfo_or_arcname, |
| 699 | date_time=time.localtime(time.time())) |
| 700 | zinfo.compress_type = self.compression |
| 701 | else: |
| 702 | zinfo = zinfo_or_arcname |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 703 | zinfo.file_size = len(bytes) # Uncompressed size |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 704 | zinfo.header_offset = self.fp.tell() # Start of header bytes |
| 705 | self._writecheck(zinfo) |
| 706 | self._didModify = True |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 707 | zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 708 | if zinfo.compress_type == ZIP_DEFLATED: |
| 709 | co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, |
| 710 | zlib.DEFLATED, -15) |
| 711 | bytes = co.compress(bytes) + co.flush() |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 712 | zinfo.compress_size = len(bytes) # Compressed size |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 713 | else: |
| 714 | zinfo.compress_size = zinfo.file_size |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 715 | zinfo.header_offset = self.fp.tell() # Start of header bytes |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 716 | self.fp.write(zinfo.FileHeader()) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 717 | self.fp.write(bytes) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 718 | self.fp.flush() |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 719 | if zinfo.flag_bits & 0x08: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 720 | # Write CRC and file sizes after the file data |
Brett Cannon | ff450f7 | 2004-07-10 19:09:20 +0000 | [diff] [blame] | 721 | self.fp.write(struct.pack("<lLL", zinfo.CRC, zinfo.compress_size, |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 722 | zinfo.file_size)) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 723 | self.filelist.append(zinfo) |
| 724 | self.NameToInfo[zinfo.filename] = zinfo |
| 725 | |
| 726 | def __del__(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 727 | """Call the "close()" method in case the user forgot.""" |
Tim Peters | d15f8bb | 2001-11-28 23:16:40 +0000 | [diff] [blame] | 728 | self.close() |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 729 | |
| 730 | def close(self): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 731 | """Close the file, and for mode "w" and "a" write the ending |
| 732 | records.""" |
Tim Peters | d15f8bb | 2001-11-28 23:16:40 +0000 | [diff] [blame] | 733 | if self.fp is None: |
| 734 | return |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 735 | |
| 736 | 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] | 737 | count = 0 |
| 738 | pos1 = self.fp.tell() |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 739 | for zinfo in self.filelist: # write central directory |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 740 | count = count + 1 |
| 741 | dt = zinfo.date_time |
| 742 | dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2] |
Tim Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 743 | dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 744 | extra = [] |
| 745 | if zinfo.file_size > ZIP64_LIMIT \ |
| 746 | or zinfo.compress_size > ZIP64_LIMIT: |
| 747 | extra.append(zinfo.file_size) |
| 748 | extra.append(zinfo.compress_size) |
| 749 | file_size = 0xffffffff #-1 |
| 750 | compress_size = 0xffffffff #-1 |
| 751 | else: |
| 752 | file_size = zinfo.file_size |
| 753 | compress_size = zinfo.compress_size |
| 754 | |
| 755 | if zinfo.header_offset > ZIP64_LIMIT: |
| 756 | extra.append(zinfo.header_offset) |
| 757 | header_offset = -1 # struct "l" format: 32 one bits |
| 758 | else: |
| 759 | header_offset = zinfo.header_offset |
| 760 | |
| 761 | extra_data = zinfo.extra |
| 762 | if extra: |
| 763 | # Append a ZIP64 field to the extra's |
| 764 | extra_data = struct.pack( |
| 765 | '<hh' + 'q'*len(extra), |
| 766 | 1, 8*len(extra), *extra) + extra_data |
| 767 | |
| 768 | extract_version = max(45, zinfo.extract_version) |
| 769 | create_version = max(45, zinfo.create_version) |
| 770 | else: |
| 771 | extract_version = zinfo.extract_version |
| 772 | create_version = zinfo.create_version |
| 773 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 774 | centdir = struct.pack(structCentralDir, |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 775 | stringCentralDir, create_version, |
| 776 | zinfo.create_system, extract_version, zinfo.reserved, |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 777 | zinfo.flag_bits, zinfo.compress_type, dostime, dosdate, |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 778 | zinfo.CRC, compress_size, file_size, |
| 779 | len(zinfo.filename), len(extra_data), len(zinfo.comment), |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 780 | 0, zinfo.internal_attr, zinfo.external_attr, |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 781 | header_offset) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 782 | self.fp.write(centdir) |
| 783 | self.fp.write(zinfo.filename) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 784 | self.fp.write(extra_data) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 785 | self.fp.write(zinfo.comment) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 786 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 787 | pos2 = self.fp.tell() |
| 788 | # Write end-of-zip-archive record |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 789 | if pos1 > ZIP64_LIMIT: |
| 790 | # Need to write the ZIP64 end-of-archive records |
| 791 | zip64endrec = struct.pack( |
| 792 | structEndArchive64, stringEndArchive64, |
| 793 | 44, 45, 45, 0, 0, count, count, pos2 - pos1, pos1) |
| 794 | self.fp.write(zip64endrec) |
| 795 | |
| 796 | zip64locrec = struct.pack( |
| 797 | structEndArchive64Locator, |
| 798 | stringEndArchive64Locator, 0, pos2, 1) |
| 799 | self.fp.write(zip64locrec) |
| 800 | |
| 801 | # XXX Why is `pos3` computed next? It's never referenced. |
| 802 | pos3 = self.fp.tell() |
| 803 | endrec = struct.pack(structEndArchive, stringEndArchive, |
| 804 | 0, 0, count, count, pos2 - pos1, -1, 0) |
| 805 | self.fp.write(endrec) |
| 806 | |
| 807 | else: |
| 808 | endrec = struct.pack(structEndArchive, stringEndArchive, |
| 809 | 0, 0, count, count, pos2 - pos1, pos1, 0) |
| 810 | self.fp.write(endrec) |
Guido van Rossum | f85af61 | 2001-04-14 16:45:14 +0000 | [diff] [blame] | 811 | self.fp.flush() |
Fred Drake | 3d9091e | 2001-03-26 15:49:24 +0000 | [diff] [blame] | 812 | if not self._filePassed: |
| 813 | self.fp.close() |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 814 | self.fp = None |
| 815 | |
| 816 | |
| 817 | class PyZipFile(ZipFile): |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 818 | """Class to create ZIP archives with Python library files and packages.""" |
| 819 | |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 820 | def writepy(self, pathname, basename = ""): |
| 821 | """Add all files from "pathname" to the ZIP archive. |
| 822 | |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 823 | If pathname is a package directory, search the directory and |
| 824 | all package subdirectories recursively for all *.py and enter |
| 825 | the modules into the archive. If pathname is a plain |
| 826 | directory, listdir *.py and enter all modules. Else, pathname |
| 827 | must be a Python *.py file and the module will be put into the |
| 828 | archive. Added modules are always module.pyo or module.pyc. |
| 829 | This method will compile the module.py into module.pyc if |
| 830 | necessary. |
| 831 | """ |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 832 | dir, name = os.path.split(pathname) |
| 833 | if os.path.isdir(pathname): |
| 834 | initname = os.path.join(pathname, "__init__.py") |
| 835 | if os.path.isfile(initname): |
| 836 | # This is a package directory, add it |
| 837 | if basename: |
| 838 | basename = "%s/%s" % (basename, name) |
| 839 | else: |
| 840 | basename = name |
| 841 | if self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 842 | print("Adding package in", pathname, "as", basename) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 843 | fname, arcname = self._get_codename(initname[0:-3], basename) |
| 844 | if self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 845 | print("Adding", arcname) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 846 | self.write(fname, arcname) |
| 847 | dirlist = os.listdir(pathname) |
| 848 | dirlist.remove("__init__.py") |
| 849 | # Add all *.py files and package subdirectories |
| 850 | for filename in dirlist: |
| 851 | path = os.path.join(pathname, filename) |
| 852 | root, ext = os.path.splitext(filename) |
| 853 | if os.path.isdir(path): |
| 854 | if os.path.isfile(os.path.join(path, "__init__.py")): |
| 855 | # This is a package directory, add it |
| 856 | self.writepy(path, basename) # Recursive call |
| 857 | elif ext == ".py": |
| 858 | fname, arcname = self._get_codename(path[0:-3], |
| 859 | basename) |
| 860 | if self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 861 | print("Adding", arcname) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 862 | self.write(fname, arcname) |
| 863 | else: |
| 864 | # This is NOT a package directory, add its files at top level |
| 865 | if self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 866 | print("Adding files from directory", pathname) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 867 | for filename in os.listdir(pathname): |
| 868 | path = os.path.join(pathname, filename) |
| 869 | root, ext = os.path.splitext(filename) |
| 870 | if ext == ".py": |
| 871 | fname, arcname = self._get_codename(path[0:-3], |
| 872 | basename) |
| 873 | if self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 874 | print("Adding", arcname) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 875 | self.write(fname, arcname) |
| 876 | else: |
| 877 | if pathname[-3:] != ".py": |
| 878 | raise RuntimeError, \ |
Fred Drake | 5db246d | 2000-09-29 20:44:48 +0000 | [diff] [blame] | 879 | 'Files added with writepy() must end with ".py"' |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 880 | fname, arcname = self._get_codename(pathname[0:-3], basename) |
| 881 | if self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 882 | print("Adding file", arcname) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 883 | self.write(fname, arcname) |
| 884 | |
| 885 | def _get_codename(self, pathname, basename): |
| 886 | """Return (filename, archivename) for the path. |
| 887 | |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 888 | Given a module name path, return the correct file path and |
| 889 | archive name, compiling if necessary. For example, given |
| 890 | /python/lib/string, return (/python/lib/string.pyc, string). |
| 891 | """ |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 892 | file_py = pathname + ".py" |
| 893 | file_pyc = pathname + ".pyc" |
| 894 | file_pyo = pathname + ".pyo" |
| 895 | if os.path.isfile(file_pyo) and \ |
Raymond Hettinger | 32200ae | 2002-06-01 19:51:15 +0000 | [diff] [blame] | 896 | os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime: |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 897 | fname = file_pyo # Use .pyo file |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 898 | elif not os.path.isfile(file_pyc) or \ |
Raymond Hettinger | 32200ae | 2002-06-01 19:51:15 +0000 | [diff] [blame] | 899 | os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime: |
Fred Drake | 484d735 | 2000-10-02 21:14:52 +0000 | [diff] [blame] | 900 | import py_compile |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 901 | if self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 902 | print("Compiling", file_py) |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 903 | try: |
| 904 | py_compile.compile(file_py, file_pyc, None, True) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 905 | except py_compile.PyCompileError as err: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 906 | print(err.msg) |
Guido van Rossum | 32abe6f | 2000-03-31 17:30:02 +0000 | [diff] [blame] | 907 | fname = file_pyc |
| 908 | else: |
| 909 | fname = file_pyc |
| 910 | archivename = os.path.split(fname)[1] |
| 911 | if basename: |
| 912 | archivename = "%s/%s" % (basename, archivename) |
| 913 | return (fname, archivename) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 914 | |
| 915 | |
| 916 | def main(args = None): |
| 917 | import textwrap |
| 918 | USAGE=textwrap.dedent("""\ |
| 919 | Usage: |
| 920 | zipfile.py -l zipfile.zip # Show listing of a zipfile |
| 921 | zipfile.py -t zipfile.zip # Test if a zipfile is valid |
| 922 | zipfile.py -e zipfile.zip target # Extract zipfile into target dir |
| 923 | zipfile.py -c zipfile.zip src ... # Create zipfile from sources |
| 924 | """) |
| 925 | if args is None: |
| 926 | args = sys.argv[1:] |
| 927 | |
| 928 | 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] | 929 | print(USAGE) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 930 | sys.exit(1) |
| 931 | |
| 932 | if args[0] == '-l': |
| 933 | if len(args) != 2: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 934 | print(USAGE) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 935 | sys.exit(1) |
| 936 | zf = ZipFile(args[1], 'r') |
| 937 | zf.printdir() |
| 938 | zf.close() |
| 939 | |
| 940 | elif args[0] == '-t': |
| 941 | if len(args) != 2: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 942 | print(USAGE) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 943 | sys.exit(1) |
| 944 | zf = ZipFile(args[1], 'r') |
| 945 | zf.testzip() |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 946 | print("Done testing") |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 947 | |
| 948 | elif args[0] == '-e': |
| 949 | if len(args) != 3: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 950 | print(USAGE) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 951 | sys.exit(1) |
| 952 | |
| 953 | zf = ZipFile(args[1], 'r') |
| 954 | out = args[2] |
| 955 | for path in zf.namelist(): |
| 956 | if path.startswith('./'): |
| 957 | tgt = os.path.join(out, path[2:]) |
| 958 | else: |
| 959 | tgt = os.path.join(out, path) |
| 960 | |
| 961 | tgtdir = os.path.dirname(tgt) |
| 962 | if not os.path.exists(tgtdir): |
| 963 | os.makedirs(tgtdir) |
| 964 | fp = open(tgt, 'wb') |
| 965 | fp.write(zf.read(path)) |
| 966 | fp.close() |
| 967 | zf.close() |
| 968 | |
| 969 | elif args[0] == '-c': |
| 970 | if len(args) < 3: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 971 | print(USAGE) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 972 | sys.exit(1) |
| 973 | |
| 974 | def addToZip(zf, path, zippath): |
| 975 | if os.path.isfile(path): |
| 976 | zf.write(path, zippath, ZIP_DEFLATED) |
| 977 | elif os.path.isdir(path): |
| 978 | for nm in os.listdir(path): |
| 979 | addToZip(zf, |
| 980 | os.path.join(path, nm), os.path.join(zippath, nm)) |
| 981 | # else: ignore |
| 982 | |
| 983 | zf = ZipFile(args[1], 'w', allowZip64=True) |
| 984 | for src in args[2:]: |
| 985 | addToZip(zf, src, os.path.basename(src)) |
| 986 | |
| 987 | zf.close() |
| 988 | |
| 989 | if __name__ == "__main__": |
| 990 | main() |