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