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