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