Benjamin Peterson | 90f5ba5 | 2010-03-11 22:53:45 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2 | #------------------------------------------------------------------- |
| 3 | # tarfile.py |
| 4 | #------------------------------------------------------------------- |
Christian Heimes | 9c1257e | 2007-11-04 11:37:22 +0000 | [diff] [blame] | 5 | # Copyright (C) 2002 Lars Gustaebel <lars@gustaebel.de> |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 6 | # All rights reserved. |
| 7 | # |
| 8 | # Permission is hereby granted, free of charge, to any person |
| 9 | # obtaining a copy of this software and associated documentation |
| 10 | # files (the "Software"), to deal in the Software without |
| 11 | # restriction, including without limitation the rights to use, |
| 12 | # copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 13 | # copies of the Software, and to permit persons to whom the |
| 14 | # Software is furnished to do so, subject to the following |
| 15 | # conditions: |
| 16 | # |
| 17 | # The above copyright notice and this permission notice shall be |
| 18 | # included in all copies or substantial portions of the Software. |
| 19 | # |
| 20 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 21 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES |
| 22 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 23 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 24 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, |
| 25 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 26 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR |
| 27 | # OTHER DEALINGS IN THE SOFTWARE. |
| 28 | # |
| 29 | """Read from and write to tar format archives. |
| 30 | """ |
| 31 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 32 | version = "0.9.0" |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 33 | __author__ = "Lars Gust\u00e4bel (lars@gustaebel.de)" |
Senthil Kumaran | 7c9719c | 2011-07-28 22:32:49 +0800 | [diff] [blame] | 34 | __date__ = "$Date: 2011-02-25 17:42:01 +0200 (Fri, 25 Feb 2011) $" |
| 35 | __cvsid__ = "$Id: tarfile.py 88586 2011-02-25 15:42:01Z marc-andre.lemburg $" |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 36 | __credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend." |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 37 | |
| 38 | #--------- |
| 39 | # Imports |
| 40 | #--------- |
| 41 | import sys |
| 42 | import os |
Eli Bendersky | 74c503b | 2012-01-03 06:26:13 +0200 | [diff] [blame] | 43 | import io |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 44 | import shutil |
| 45 | import stat |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 46 | import time |
| 47 | import struct |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 48 | import copy |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 49 | import re |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 50 | |
| 51 | try: |
| 52 | import grp, pwd |
| 53 | except ImportError: |
| 54 | grp = pwd = None |
| 55 | |
Brian Curtin | 16633fa | 2010-07-09 13:54:27 +0000 | [diff] [blame] | 56 | # os.symlink on Windows prior to 6.0 raises NotImplementedError |
| 57 | symlink_exception = (AttributeError, NotImplementedError) |
| 58 | try: |
| 59 | # WindowsError (1314) will be raised if the caller does not hold the |
| 60 | # SeCreateSymbolicLinkPrivilege privilege |
| 61 | symlink_exception += (WindowsError,) |
| 62 | except NameError: |
| 63 | pass |
| 64 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 65 | # from tarfile import * |
| 66 | __all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"] |
| 67 | |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 68 | from builtins import open as _open # Since 'open' is TarFile.open |
Guido van Rossum | 8f78fe9 | 2006-08-24 04:03:53 +0000 | [diff] [blame] | 69 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 70 | #--------------------------------------------------------- |
| 71 | # tar constants |
| 72 | #--------------------------------------------------------- |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 73 | NUL = b"\0" # the null character |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 74 | BLOCKSIZE = 512 # length of processing blocks |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 75 | RECORDSIZE = BLOCKSIZE * 20 # length of records |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 76 | GNU_MAGIC = b"ustar \0" # magic gnu tar string |
| 77 | POSIX_MAGIC = b"ustar\x0000" # magic posix tar string |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 78 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 79 | LENGTH_NAME = 100 # maximum length of a filename |
| 80 | LENGTH_LINK = 100 # maximum length of a linkname |
| 81 | LENGTH_PREFIX = 155 # maximum length of the prefix field |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 82 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 83 | REGTYPE = b"0" # regular file |
| 84 | AREGTYPE = b"\0" # regular file |
| 85 | LNKTYPE = b"1" # link (inside tarfile) |
| 86 | SYMTYPE = b"2" # symbolic link |
| 87 | CHRTYPE = b"3" # character special device |
| 88 | BLKTYPE = b"4" # block special device |
| 89 | DIRTYPE = b"5" # directory |
| 90 | FIFOTYPE = b"6" # fifo special device |
| 91 | CONTTYPE = b"7" # contiguous file |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 92 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 93 | GNUTYPE_LONGNAME = b"L" # GNU tar longname |
| 94 | GNUTYPE_LONGLINK = b"K" # GNU tar longlink |
| 95 | GNUTYPE_SPARSE = b"S" # GNU tar sparse file |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 96 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 97 | XHDTYPE = b"x" # POSIX.1-2001 extended header |
| 98 | XGLTYPE = b"g" # POSIX.1-2001 global header |
| 99 | SOLARIS_XHDTYPE = b"X" # Solaris extended header |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 100 | |
| 101 | USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format |
| 102 | GNU_FORMAT = 1 # GNU tar format |
| 103 | PAX_FORMAT = 2 # POSIX.1-2001 (pax) format |
| 104 | DEFAULT_FORMAT = GNU_FORMAT |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 105 | |
| 106 | #--------------------------------------------------------- |
| 107 | # tarfile constants |
| 108 | #--------------------------------------------------------- |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 109 | # File types that tarfile supports: |
| 110 | SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE, |
| 111 | SYMTYPE, DIRTYPE, FIFOTYPE, |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 112 | CONTTYPE, CHRTYPE, BLKTYPE, |
| 113 | GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, |
| 114 | GNUTYPE_SPARSE) |
| 115 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 116 | # File types that will be treated as a regular file. |
| 117 | REGULAR_TYPES = (REGTYPE, AREGTYPE, |
| 118 | CONTTYPE, GNUTYPE_SPARSE) |
| 119 | |
| 120 | # File types that are part of the GNU tar format. |
| 121 | GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK, |
| 122 | GNUTYPE_SPARSE) |
| 123 | |
| 124 | # Fields from a pax header that override a TarInfo attribute. |
| 125 | PAX_FIELDS = ("path", "linkpath", "size", "mtime", |
| 126 | "uid", "gid", "uname", "gname") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 127 | |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 128 | # Fields from a pax header that are affected by hdrcharset. |
| 129 | PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"} |
| 130 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 131 | # Fields in a pax header that are numbers, all other fields |
| 132 | # are treated as strings. |
| 133 | PAX_NUMBER_FIELDS = { |
| 134 | "atime": float, |
| 135 | "ctime": float, |
| 136 | "mtime": float, |
| 137 | "uid": int, |
| 138 | "gid": int, |
| 139 | "size": int |
| 140 | } |
| 141 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 142 | #--------------------------------------------------------- |
| 143 | # Bits used in the mode field, values in octal. |
| 144 | #--------------------------------------------------------- |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 145 | S_IFLNK = 0o120000 # symbolic link |
| 146 | S_IFREG = 0o100000 # regular file |
| 147 | S_IFBLK = 0o060000 # block device |
| 148 | S_IFDIR = 0o040000 # directory |
| 149 | S_IFCHR = 0o020000 # character device |
| 150 | S_IFIFO = 0o010000 # fifo |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 151 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 152 | TSUID = 0o4000 # set UID on execution |
| 153 | TSGID = 0o2000 # set GID on execution |
| 154 | TSVTX = 0o1000 # reserved |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 155 | |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 156 | TUREAD = 0o400 # read by owner |
| 157 | TUWRITE = 0o200 # write by owner |
| 158 | TUEXEC = 0o100 # execute/search by owner |
| 159 | TGREAD = 0o040 # read by group |
| 160 | TGWRITE = 0o020 # write by group |
| 161 | TGEXEC = 0o010 # execute/search by group |
| 162 | TOREAD = 0o004 # read by other |
| 163 | TOWRITE = 0o002 # write by other |
| 164 | TOEXEC = 0o001 # execute/search by other |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 165 | |
| 166 | #--------------------------------------------------------- |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 167 | # initialization |
| 168 | #--------------------------------------------------------- |
Victor Stinner | 0f35e2c | 2010-06-11 23:46:47 +0000 | [diff] [blame] | 169 | if os.name in ("nt", "ce"): |
| 170 | ENCODING = "utf-8" |
| 171 | else: |
| 172 | ENCODING = sys.getfilesystemencoding() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 173 | |
| 174 | #--------------------------------------------------------- |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 175 | # Some useful functions |
| 176 | #--------------------------------------------------------- |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 177 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 178 | def stn(s, length, encoding, errors): |
| 179 | """Convert a string to a null-terminated bytes object. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 180 | """ |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 181 | s = s.encode(encoding, errors) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 182 | return s[:length] + (length - len(s)) * NUL |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 183 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 184 | def nts(s, encoding, errors): |
| 185 | """Convert a null-terminated bytes object to a string. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 186 | """ |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 187 | p = s.find(b"\0") |
| 188 | if p != -1: |
| 189 | s = s[:p] |
| 190 | return s.decode(encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 191 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 192 | def nti(s): |
| 193 | """Convert a number field to a python number. |
| 194 | """ |
| 195 | # There are two possible encodings for a number field, see |
| 196 | # itn() below. |
Lars Gustäbel | ac3d137 | 2011-10-14 12:46:40 +0200 | [diff] [blame] | 197 | if s[0] in (0o200, 0o377): |
| 198 | n = 0 |
| 199 | for i in range(len(s) - 1): |
| 200 | n <<= 8 |
| 201 | n += s[i + 1] |
| 202 | if s[0] == 0o377: |
| 203 | n = -(256 ** (len(s) - 1) - n) |
| 204 | else: |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 205 | try: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 206 | n = int(nts(s, "ascii", "strict") or "0", 8) |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 207 | except ValueError: |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 208 | raise InvalidHeaderError("invalid header") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 209 | return n |
| 210 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 211 | def itn(n, digits=8, format=DEFAULT_FORMAT): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 212 | """Convert a python number to a number field. |
| 213 | """ |
| 214 | # POSIX 1003.1-1988 requires numbers to be encoded as a string of |
| 215 | # octal digits followed by a null-byte, this allows values up to |
| 216 | # (8**(digits-1))-1. GNU tar allows storing numbers greater than |
Lars Gustäbel | ac3d137 | 2011-10-14 12:46:40 +0200 | [diff] [blame] | 217 | # that if necessary. A leading 0o200 or 0o377 byte indicate this |
| 218 | # particular encoding, the following digits-1 bytes are a big-endian |
| 219 | # base-256 representation. This allows values up to (256**(digits-1))-1. |
| 220 | # A 0o200 byte indicates a positive number, a 0o377 byte a negative |
| 221 | # number. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 222 | if 0 <= n < 8 ** (digits - 1): |
Lars Gustäbel | a280ca75 | 2007-08-28 07:34:33 +0000 | [diff] [blame] | 223 | s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL |
Lars Gustäbel | ac3d137 | 2011-10-14 12:46:40 +0200 | [diff] [blame] | 224 | elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1): |
| 225 | if n >= 0: |
| 226 | s = bytearray([0o200]) |
| 227 | else: |
| 228 | s = bytearray([0o377]) |
| 229 | n = 256 ** digits + n |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 230 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 231 | for i in range(digits - 1): |
Lars Gustäbel | ac3d137 | 2011-10-14 12:46:40 +0200 | [diff] [blame] | 232 | s.insert(1, n & 0o377) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 233 | n >>= 8 |
Lars Gustäbel | ac3d137 | 2011-10-14 12:46:40 +0200 | [diff] [blame] | 234 | else: |
| 235 | raise ValueError("overflow in number field") |
| 236 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 237 | return s |
| 238 | |
| 239 | def calc_chksums(buf): |
| 240 | """Calculate the checksum for a member's header by summing up all |
| 241 | characters except for the chksum field which is treated as if |
| 242 | it was filled with spaces. According to the GNU tar sources, |
| 243 | some tars (Sun and NeXT) calculate chksum with signed char, |
| 244 | which will be different if there are chars in the buffer with |
| 245 | the high bit set. So we calculate two checksums, unsigned and |
| 246 | signed. |
| 247 | """ |
Ross Lagerwall | 468ff4c | 2012-05-17 19:49:27 +0200 | [diff] [blame] | 248 | unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf)) |
| 249 | signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf)) |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 250 | return unsigned_chksum, signed_chksum |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 251 | |
| 252 | def copyfileobj(src, dst, length=None): |
| 253 | """Copy length bytes from fileobj src to fileobj dst. |
| 254 | If length is None, copy the entire content. |
| 255 | """ |
| 256 | if length == 0: |
| 257 | return |
| 258 | if length is None: |
| 259 | shutil.copyfileobj(src, dst) |
| 260 | return |
| 261 | |
| 262 | BUFSIZE = 16 * 1024 |
| 263 | blocks, remainder = divmod(length, BUFSIZE) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 264 | for b in range(blocks): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 265 | buf = src.read(BUFSIZE) |
| 266 | if len(buf) < BUFSIZE: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 267 | raise IOError("end of file reached") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 268 | dst.write(buf) |
| 269 | |
| 270 | if remainder != 0: |
| 271 | buf = src.read(remainder) |
| 272 | if len(buf) < remainder: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 273 | raise IOError("end of file reached") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 274 | dst.write(buf) |
| 275 | return |
| 276 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 277 | def filemode(mode): |
Giampaolo Rodola' | ffa1d0b | 2012-05-15 15:30:25 +0200 | [diff] [blame] | 278 | """Deprecated in this location; use stat.filemode.""" |
| 279 | import warnings |
| 280 | warnings.warn("deprecated in favor of stat.filemode", |
| 281 | DeprecationWarning, 2) |
| 282 | return stat.filemode(mode) |
| 283 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 284 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 285 | class TarError(Exception): |
| 286 | """Base exception.""" |
| 287 | pass |
| 288 | class ExtractError(TarError): |
| 289 | """General exception for extract errors.""" |
| 290 | pass |
| 291 | class ReadError(TarError): |
| 292 | """Exception for unreadble tar archives.""" |
| 293 | pass |
| 294 | class CompressionError(TarError): |
| 295 | """Exception for unavailable compression methods.""" |
| 296 | pass |
| 297 | class StreamError(TarError): |
| 298 | """Exception for unsupported operations on stream-like TarFiles.""" |
| 299 | pass |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 300 | class HeaderError(TarError): |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 301 | """Base exception for header errors.""" |
| 302 | pass |
| 303 | class EmptyHeaderError(HeaderError): |
| 304 | """Exception for empty headers.""" |
| 305 | pass |
| 306 | class TruncatedHeaderError(HeaderError): |
| 307 | """Exception for truncated headers.""" |
| 308 | pass |
| 309 | class EOFHeaderError(HeaderError): |
| 310 | """Exception for end of file headers.""" |
| 311 | pass |
| 312 | class InvalidHeaderError(HeaderError): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 313 | """Exception for invalid headers.""" |
| 314 | pass |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 315 | class SubsequentHeaderError(HeaderError): |
| 316 | """Exception for missing and invalid extended headers.""" |
| 317 | pass |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 318 | |
| 319 | #--------------------------- |
| 320 | # internal stream interface |
| 321 | #--------------------------- |
| 322 | class _LowLevelFile: |
| 323 | """Low-level file object. Supports reading and writing. |
| 324 | It is used instead of a regular file object for streaming |
| 325 | access. |
| 326 | """ |
| 327 | |
| 328 | def __init__(self, name, mode): |
| 329 | mode = { |
| 330 | "r": os.O_RDONLY, |
| 331 | "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC, |
| 332 | }[mode] |
| 333 | if hasattr(os, "O_BINARY"): |
| 334 | mode |= os.O_BINARY |
Lars Gustäbel | d6eb70b | 2010-04-29 15:37:02 +0000 | [diff] [blame] | 335 | self.fd = os.open(name, mode, 0o666) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 336 | |
| 337 | def close(self): |
| 338 | os.close(self.fd) |
| 339 | |
| 340 | def read(self, size): |
| 341 | return os.read(self.fd, size) |
| 342 | |
| 343 | def write(self, s): |
| 344 | os.write(self.fd, s) |
| 345 | |
| 346 | class _Stream: |
| 347 | """Class that serves as an adapter between TarFile and |
| 348 | a stream-like object. The stream-like object only |
| 349 | needs to have a read() or write() method and is accessed |
| 350 | blockwise. Use of gzip or bzip2 compression is possible. |
| 351 | A stream-like object could be for example: sys.stdin, |
| 352 | sys.stdout, a socket, a tape device etc. |
| 353 | |
| 354 | _Stream is intended to be used only internally. |
| 355 | """ |
| 356 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 357 | def __init__(self, name, mode, comptype, fileobj, bufsize): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 358 | """Construct a _Stream object. |
| 359 | """ |
| 360 | self._extfileobj = True |
| 361 | if fileobj is None: |
| 362 | fileobj = _LowLevelFile(name, mode) |
| 363 | self._extfileobj = False |
| 364 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 365 | if comptype == '*': |
| 366 | # Enable transparent compression detection for the |
| 367 | # stream interface |
| 368 | fileobj = _StreamProxy(fileobj) |
| 369 | comptype = fileobj.getcomptype() |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 370 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 371 | self.name = name or "" |
| 372 | self.mode = mode |
| 373 | self.comptype = comptype |
| 374 | self.fileobj = fileobj |
| 375 | self.bufsize = bufsize |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 376 | self.buf = b"" |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 377 | self.pos = 0 |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 378 | self.closed = False |
| 379 | |
Antoine Pitrou | 605c293 | 2010-09-23 20:15:14 +0000 | [diff] [blame] | 380 | try: |
| 381 | if comptype == "gz": |
| 382 | try: |
| 383 | import zlib |
| 384 | except ImportError: |
| 385 | raise CompressionError("zlib module is not available") |
| 386 | self.zlib = zlib |
| 387 | self.crc = zlib.crc32(b"") |
| 388 | if mode == "r": |
| 389 | self._init_read_gz() |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 390 | self.exception = zlib.error |
Antoine Pitrou | 605c293 | 2010-09-23 20:15:14 +0000 | [diff] [blame] | 391 | else: |
| 392 | self._init_write_gz() |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 393 | |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 394 | elif comptype == "bz2": |
Antoine Pitrou | 605c293 | 2010-09-23 20:15:14 +0000 | [diff] [blame] | 395 | try: |
| 396 | import bz2 |
| 397 | except ImportError: |
| 398 | raise CompressionError("bz2 module is not available") |
| 399 | if mode == "r": |
| 400 | self.dbuf = b"" |
| 401 | self.cmp = bz2.BZ2Decompressor() |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 402 | self.exception = IOError |
Antoine Pitrou | 605c293 | 2010-09-23 20:15:14 +0000 | [diff] [blame] | 403 | else: |
| 404 | self.cmp = bz2.BZ2Compressor() |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 405 | |
| 406 | elif comptype == "xz": |
| 407 | try: |
| 408 | import lzma |
| 409 | except ImportError: |
| 410 | raise CompressionError("lzma module is not available") |
| 411 | if mode == "r": |
| 412 | self.dbuf = b"" |
| 413 | self.cmp = lzma.LZMADecompressor() |
| 414 | self.exception = lzma.LZMAError |
| 415 | else: |
| 416 | self.cmp = lzma.LZMACompressor() |
| 417 | |
| 418 | elif comptype != "tar": |
| 419 | raise CompressionError("unknown compression type %r" % comptype) |
| 420 | |
Antoine Pitrou | 605c293 | 2010-09-23 20:15:14 +0000 | [diff] [blame] | 421 | except: |
| 422 | if not self._extfileobj: |
| 423 | self.fileobj.close() |
| 424 | self.closed = True |
| 425 | raise |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 426 | |
| 427 | def __del__(self): |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 428 | if hasattr(self, "closed") and not self.closed: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 429 | self.close() |
| 430 | |
| 431 | def _init_write_gz(self): |
| 432 | """Initialize for writing with gzip compression. |
| 433 | """ |
| 434 | self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, |
| 435 | -self.zlib.MAX_WBITS, |
| 436 | self.zlib.DEF_MEM_LEVEL, |
| 437 | 0) |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 438 | timestamp = struct.pack("<L", int(time.time())) |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 439 | self.__write(b"\037\213\010\010" + timestamp + b"\002\377") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 440 | if self.name.endswith(".gz"): |
| 441 | self.name = self.name[:-3] |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 442 | # RFC1952 says we must use ISO-8859-1 for the FNAME field. |
| 443 | self.__write(self.name.encode("iso-8859-1", "replace") + NUL) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 444 | |
| 445 | def write(self, s): |
| 446 | """Write string s to the stream. |
| 447 | """ |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 448 | if self.comptype == "gz": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 449 | self.crc = self.zlib.crc32(s, self.crc) |
| 450 | self.pos += len(s) |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 451 | if self.comptype != "tar": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 452 | s = self.cmp.compress(s) |
| 453 | self.__write(s) |
| 454 | |
| 455 | def __write(self, s): |
| 456 | """Write string s to the stream if a whole new block |
| 457 | is ready to be written. |
| 458 | """ |
| 459 | self.buf += s |
| 460 | while len(self.buf) > self.bufsize: |
| 461 | self.fileobj.write(self.buf[:self.bufsize]) |
| 462 | self.buf = self.buf[self.bufsize:] |
| 463 | |
| 464 | def close(self): |
| 465 | """Close the _Stream object. No operation should be |
| 466 | done on it afterwards. |
| 467 | """ |
| 468 | if self.closed: |
| 469 | return |
| 470 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 471 | if self.mode == "w" and self.comptype != "tar": |
Martin v. Löwis | c234a52 | 2004-08-22 21:28:33 +0000 | [diff] [blame] | 472 | self.buf += self.cmp.flush() |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 473 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 474 | if self.mode == "w" and self.buf: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 475 | self.fileobj.write(self.buf) |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 476 | self.buf = b"" |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 477 | if self.comptype == "gz": |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 478 | # The native zlib crc is an unsigned 32-bit integer, but |
| 479 | # the Python wrapper implicitly casts that to a signed C |
| 480 | # long. So, on a 32-bit box self.crc may "look negative", |
| 481 | # while the same crc on a 64-bit box may "look positive". |
| 482 | # To avoid irksome warnings from the `struct` module, force |
| 483 | # it to look positive on all boxes. |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 484 | self.fileobj.write(struct.pack("<L", self.crc & 0xffffffff)) |
| 485 | self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 486 | |
| 487 | if not self._extfileobj: |
| 488 | self.fileobj.close() |
| 489 | |
| 490 | self.closed = True |
| 491 | |
| 492 | def _init_read_gz(self): |
| 493 | """Initialize for reading a gzip compressed fileobj. |
| 494 | """ |
| 495 | self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 496 | self.dbuf = b"" |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 497 | |
| 498 | # taken from gzip.GzipFile with some alterations |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 499 | if self.__read(2) != b"\037\213": |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 500 | raise ReadError("not a gzip file") |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 501 | if self.__read(1) != b"\010": |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 502 | raise CompressionError("unsupported compression method") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 503 | |
| 504 | flag = ord(self.__read(1)) |
| 505 | self.__read(6) |
| 506 | |
| 507 | if flag & 4: |
| 508 | xlen = ord(self.__read(1)) + 256 * ord(self.__read(1)) |
| 509 | self.read(xlen) |
| 510 | if flag & 8: |
| 511 | while True: |
| 512 | s = self.__read(1) |
| 513 | if not s or s == NUL: |
| 514 | break |
| 515 | if flag & 16: |
| 516 | while True: |
| 517 | s = self.__read(1) |
| 518 | if not s or s == NUL: |
| 519 | break |
| 520 | if flag & 2: |
| 521 | self.__read(2) |
| 522 | |
| 523 | def tell(self): |
| 524 | """Return the stream's file pointer position. |
| 525 | """ |
| 526 | return self.pos |
| 527 | |
| 528 | def seek(self, pos=0): |
| 529 | """Set the stream's file pointer to pos. Negative seeking |
| 530 | is forbidden. |
| 531 | """ |
| 532 | if pos - self.pos >= 0: |
| 533 | blocks, remainder = divmod(pos - self.pos, self.bufsize) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 534 | for i in range(blocks): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 535 | self.read(self.bufsize) |
| 536 | self.read(remainder) |
| 537 | else: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 538 | raise StreamError("seeking backwards is not allowed") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 539 | return self.pos |
| 540 | |
| 541 | def read(self, size=None): |
| 542 | """Return the next size number of bytes from the stream. |
| 543 | If size is not defined, return all bytes of the stream |
| 544 | up to EOF. |
| 545 | """ |
| 546 | if size is None: |
| 547 | t = [] |
| 548 | while True: |
| 549 | buf = self._read(self.bufsize) |
| 550 | if not buf: |
| 551 | break |
| 552 | t.append(buf) |
| 553 | buf = "".join(t) |
| 554 | else: |
| 555 | buf = self._read(size) |
| 556 | self.pos += len(buf) |
| 557 | return buf |
| 558 | |
| 559 | def _read(self, size): |
| 560 | """Return size bytes from the stream. |
| 561 | """ |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 562 | if self.comptype == "tar": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 563 | return self.__read(size) |
| 564 | |
| 565 | c = len(self.dbuf) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 566 | while c < size: |
| 567 | buf = self.__read(self.bufsize) |
| 568 | if not buf: |
| 569 | break |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 570 | try: |
| 571 | buf = self.cmp.decompress(buf) |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 572 | except self.exception: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 573 | raise ReadError("invalid compressed data") |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 574 | self.dbuf += buf |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 575 | c += len(buf) |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 576 | buf = self.dbuf[:size] |
| 577 | self.dbuf = self.dbuf[size:] |
| 578 | return buf |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 579 | |
| 580 | def __read(self, size): |
| 581 | """Return size bytes from stream. If internal buffer is empty, |
| 582 | read another block from the stream. |
| 583 | """ |
| 584 | c = len(self.buf) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 585 | while c < size: |
| 586 | buf = self.fileobj.read(self.bufsize) |
| 587 | if not buf: |
| 588 | break |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 589 | self.buf += buf |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 590 | c += len(buf) |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 591 | buf = self.buf[:size] |
| 592 | self.buf = self.buf[size:] |
| 593 | return buf |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 594 | # class _Stream |
| 595 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 596 | class _StreamProxy(object): |
| 597 | """Small proxy class that enables transparent compression |
| 598 | detection for the Stream interface (mode 'r|*'). |
| 599 | """ |
| 600 | |
| 601 | def __init__(self, fileobj): |
| 602 | self.fileobj = fileobj |
| 603 | self.buf = self.fileobj.read(BLOCKSIZE) |
| 604 | |
| 605 | def read(self, size): |
| 606 | self.read = self.fileobj.read |
| 607 | return self.buf |
| 608 | |
| 609 | def getcomptype(self): |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 610 | if self.buf.startswith(b"\x1f\x8b\x08"): |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 611 | return "gz" |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 612 | elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY": |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 613 | return "bz2" |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 614 | elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")): |
| 615 | return "xz" |
| 616 | else: |
| 617 | return "tar" |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 618 | |
| 619 | def close(self): |
| 620 | self.fileobj.close() |
| 621 | # class StreamProxy |
| 622 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 623 | #------------------------ |
| 624 | # Extraction file object |
| 625 | #------------------------ |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 626 | class _FileInFile(object): |
| 627 | """A thin wrapper around an existing file object that |
| 628 | provides a part of its data as an individual file |
| 629 | object. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 630 | """ |
| 631 | |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 632 | def __init__(self, fileobj, offset, size, blockinfo=None): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 633 | self.fileobj = fileobj |
| 634 | self.offset = offset |
| 635 | self.size = size |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 636 | self.position = 0 |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 637 | self.name = getattr(fileobj, "name", None) |
| 638 | self.closed = False |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 639 | |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 640 | if blockinfo is None: |
| 641 | blockinfo = [(0, size)] |
| 642 | |
| 643 | # Construct a map with data and zero blocks. |
| 644 | self.map_index = 0 |
| 645 | self.map = [] |
| 646 | lastpos = 0 |
| 647 | realpos = self.offset |
| 648 | for offset, size in blockinfo: |
| 649 | if offset > lastpos: |
| 650 | self.map.append((False, lastpos, offset, None)) |
| 651 | self.map.append((True, offset, offset + size, realpos)) |
| 652 | realpos += size |
| 653 | lastpos = offset + size |
| 654 | if lastpos < self.size: |
| 655 | self.map.append((False, lastpos, self.size, None)) |
| 656 | |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 657 | def flush(self): |
| 658 | pass |
| 659 | |
| 660 | def readable(self): |
| 661 | return True |
| 662 | |
| 663 | def writable(self): |
| 664 | return False |
| 665 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 666 | def seekable(self): |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 667 | return self.fileobj.seekable() |
| 668 | |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 669 | def tell(self): |
| 670 | """Return the current file position. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 671 | """ |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 672 | return self.position |
| 673 | |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 674 | def seek(self, position, whence=io.SEEK_SET): |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 675 | """Seek to a position in the file. |
| 676 | """ |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 677 | if whence == io.SEEK_SET: |
| 678 | self.position = min(max(position, 0), self.size) |
| 679 | elif whence == io.SEEK_CUR: |
| 680 | if position < 0: |
| 681 | self.position = max(self.position + position, 0) |
| 682 | else: |
| 683 | self.position = min(self.position + position, self.size) |
| 684 | elif whence == io.SEEK_END: |
| 685 | self.position = max(min(self.size + position, self.size), 0) |
| 686 | else: |
| 687 | raise ValueError("Invalid argument") |
| 688 | return self.position |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 689 | |
| 690 | def read(self, size=None): |
| 691 | """Read data from the file. |
| 692 | """ |
| 693 | if size is None: |
| 694 | size = self.size - self.position |
| 695 | else: |
| 696 | size = min(size, self.size - self.position) |
| 697 | |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 698 | buf = b"" |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 699 | while size > 0: |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 700 | while True: |
| 701 | data, start, stop, offset = self.map[self.map_index] |
| 702 | if start <= self.position < stop: |
| 703 | break |
| 704 | else: |
| 705 | self.map_index += 1 |
| 706 | if self.map_index == len(self.map): |
| 707 | self.map_index = 0 |
| 708 | length = min(size, stop - self.position) |
| 709 | if data: |
Lars Gustäbel | dd07104 | 2011-02-23 11:42:22 +0000 | [diff] [blame] | 710 | self.fileobj.seek(offset + (self.position - start)) |
| 711 | buf += self.fileobj.read(length) |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 712 | else: |
| 713 | buf += NUL * length |
| 714 | size -= length |
| 715 | self.position += length |
| 716 | return buf |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 717 | |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 718 | def readinto(self, b): |
| 719 | buf = self.read(len(b)) |
| 720 | b[:len(buf)] = buf |
| 721 | return len(buf) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 722 | |
| 723 | def close(self): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 724 | self.closed = True |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 725 | #class _FileInFile |
Martin v. Löwis | df24153 | 2005-03-03 08:17:42 +0000 | [diff] [blame] | 726 | |
Lars Gustäbel | b062a2f | 2012-05-14 13:18:16 +0200 | [diff] [blame] | 727 | class ExFileObject(io.BufferedReader): |
| 728 | |
| 729 | def __init__(self, tarfile, tarinfo): |
| 730 | fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data, |
| 731 | tarinfo.size, tarinfo.sparse) |
| 732 | super().__init__(fileobj) |
| 733 | #class ExFileObject |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 734 | |
| 735 | #------------------ |
| 736 | # Exported Classes |
| 737 | #------------------ |
| 738 | class TarInfo(object): |
| 739 | """Informational class which holds the details about an |
| 740 | archive member given by a tar header block. |
| 741 | TarInfo objects are returned by TarFile.getmember(), |
| 742 | TarFile.getmembers() and TarFile.gettarinfo() and are |
| 743 | usually created internally. |
| 744 | """ |
| 745 | |
Lars Gustäbel | c2ea8c6 | 2008-04-14 10:05:48 +0000 | [diff] [blame] | 746 | __slots__ = ("name", "mode", "uid", "gid", "size", "mtime", |
| 747 | "chksum", "type", "linkname", "uname", "gname", |
| 748 | "devmajor", "devminor", |
| 749 | "offset", "offset_data", "pax_headers", "sparse", |
| 750 | "tarfile", "_sparse_structs", "_link_target") |
| 751 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 752 | def __init__(self, name=""): |
| 753 | """Construct a TarInfo object. name is the optional name |
| 754 | of the member. |
| 755 | """ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 756 | self.name = name # member name |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 757 | self.mode = 0o644 # file permissions |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 758 | self.uid = 0 # user id |
| 759 | self.gid = 0 # group id |
| 760 | self.size = 0 # file size |
| 761 | self.mtime = 0 # modification time |
| 762 | self.chksum = 0 # header checksum |
| 763 | self.type = REGTYPE # member type |
| 764 | self.linkname = "" # link name |
Lars Gustäbel | 331b800 | 2010-10-04 15:18:47 +0000 | [diff] [blame] | 765 | self.uname = "" # user name |
| 766 | self.gname = "" # group name |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 767 | self.devmajor = 0 # device major number |
| 768 | self.devminor = 0 # device minor number |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 769 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 770 | self.offset = 0 # the tar header starts here |
| 771 | self.offset_data = 0 # the file's data starts here |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 772 | |
Lars Gustäbel | c2ea8c6 | 2008-04-14 10:05:48 +0000 | [diff] [blame] | 773 | self.sparse = None # sparse member information |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 774 | self.pax_headers = {} # pax header information |
| 775 | |
| 776 | # In pax headers the "name" and "linkname" field are called |
| 777 | # "path" and "linkpath". |
| 778 | def _getpath(self): |
| 779 | return self.name |
| 780 | def _setpath(self, name): |
| 781 | self.name = name |
| 782 | path = property(_getpath, _setpath) |
| 783 | |
| 784 | def _getlinkpath(self): |
| 785 | return self.linkname |
| 786 | def _setlinkpath(self, linkname): |
| 787 | self.linkname = linkname |
| 788 | linkpath = property(_getlinkpath, _setlinkpath) |
| 789 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 790 | def __repr__(self): |
| 791 | return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self)) |
| 792 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 793 | def get_info(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 794 | """Return the TarInfo's attributes as a dictionary. |
| 795 | """ |
| 796 | info = { |
Lars Gustäbel | bfdfdda | 2009-08-28 19:59:59 +0000 | [diff] [blame] | 797 | "name": self.name, |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 798 | "mode": self.mode & 0o7777, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 799 | "uid": self.uid, |
| 800 | "gid": self.gid, |
| 801 | "size": self.size, |
| 802 | "mtime": self.mtime, |
| 803 | "chksum": self.chksum, |
| 804 | "type": self.type, |
Lars Gustäbel | bfdfdda | 2009-08-28 19:59:59 +0000 | [diff] [blame] | 805 | "linkname": self.linkname, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 806 | "uname": self.uname, |
| 807 | "gname": self.gname, |
| 808 | "devmajor": self.devmajor, |
| 809 | "devminor": self.devminor |
| 810 | } |
| 811 | |
| 812 | if info["type"] == DIRTYPE and not info["name"].endswith("/"): |
| 813 | info["name"] += "/" |
| 814 | |
| 815 | return info |
| 816 | |
Victor Stinner | de629d4 | 2010-05-05 21:43:57 +0000 | [diff] [blame] | 817 | def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 818 | """Return a tar header as a string of 512 byte blocks. |
| 819 | """ |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 820 | info = self.get_info() |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 821 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 822 | if format == USTAR_FORMAT: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 823 | return self.create_ustar_header(info, encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 824 | elif format == GNU_FORMAT: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 825 | return self.create_gnu_header(info, encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 826 | elif format == PAX_FORMAT: |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 827 | return self.create_pax_header(info, encoding) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 828 | else: |
| 829 | raise ValueError("invalid format") |
| 830 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 831 | def create_ustar_header(self, info, encoding, errors): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 832 | """Return the object as a ustar header block. |
| 833 | """ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 834 | info["magic"] = POSIX_MAGIC |
| 835 | |
| 836 | if len(info["linkname"]) > LENGTH_LINK: |
| 837 | raise ValueError("linkname is too long") |
| 838 | |
| 839 | if len(info["name"]) > LENGTH_NAME: |
| 840 | info["prefix"], info["name"] = self._posix_split_name(info["name"]) |
| 841 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 842 | return self._create_header(info, USTAR_FORMAT, encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 843 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 844 | def create_gnu_header(self, info, encoding, errors): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 845 | """Return the object as a GNU header block sequence. |
| 846 | """ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 847 | info["magic"] = GNU_MAGIC |
| 848 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 849 | buf = b"" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 850 | if len(info["linkname"]) > LENGTH_LINK: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 851 | buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 852 | |
| 853 | if len(info["name"]) > LENGTH_NAME: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 854 | buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 855 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 856 | return buf + self._create_header(info, GNU_FORMAT, encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 857 | |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 858 | def create_pax_header(self, info, encoding): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 859 | """Return the object as a ustar header block. If it cannot be |
| 860 | represented this way, prepend a pax extended header sequence |
| 861 | with supplement information. |
| 862 | """ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 863 | info["magic"] = POSIX_MAGIC |
| 864 | pax_headers = self.pax_headers.copy() |
| 865 | |
| 866 | # Test string fields for values that exceed the field length or cannot |
| 867 | # be represented in ASCII encoding. |
| 868 | for name, hname, length in ( |
| 869 | ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK), |
| 870 | ("uname", "uname", 32), ("gname", "gname", 32)): |
| 871 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 872 | if hname in pax_headers: |
| 873 | # The pax header has priority. |
| 874 | continue |
| 875 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 876 | # Try to encode the string as ASCII. |
| 877 | try: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 878 | info[name].encode("ascii", "strict") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 879 | except UnicodeEncodeError: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 880 | pax_headers[hname] = info[name] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 881 | continue |
| 882 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 883 | if len(info[name]) > length: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 884 | pax_headers[hname] = info[name] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 885 | |
| 886 | # Test number fields for values that exceed the field limit or values |
| 887 | # that like to be stored as float. |
| 888 | for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)): |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 889 | if name in pax_headers: |
| 890 | # The pax header has priority. Avoid overflow. |
| 891 | info[name] = 0 |
| 892 | continue |
| 893 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 894 | val = info[name] |
| 895 | if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float): |
Guido van Rossum | ef87d6e | 2007-05-02 19:09:54 +0000 | [diff] [blame] | 896 | pax_headers[name] = str(val) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 897 | info[name] = 0 |
| 898 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 899 | # Create a pax extended header if necessary. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 900 | if pax_headers: |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 901 | buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 902 | else: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 903 | buf = b"" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 904 | |
Lars Gustäbel | 3741eff | 2007-08-21 12:17:05 +0000 | [diff] [blame] | 905 | return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 906 | |
| 907 | @classmethod |
Lars Gustäbel | 3741eff | 2007-08-21 12:17:05 +0000 | [diff] [blame] | 908 | def create_pax_global_header(cls, pax_headers): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 909 | """Return the object as a pax global header block sequence. |
| 910 | """ |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 911 | return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 912 | |
| 913 | def _posix_split_name(self, name): |
| 914 | """Split a name longer than 100 chars into a prefix |
| 915 | and a name part. |
| 916 | """ |
| 917 | prefix = name[:LENGTH_PREFIX + 1] |
| 918 | while prefix and prefix[-1] != "/": |
| 919 | prefix = prefix[:-1] |
| 920 | |
| 921 | name = name[len(prefix):] |
| 922 | prefix = prefix[:-1] |
| 923 | |
| 924 | if not prefix or len(name) > LENGTH_NAME: |
| 925 | raise ValueError("name is too long") |
| 926 | return prefix, name |
| 927 | |
| 928 | @staticmethod |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 929 | def _create_header(info, format, encoding, errors): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 930 | """Return a header block. info is a dictionary with file |
| 931 | information, format must be one of the *_FORMAT constants. |
| 932 | """ |
| 933 | parts = [ |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 934 | stn(info.get("name", ""), 100, encoding, errors), |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 935 | itn(info.get("mode", 0) & 0o7777, 8, format), |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 936 | itn(info.get("uid", 0), 8, format), |
| 937 | itn(info.get("gid", 0), 8, format), |
| 938 | itn(info.get("size", 0), 12, format), |
| 939 | itn(info.get("mtime", 0), 12, format), |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 940 | b" ", # checksum field |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 941 | info.get("type", REGTYPE), |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 942 | stn(info.get("linkname", ""), 100, encoding, errors), |
| 943 | info.get("magic", POSIX_MAGIC), |
Lars Gustäbel | 331b800 | 2010-10-04 15:18:47 +0000 | [diff] [blame] | 944 | stn(info.get("uname", ""), 32, encoding, errors), |
| 945 | stn(info.get("gname", ""), 32, encoding, errors), |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 946 | itn(info.get("devmajor", 0), 8, format), |
| 947 | itn(info.get("devminor", 0), 8, format), |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 948 | stn(info.get("prefix", ""), 155, encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 949 | ] |
| 950 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 951 | buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 952 | chksum = calc_chksums(buf[-BLOCKSIZE:])[0] |
Lars Gustäbel | a280ca75 | 2007-08-28 07:34:33 +0000 | [diff] [blame] | 953 | buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 954 | return buf |
| 955 | |
| 956 | @staticmethod |
| 957 | def _create_payload(payload): |
| 958 | """Return the string payload filled with zero bytes |
| 959 | up to the next 512 byte border. |
| 960 | """ |
| 961 | blocks, remainder = divmod(len(payload), BLOCKSIZE) |
| 962 | if remainder > 0: |
| 963 | payload += (BLOCKSIZE - remainder) * NUL |
| 964 | return payload |
| 965 | |
| 966 | @classmethod |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 967 | def _create_gnu_long_header(cls, name, type, encoding, errors): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 968 | """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence |
| 969 | for name. |
| 970 | """ |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 971 | name = name.encode(encoding, errors) + NUL |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 972 | |
| 973 | info = {} |
| 974 | info["name"] = "././@LongLink" |
| 975 | info["type"] = type |
| 976 | info["size"] = len(name) |
| 977 | info["magic"] = GNU_MAGIC |
| 978 | |
| 979 | # create extended header + name blocks. |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 980 | return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 981 | cls._create_payload(name) |
| 982 | |
| 983 | @classmethod |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 984 | def _create_pax_generic_header(cls, pax_headers, type, encoding): |
| 985 | """Return a POSIX.1-2008 extended or global header sequence |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 986 | that contains a list of keyword, value pairs. The values |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 987 | must be strings. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 988 | """ |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 989 | # Check if one of the fields contains surrogate characters and thereby |
| 990 | # forces hdrcharset=BINARY, see _proc_pax() for more information. |
| 991 | binary = False |
| 992 | for keyword, value in pax_headers.items(): |
| 993 | try: |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 994 | value.encode("utf-8", "strict") |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 995 | except UnicodeEncodeError: |
| 996 | binary = True |
| 997 | break |
| 998 | |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 999 | records = b"" |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1000 | if binary: |
| 1001 | # Put the hdrcharset field at the beginning of the header. |
| 1002 | records += b"21 hdrcharset=BINARY\n" |
| 1003 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1004 | for keyword, value in pax_headers.items(): |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1005 | keyword = keyword.encode("utf-8") |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1006 | if binary: |
| 1007 | # Try to restore the original byte representation of `value'. |
| 1008 | # Needless to say, that the encoding must match the string. |
| 1009 | value = value.encode(encoding, "surrogateescape") |
| 1010 | else: |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1011 | value = value.encode("utf-8") |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1012 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1013 | l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' |
| 1014 | n = p = 0 |
| 1015 | while True: |
| 1016 | n = l + len(str(p)) |
| 1017 | if n == p: |
| 1018 | break |
| 1019 | p = n |
Lars Gustäbel | a280ca75 | 2007-08-28 07:34:33 +0000 | [diff] [blame] | 1020 | records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n" |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1021 | |
| 1022 | # We use a hardcoded "././@PaxHeader" name like star does |
| 1023 | # instead of the one that POSIX recommends. |
| 1024 | info = {} |
| 1025 | info["name"] = "././@PaxHeader" |
| 1026 | info["type"] = type |
| 1027 | info["size"] = len(records) |
| 1028 | info["magic"] = POSIX_MAGIC |
| 1029 | |
| 1030 | # Create pax header + record blocks. |
Lars Gustäbel | 3741eff | 2007-08-21 12:17:05 +0000 | [diff] [blame] | 1031 | return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1032 | cls._create_payload(records) |
| 1033 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1034 | @classmethod |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1035 | def frombuf(cls, buf, encoding, errors): |
| 1036 | """Construct a TarInfo object from a 512 byte bytes object. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1037 | """ |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1038 | if len(buf) == 0: |
| 1039 | raise EmptyHeaderError("empty header") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1040 | if len(buf) != BLOCKSIZE: |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1041 | raise TruncatedHeaderError("truncated header") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1042 | if buf.count(NUL) == BLOCKSIZE: |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1043 | raise EOFHeaderError("end of file header") |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1044 | |
| 1045 | chksum = nti(buf[148:156]) |
| 1046 | if chksum not in calc_chksums(buf): |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1047 | raise InvalidHeaderError("bad checksum") |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1048 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1049 | obj = cls() |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1050 | obj.name = nts(buf[0:100], encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1051 | obj.mode = nti(buf[100:108]) |
| 1052 | obj.uid = nti(buf[108:116]) |
| 1053 | obj.gid = nti(buf[116:124]) |
| 1054 | obj.size = nti(buf[124:136]) |
| 1055 | obj.mtime = nti(buf[136:148]) |
| 1056 | obj.chksum = chksum |
| 1057 | obj.type = buf[156:157] |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1058 | obj.linkname = nts(buf[157:257], encoding, errors) |
| 1059 | obj.uname = nts(buf[265:297], encoding, errors) |
| 1060 | obj.gname = nts(buf[297:329], encoding, errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1061 | obj.devmajor = nti(buf[329:337]) |
| 1062 | obj.devminor = nti(buf[337:345]) |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1063 | prefix = nts(buf[345:500], encoding, errors) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1064 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1065 | # Old V7 tar format represents a directory as a regular |
| 1066 | # file with a trailing slash. |
| 1067 | if obj.type == AREGTYPE and obj.name.endswith("/"): |
| 1068 | obj.type = DIRTYPE |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1069 | |
Lars Gustäbel | c2ea8c6 | 2008-04-14 10:05:48 +0000 | [diff] [blame] | 1070 | # The old GNU sparse format occupies some of the unused |
| 1071 | # space in the buffer for up to 4 sparse structures. |
| 1072 | # Save the them for later processing in _proc_sparse(). |
| 1073 | if obj.type == GNUTYPE_SPARSE: |
| 1074 | pos = 386 |
| 1075 | structs = [] |
| 1076 | for i in range(4): |
| 1077 | try: |
| 1078 | offset = nti(buf[pos:pos + 12]) |
| 1079 | numbytes = nti(buf[pos + 12:pos + 24]) |
| 1080 | except ValueError: |
| 1081 | break |
| 1082 | structs.append((offset, numbytes)) |
| 1083 | pos += 24 |
| 1084 | isextended = bool(buf[482]) |
| 1085 | origsize = nti(buf[483:495]) |
| 1086 | obj._sparse_structs = (structs, isextended, origsize) |
| 1087 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1088 | # Remove redundant slashes from directories. |
| 1089 | if obj.isdir(): |
| 1090 | obj.name = obj.name.rstrip("/") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1091 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1092 | # Reconstruct a ustar longname. |
| 1093 | if prefix and obj.type not in GNU_TYPES: |
| 1094 | obj.name = prefix + "/" + obj.name |
| 1095 | return obj |
| 1096 | |
| 1097 | @classmethod |
| 1098 | def fromtarfile(cls, tarfile): |
| 1099 | """Return the next TarInfo object from TarFile object |
| 1100 | tarfile. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1101 | """ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1102 | buf = tarfile.fileobj.read(BLOCKSIZE) |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1103 | obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1104 | obj.offset = tarfile.fileobj.tell() - BLOCKSIZE |
| 1105 | return obj._proc_member(tarfile) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1106 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1107 | #-------------------------------------------------------------------------- |
| 1108 | # The following are methods that are called depending on the type of a |
| 1109 | # member. The entry point is _proc_member() which can be overridden in a |
| 1110 | # subclass to add custom _proc_*() methods. A _proc_*() method MUST |
| 1111 | # implement the following |
| 1112 | # operations: |
| 1113 | # 1. Set self.offset_data to the position where the data blocks begin, |
| 1114 | # if there is data that follows. |
| 1115 | # 2. Set tarfile.offset to the position where the next member's header will |
| 1116 | # begin. |
| 1117 | # 3. Return self or another valid TarInfo object. |
| 1118 | def _proc_member(self, tarfile): |
| 1119 | """Choose the right processing method depending on |
| 1120 | the type and call it. |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1121 | """ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1122 | if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): |
| 1123 | return self._proc_gnulong(tarfile) |
| 1124 | elif self.type == GNUTYPE_SPARSE: |
| 1125 | return self._proc_sparse(tarfile) |
| 1126 | elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE): |
| 1127 | return self._proc_pax(tarfile) |
| 1128 | else: |
| 1129 | return self._proc_builtin(tarfile) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1130 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1131 | def _proc_builtin(self, tarfile): |
| 1132 | """Process a builtin type or an unknown type which |
| 1133 | will be treated as a regular file. |
| 1134 | """ |
| 1135 | self.offset_data = tarfile.fileobj.tell() |
| 1136 | offset = self.offset_data |
| 1137 | if self.isreg() or self.type not in SUPPORTED_TYPES: |
| 1138 | # Skip the following data blocks. |
| 1139 | offset += self._block(self.size) |
| 1140 | tarfile.offset = offset |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1141 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1142 | # Patch the TarInfo object with saved global |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1143 | # header information. |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1144 | self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1145 | |
| 1146 | return self |
| 1147 | |
| 1148 | def _proc_gnulong(self, tarfile): |
| 1149 | """Process the blocks that hold a GNU longname |
| 1150 | or longlink member. |
| 1151 | """ |
| 1152 | buf = tarfile.fileobj.read(self._block(self.size)) |
| 1153 | |
| 1154 | # Fetch the next header and process it. |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1155 | try: |
| 1156 | next = self.fromtarfile(tarfile) |
| 1157 | except HeaderError: |
| 1158 | raise SubsequentHeaderError("missing or bad subsequent header") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1159 | |
| 1160 | # Patch the TarInfo object from the next header with |
| 1161 | # the longname information. |
| 1162 | next.offset = self.offset |
| 1163 | if self.type == GNUTYPE_LONGNAME: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1164 | next.name = nts(buf, tarfile.encoding, tarfile.errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1165 | elif self.type == GNUTYPE_LONGLINK: |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1166 | next.linkname = nts(buf, tarfile.encoding, tarfile.errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1167 | |
| 1168 | return next |
| 1169 | |
| 1170 | def _proc_sparse(self, tarfile): |
| 1171 | """Process a GNU sparse header plus extra headers. |
| 1172 | """ |
Lars Gustäbel | c2ea8c6 | 2008-04-14 10:05:48 +0000 | [diff] [blame] | 1173 | # We already collected some sparse structures in frombuf(). |
| 1174 | structs, isextended, origsize = self._sparse_structs |
| 1175 | del self._sparse_structs |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1176 | |
Lars Gustäbel | c2ea8c6 | 2008-04-14 10:05:48 +0000 | [diff] [blame] | 1177 | # Collect sparse structures from extended header blocks. |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1178 | while isextended: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1179 | buf = tarfile.fileobj.read(BLOCKSIZE) |
| 1180 | pos = 0 |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 1181 | for i in range(21): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1182 | try: |
| 1183 | offset = nti(buf[pos:pos + 12]) |
| 1184 | numbytes = nti(buf[pos + 12:pos + 24]) |
| 1185 | except ValueError: |
| 1186 | break |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 1187 | if offset and numbytes: |
| 1188 | structs.append((offset, numbytes)) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1189 | pos += 24 |
Lars Gustäbel | b506dc3 | 2007-08-07 18:36:16 +0000 | [diff] [blame] | 1190 | isextended = bool(buf[504]) |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 1191 | self.sparse = structs |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1192 | |
| 1193 | self.offset_data = tarfile.fileobj.tell() |
| 1194 | tarfile.offset = self.offset_data + self._block(self.size) |
| 1195 | self.size = origsize |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1196 | return self |
| 1197 | |
| 1198 | def _proc_pax(self, tarfile): |
| 1199 | """Process an extended or global header as described in |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1200 | POSIX.1-2008. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1201 | """ |
| 1202 | # Read the header information. |
| 1203 | buf = tarfile.fileobj.read(self._block(self.size)) |
| 1204 | |
| 1205 | # A pax header stores supplemental information for either |
| 1206 | # the following file (extended) or all following files |
| 1207 | # (global). |
| 1208 | if self.type == XGLTYPE: |
| 1209 | pax_headers = tarfile.pax_headers |
| 1210 | else: |
| 1211 | pax_headers = tarfile.pax_headers.copy() |
| 1212 | |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1213 | # Check if the pax header contains a hdrcharset field. This tells us |
| 1214 | # the encoding of the path, linkpath, uname and gname fields. Normally, |
| 1215 | # these fields are UTF-8 encoded but since POSIX.1-2008 tar |
| 1216 | # implementations are allowed to store them as raw binary strings if |
| 1217 | # the translation to UTF-8 fails. |
| 1218 | match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) |
| 1219 | if match is not None: |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1220 | pax_headers["hdrcharset"] = match.group(1).decode("utf-8") |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1221 | |
| 1222 | # For the time being, we don't care about anything other than "BINARY". |
| 1223 | # The only other value that is currently allowed by the standard is |
| 1224 | # "ISO-IR 10646 2000 UTF-8" in other words UTF-8. |
| 1225 | hdrcharset = pax_headers.get("hdrcharset") |
| 1226 | if hdrcharset == "BINARY": |
| 1227 | encoding = tarfile.encoding |
| 1228 | else: |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1229 | encoding = "utf-8" |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1230 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1231 | # Parse pax header information. A record looks like that: |
| 1232 | # "%d %s=%s\n" % (length, keyword, value). length is the size |
| 1233 | # of the complete record including the length field itself and |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1234 | # the newline. keyword and value are both UTF-8 encoded strings. |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 1235 | regex = re.compile(br"(\d+) ([^=]+)=") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1236 | pos = 0 |
| 1237 | while True: |
| 1238 | match = regex.match(buf, pos) |
| 1239 | if not match: |
| 1240 | break |
| 1241 | |
| 1242 | length, keyword = match.groups() |
| 1243 | length = int(length) |
| 1244 | value = buf[match.end(2) + 1:match.start(1) + length - 1] |
| 1245 | |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1246 | # Normally, we could just use "utf-8" as the encoding and "strict" |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1247 | # as the error handler, but we better not take the risk. For |
| 1248 | # example, GNU tar <= 1.23 is known to store filenames it cannot |
| 1249 | # translate to UTF-8 as raw strings (unfortunately without a |
| 1250 | # hdrcharset=BINARY header). |
| 1251 | # We first try the strict standard encoding, and if that fails we |
| 1252 | # fall back on the user's encoding and error handler. |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1253 | keyword = self._decode_pax_field(keyword, "utf-8", "utf-8", |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1254 | tarfile.errors) |
| 1255 | if keyword in PAX_NAME_FIELDS: |
| 1256 | value = self._decode_pax_field(value, encoding, tarfile.encoding, |
| 1257 | tarfile.errors) |
| 1258 | else: |
Marc-André Lemburg | 8f36af7 | 2011-02-25 15:42:01 +0000 | [diff] [blame] | 1259 | value = self._decode_pax_field(value, "utf-8", "utf-8", |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1260 | tarfile.errors) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1261 | |
| 1262 | pax_headers[keyword] = value |
| 1263 | pos += length |
| 1264 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1265 | # Fetch the next header. |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1266 | try: |
| 1267 | next = self.fromtarfile(tarfile) |
| 1268 | except HeaderError: |
| 1269 | raise SubsequentHeaderError("missing or bad subsequent header") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1270 | |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 1271 | # Process GNU sparse information. |
| 1272 | if "GNU.sparse.map" in pax_headers: |
| 1273 | # GNU extended sparse format version 0.1. |
| 1274 | self._proc_gnusparse_01(next, pax_headers) |
| 1275 | |
| 1276 | elif "GNU.sparse.size" in pax_headers: |
| 1277 | # GNU extended sparse format version 0.0. |
| 1278 | self._proc_gnusparse_00(next, pax_headers, buf) |
| 1279 | |
| 1280 | elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0": |
| 1281 | # GNU extended sparse format version 1.0. |
| 1282 | self._proc_gnusparse_10(next, pax_headers, tarfile) |
| 1283 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1284 | if self.type in (XHDTYPE, SOLARIS_XHDTYPE): |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1285 | # Patch the TarInfo object with the extended header info. |
| 1286 | next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors) |
| 1287 | next.offset = self.offset |
| 1288 | |
| 1289 | if "size" in pax_headers: |
| 1290 | # If the extended header replaces the size field, |
| 1291 | # we need to recalculate the offset where the next |
| 1292 | # header starts. |
| 1293 | offset = next.offset_data |
| 1294 | if next.isreg() or next.type not in SUPPORTED_TYPES: |
| 1295 | offset += next._block(next.size) |
| 1296 | tarfile.offset = offset |
| 1297 | |
| 1298 | return next |
| 1299 | |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 1300 | def _proc_gnusparse_00(self, next, pax_headers, buf): |
| 1301 | """Process a GNU tar extended sparse header, version 0.0. |
| 1302 | """ |
| 1303 | offsets = [] |
| 1304 | for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf): |
| 1305 | offsets.append(int(match.group(1))) |
| 1306 | numbytes = [] |
| 1307 | for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf): |
| 1308 | numbytes.append(int(match.group(1))) |
| 1309 | next.sparse = list(zip(offsets, numbytes)) |
| 1310 | |
| 1311 | def _proc_gnusparse_01(self, next, pax_headers): |
| 1312 | """Process a GNU tar extended sparse header, version 0.1. |
| 1313 | """ |
| 1314 | sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")] |
| 1315 | next.sparse = list(zip(sparse[::2], sparse[1::2])) |
| 1316 | |
| 1317 | def _proc_gnusparse_10(self, next, pax_headers, tarfile): |
| 1318 | """Process a GNU tar extended sparse header, version 1.0. |
| 1319 | """ |
| 1320 | fields = None |
| 1321 | sparse = [] |
| 1322 | buf = tarfile.fileobj.read(BLOCKSIZE) |
| 1323 | fields, buf = buf.split(b"\n", 1) |
| 1324 | fields = int(fields) |
| 1325 | while len(sparse) < fields * 2: |
| 1326 | if b"\n" not in buf: |
| 1327 | buf += tarfile.fileobj.read(BLOCKSIZE) |
| 1328 | number, buf = buf.split(b"\n", 1) |
| 1329 | sparse.append(int(number)) |
| 1330 | next.offset_data = tarfile.fileobj.tell() |
| 1331 | next.sparse = list(zip(sparse[::2], sparse[1::2])) |
| 1332 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1333 | def _apply_pax_info(self, pax_headers, encoding, errors): |
| 1334 | """Replace fields with supplemental information from a previous |
| 1335 | pax extended or global header. |
| 1336 | """ |
| 1337 | for keyword, value in pax_headers.items(): |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 1338 | if keyword == "GNU.sparse.name": |
| 1339 | setattr(self, "path", value) |
| 1340 | elif keyword == "GNU.sparse.size": |
| 1341 | setattr(self, "size", int(value)) |
| 1342 | elif keyword == "GNU.sparse.realsize": |
| 1343 | setattr(self, "size", int(value)) |
| 1344 | elif keyword in PAX_FIELDS: |
| 1345 | if keyword in PAX_NUMBER_FIELDS: |
| 1346 | try: |
| 1347 | value = PAX_NUMBER_FIELDS[keyword](value) |
| 1348 | except ValueError: |
| 1349 | value = 0 |
| 1350 | if keyword == "path": |
| 1351 | value = value.rstrip("/") |
| 1352 | setattr(self, keyword, value) |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1353 | |
| 1354 | self.pax_headers = pax_headers.copy() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1355 | |
Lars Gustäbel | 1465cc2 | 2010-05-17 18:02:50 +0000 | [diff] [blame] | 1356 | def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors): |
| 1357 | """Decode a single field from a pax record. |
| 1358 | """ |
| 1359 | try: |
| 1360 | return value.decode(encoding, "strict") |
| 1361 | except UnicodeDecodeError: |
| 1362 | return value.decode(fallback_encoding, fallback_errors) |
| 1363 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1364 | def _block(self, count): |
| 1365 | """Round up a byte count by BLOCKSIZE and return it, |
| 1366 | e.g. _block(834) => 1024. |
| 1367 | """ |
| 1368 | blocks, remainder = divmod(count, BLOCKSIZE) |
| 1369 | if remainder: |
| 1370 | blocks += 1 |
| 1371 | return blocks * BLOCKSIZE |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1372 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1373 | def isreg(self): |
| 1374 | return self.type in REGULAR_TYPES |
| 1375 | def isfile(self): |
| 1376 | return self.isreg() |
| 1377 | def isdir(self): |
| 1378 | return self.type == DIRTYPE |
| 1379 | def issym(self): |
| 1380 | return self.type == SYMTYPE |
| 1381 | def islnk(self): |
| 1382 | return self.type == LNKTYPE |
| 1383 | def ischr(self): |
| 1384 | return self.type == CHRTYPE |
| 1385 | def isblk(self): |
| 1386 | return self.type == BLKTYPE |
| 1387 | def isfifo(self): |
| 1388 | return self.type == FIFOTYPE |
| 1389 | def issparse(self): |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 1390 | return self.sparse is not None |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1391 | def isdev(self): |
| 1392 | return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE) |
| 1393 | # class TarInfo |
| 1394 | |
| 1395 | class TarFile(object): |
| 1396 | """The TarFile Class provides an interface to tar archives. |
| 1397 | """ |
| 1398 | |
| 1399 | debug = 0 # May be set from 0 (no msgs) to 3 (all msgs) |
| 1400 | |
| 1401 | dereference = False # If true, add content of linked file to the |
| 1402 | # tar file, else the link. |
| 1403 | |
| 1404 | ignore_zeros = False # If true, skips empty or invalid blocks and |
| 1405 | # continues processing. |
| 1406 | |
Lars Gustäbel | 365aff3 | 2009-12-13 11:42:29 +0000 | [diff] [blame] | 1407 | errorlevel = 1 # If 0, fatal errors only appear in debug |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1408 | # messages (if debug >= 0). If > 0, errors |
| 1409 | # are passed to the caller as exceptions. |
| 1410 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1411 | format = DEFAULT_FORMAT # The format to use when creating an archive. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1412 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1413 | encoding = ENCODING # Encoding for 8-bit character strings. |
| 1414 | |
| 1415 | errors = None # Error handler for unicode conversion. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1416 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1417 | tarinfo = TarInfo # The default TarInfo class to use. |
| 1418 | |
Lars Gustäbel | b062a2f | 2012-05-14 13:18:16 +0200 | [diff] [blame] | 1419 | fileobject = ExFileObject # The file-object for extractfile(). |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1420 | |
| 1421 | def __init__(self, name=None, mode="r", fileobj=None, format=None, |
| 1422 | tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, |
Victor Stinner | de629d4 | 2010-05-05 21:43:57 +0000 | [diff] [blame] | 1423 | errors="surrogateescape", pax_headers=None, debug=None, errorlevel=None): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1424 | """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to |
| 1425 | read from an existing archive, 'a' to append data to an existing |
| 1426 | file or 'w' to create a new file overwriting an existing one. `mode' |
| 1427 | defaults to 'r'. |
| 1428 | If `fileobj' is given, it is used for reading or writing data. If it |
| 1429 | can be determined, `mode' is overridden by `fileobj's mode. |
| 1430 | `fileobj' is not closed, when TarFile is closed. |
| 1431 | """ |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1432 | if len(mode) > 1 or mode not in "raw": |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1433 | raise ValueError("mode must be 'r', 'a' or 'w'") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1434 | self.mode = mode |
| 1435 | self._mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1436 | |
| 1437 | if not fileobj: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1438 | if self.mode == "a" and not os.path.exists(name): |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 1439 | # Create nonexistent files in append mode. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1440 | self.mode = "w" |
| 1441 | self._mode = "wb" |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1442 | fileobj = bltn_open(name, self._mode) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1443 | self._extfileobj = False |
| 1444 | else: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1445 | if name is None and hasattr(fileobj, "name"): |
| 1446 | name = fileobj.name |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1447 | if hasattr(fileobj, "mode"): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1448 | self._mode = fileobj.mode |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1449 | self._extfileobj = True |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 1450 | self.name = os.path.abspath(name) if name else None |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1451 | self.fileobj = fileobj |
| 1452 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1453 | # Init attributes. |
| 1454 | if format is not None: |
| 1455 | self.format = format |
| 1456 | if tarinfo is not None: |
| 1457 | self.tarinfo = tarinfo |
| 1458 | if dereference is not None: |
| 1459 | self.dereference = dereference |
| 1460 | if ignore_zeros is not None: |
| 1461 | self.ignore_zeros = ignore_zeros |
| 1462 | if encoding is not None: |
| 1463 | self.encoding = encoding |
Victor Stinner | de629d4 | 2010-05-05 21:43:57 +0000 | [diff] [blame] | 1464 | self.errors = errors |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1465 | |
| 1466 | if pax_headers is not None and self.format == PAX_FORMAT: |
| 1467 | self.pax_headers = pax_headers |
| 1468 | else: |
| 1469 | self.pax_headers = {} |
| 1470 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1471 | if debug is not None: |
| 1472 | self.debug = debug |
| 1473 | if errorlevel is not None: |
| 1474 | self.errorlevel = errorlevel |
| 1475 | |
| 1476 | # Init datastructures. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1477 | self.closed = False |
| 1478 | self.members = [] # list of members as TarInfo objects |
| 1479 | self._loaded = False # flag if all members have been read |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 1480 | self.offset = self.fileobj.tell() |
| 1481 | # current position in the archive file |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1482 | self.inodes = {} # dictionary caching the inodes of |
| 1483 | # archive members already added |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1484 | |
Lars Gustäbel | 7b46539 | 2009-11-18 20:29:25 +0000 | [diff] [blame] | 1485 | try: |
| 1486 | if self.mode == "r": |
| 1487 | self.firstmember = None |
| 1488 | self.firstmember = self.next() |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1489 | |
Lars Gustäbel | 7b46539 | 2009-11-18 20:29:25 +0000 | [diff] [blame] | 1490 | if self.mode == "a": |
| 1491 | # Move to the end of the archive, |
| 1492 | # before the first empty block. |
Lars Gustäbel | 7b46539 | 2009-11-18 20:29:25 +0000 | [diff] [blame] | 1493 | while True: |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1494 | self.fileobj.seek(self.offset) |
| 1495 | try: |
| 1496 | tarinfo = self.tarinfo.fromtarfile(self) |
| 1497 | self.members.append(tarinfo) |
| 1498 | except EOFHeaderError: |
| 1499 | self.fileobj.seek(self.offset) |
Lars Gustäbel | 7b46539 | 2009-11-18 20:29:25 +0000 | [diff] [blame] | 1500 | break |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1501 | except HeaderError as e: |
| 1502 | raise ReadError(str(e)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1503 | |
Lars Gustäbel | 7b46539 | 2009-11-18 20:29:25 +0000 | [diff] [blame] | 1504 | if self.mode in "aw": |
| 1505 | self._loaded = True |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1506 | |
Lars Gustäbel | 7b46539 | 2009-11-18 20:29:25 +0000 | [diff] [blame] | 1507 | if self.pax_headers: |
| 1508 | buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy()) |
| 1509 | self.fileobj.write(buf) |
| 1510 | self.offset += len(buf) |
| 1511 | except: |
| 1512 | if not self._extfileobj: |
| 1513 | self.fileobj.close() |
| 1514 | self.closed = True |
| 1515 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1516 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1517 | #-------------------------------------------------------------------------- |
| 1518 | # Below are the classmethods which act as alternate constructors to the |
| 1519 | # TarFile class. The open() method is the only one that is needed for |
| 1520 | # public use; it is the "super"-constructor and is able to select an |
| 1521 | # adequate "sub"-constructor for a particular compression using the mapping |
| 1522 | # from OPEN_METH. |
| 1523 | # |
| 1524 | # This concept allows one to subclass TarFile without losing the comfort of |
| 1525 | # the super-constructor. A sub-constructor is registered and made available |
| 1526 | # by adding it to the mapping in OPEN_METH. |
| 1527 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1528 | @classmethod |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1529 | def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1530 | """Open a tar archive for reading, writing or appending. Return |
| 1531 | an appropriate TarFile class. |
| 1532 | |
| 1533 | mode: |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1534 | 'r' or 'r:*' open for reading with transparent compression |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1535 | 'r:' open for reading exclusively uncompressed |
| 1536 | 'r:gz' open for reading with gzip compression |
| 1537 | 'r:bz2' open for reading with bzip2 compression |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1538 | 'r:xz' open for reading with lzma compression |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 1539 | 'a' or 'a:' open for appending, creating the file if necessary |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1540 | 'w' or 'w:' open for writing without compression |
| 1541 | 'w:gz' open for writing with gzip compression |
| 1542 | 'w:bz2' open for writing with bzip2 compression |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1543 | 'w:xz' open for writing with lzma compression |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1544 | |
| 1545 | 'r|*' open a stream of tar blocks with transparent compression |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1546 | 'r|' open an uncompressed stream of tar blocks for reading |
| 1547 | 'r|gz' open a gzip compressed stream of tar blocks |
| 1548 | 'r|bz2' open a bzip2 compressed stream of tar blocks |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1549 | 'r|xz' open an lzma compressed stream of tar blocks |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1550 | 'w|' open an uncompressed stream for writing |
| 1551 | 'w|gz' open a gzip compressed stream for writing |
| 1552 | 'w|bz2' open a bzip2 compressed stream for writing |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1553 | 'w|xz' open an lzma compressed stream for writing |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1554 | """ |
| 1555 | |
| 1556 | if not name and not fileobj: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1557 | raise ValueError("nothing to open") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1558 | |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1559 | if mode in ("r", "r:*"): |
| 1560 | # Find out which *open() is appropriate for opening the file. |
| 1561 | for comptype in cls.OPEN_METH: |
| 1562 | func = getattr(cls, cls.OPEN_METH[comptype]) |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1563 | if fileobj is not None: |
| 1564 | saved_pos = fileobj.tell() |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1565 | try: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1566 | return func(name, "r", fileobj, **kwargs) |
| 1567 | except (ReadError, CompressionError) as e: |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1568 | if fileobj is not None: |
| 1569 | fileobj.seek(saved_pos) |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1570 | continue |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1571 | raise ReadError("file could not be opened successfully") |
Martin v. Löwis | 78be7df | 2005-03-05 12:47:42 +0000 | [diff] [blame] | 1572 | |
| 1573 | elif ":" in mode: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1574 | filemode, comptype = mode.split(":", 1) |
| 1575 | filemode = filemode or "r" |
| 1576 | comptype = comptype or "tar" |
| 1577 | |
| 1578 | # Select the *open() function according to |
| 1579 | # given compression. |
| 1580 | if comptype in cls.OPEN_METH: |
| 1581 | func = getattr(cls, cls.OPEN_METH[comptype]) |
| 1582 | else: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1583 | raise CompressionError("unknown compression type %r" % comptype) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1584 | return func(name, filemode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1585 | |
| 1586 | elif "|" in mode: |
| 1587 | filemode, comptype = mode.split("|", 1) |
| 1588 | filemode = filemode or "r" |
| 1589 | comptype = comptype or "tar" |
| 1590 | |
| 1591 | if filemode not in "rw": |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1592 | raise ValueError("mode must be 'r' or 'w'") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1593 | |
Antoine Pitrou | 605c293 | 2010-09-23 20:15:14 +0000 | [diff] [blame] | 1594 | stream = _Stream(name, filemode, comptype, fileobj, bufsize) |
| 1595 | try: |
| 1596 | t = cls(name, filemode, stream, **kwargs) |
| 1597 | except: |
| 1598 | stream.close() |
| 1599 | raise |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1600 | t._extfileobj = False |
| 1601 | return t |
| 1602 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1603 | elif mode in "aw": |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1604 | return cls.taropen(name, mode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1605 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1606 | raise ValueError("undiscernible mode") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1607 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1608 | @classmethod |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1609 | def taropen(cls, name, mode="r", fileobj=None, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1610 | """Open uncompressed tar archive name for reading or writing. |
| 1611 | """ |
| 1612 | if len(mode) > 1 or mode not in "raw": |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1613 | raise ValueError("mode must be 'r', 'a' or 'w'") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1614 | return cls(name, mode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1615 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1616 | @classmethod |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1617 | def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1618 | """Open gzip compressed tar archive name for reading or writing. |
| 1619 | Appending is not allowed. |
| 1620 | """ |
| 1621 | if len(mode) > 1 or mode not in "rw": |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1622 | raise ValueError("mode must be 'r' or 'w'") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1623 | |
| 1624 | try: |
| 1625 | import gzip |
Neal Norwitz | 4ec6824 | 2003-04-11 03:05:56 +0000 | [diff] [blame] | 1626 | gzip.GzipFile |
| 1627 | except (ImportError, AttributeError): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1628 | raise CompressionError("gzip module is not available") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1629 | |
Antoine Pitrou | e1eca4e | 2010-10-29 23:49:49 +0000 | [diff] [blame] | 1630 | extfileobj = fileobj is not None |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1631 | try: |
Antoine Pitrou | e1eca4e | 2010-10-29 23:49:49 +0000 | [diff] [blame] | 1632 | fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj) |
| 1633 | t = cls.taropen(name, mode, fileobj, **kwargs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1634 | except IOError: |
Georg Brandl | 3abb372 | 2011-08-13 11:48:12 +0200 | [diff] [blame] | 1635 | if not extfileobj and fileobj is not None: |
Antoine Pitrou | 95f5560 | 2010-09-23 18:36:46 +0000 | [diff] [blame] | 1636 | fileobj.close() |
Georg Brandl | 3abb372 | 2011-08-13 11:48:12 +0200 | [diff] [blame] | 1637 | if fileobj is None: |
| 1638 | raise |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1639 | raise ReadError("not a gzip file") |
Antoine Pitrou | e1eca4e | 2010-10-29 23:49:49 +0000 | [diff] [blame] | 1640 | except: |
Georg Brandl | 3abb372 | 2011-08-13 11:48:12 +0200 | [diff] [blame] | 1641 | if not extfileobj and fileobj is not None: |
Antoine Pitrou | e1eca4e | 2010-10-29 23:49:49 +0000 | [diff] [blame] | 1642 | fileobj.close() |
| 1643 | raise |
Antoine Pitrou | 95f5560 | 2010-09-23 18:36:46 +0000 | [diff] [blame] | 1644 | t._extfileobj = extfileobj |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1645 | return t |
| 1646 | |
Guido van Rossum | 75b64e6 | 2005-01-16 00:16:11 +0000 | [diff] [blame] | 1647 | @classmethod |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1648 | def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1649 | """Open bzip2 compressed tar archive name for reading or writing. |
| 1650 | Appending is not allowed. |
| 1651 | """ |
| 1652 | if len(mode) > 1 or mode not in "rw": |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1653 | raise ValueError("mode must be 'r' or 'w'.") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1654 | |
| 1655 | try: |
| 1656 | import bz2 |
| 1657 | except ImportError: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1658 | raise CompressionError("bz2 module is not available") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1659 | |
Nadeem Vawda | aebcdba | 2012-06-04 23:31:20 +0200 | [diff] [blame] | 1660 | fileobj = bz2.BZ2File(fileobj or name, mode, |
| 1661 | compresslevel=compresslevel) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1662 | |
| 1663 | try: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1664 | t = cls.taropen(name, mode, fileobj, **kwargs) |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 1665 | except (IOError, EOFError): |
Antoine Pitrou | 95f5560 | 2010-09-23 18:36:46 +0000 | [diff] [blame] | 1666 | fileobj.close() |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1667 | raise ReadError("not a bzip2 file") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1668 | t._extfileobj = False |
| 1669 | return t |
| 1670 | |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1671 | @classmethod |
Lars Gustäbel | c5e1199 | 2012-01-18 14:01:17 +0100 | [diff] [blame] | 1672 | def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs): |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1673 | """Open lzma compressed tar archive name for reading or writing. |
| 1674 | Appending is not allowed. |
| 1675 | """ |
| 1676 | if mode not in ("r", "w"): |
| 1677 | raise ValueError("mode must be 'r' or 'w'") |
| 1678 | |
| 1679 | try: |
| 1680 | import lzma |
| 1681 | except ImportError: |
| 1682 | raise CompressionError("lzma module is not available") |
| 1683 | |
Nadeem Vawda | 33c34da | 2012-06-04 23:34:07 +0200 | [diff] [blame] | 1684 | fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset) |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1685 | |
| 1686 | try: |
| 1687 | t = cls.taropen(name, mode, fileobj, **kwargs) |
| 1688 | except (lzma.LZMAError, EOFError): |
| 1689 | fileobj.close() |
| 1690 | raise ReadError("not an lzma file") |
| 1691 | t._extfileobj = False |
| 1692 | return t |
| 1693 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1694 | # All *open() methods are registered here. |
| 1695 | OPEN_METH = { |
| 1696 | "tar": "taropen", # uncompressed tar |
| 1697 | "gz": "gzopen", # gzip compressed tar |
Lars Gustäbel | 0a9dd2f | 2011-12-10 20:38:14 +0100 | [diff] [blame] | 1698 | "bz2": "bz2open", # bzip2 compressed tar |
| 1699 | "xz": "xzopen" # lzma compressed tar |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1700 | } |
| 1701 | |
| 1702 | #-------------------------------------------------------------------------- |
| 1703 | # The public methods which TarFile provides: |
| 1704 | |
| 1705 | def close(self): |
| 1706 | """Close the TarFile. In write-mode, two finishing zero blocks are |
| 1707 | appended to the archive. |
| 1708 | """ |
| 1709 | if self.closed: |
| 1710 | return |
| 1711 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1712 | if self.mode in "aw": |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1713 | self.fileobj.write(NUL * (BLOCKSIZE * 2)) |
| 1714 | self.offset += (BLOCKSIZE * 2) |
| 1715 | # fill up the end with zero-blocks |
| 1716 | # (like option -b20 for tar does) |
| 1717 | blocks, remainder = divmod(self.offset, RECORDSIZE) |
| 1718 | if remainder > 0: |
| 1719 | self.fileobj.write(NUL * (RECORDSIZE - remainder)) |
| 1720 | |
| 1721 | if not self._extfileobj: |
| 1722 | self.fileobj.close() |
| 1723 | self.closed = True |
| 1724 | |
| 1725 | def getmember(self, name): |
| 1726 | """Return a TarInfo object for member `name'. If `name' can not be |
| 1727 | found in the archive, KeyError is raised. If a member occurs more |
Mark Dickinson | 934896d | 2009-02-21 20:59:32 +0000 | [diff] [blame] | 1728 | than once in the archive, its last occurrence is assumed to be the |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1729 | most up-to-date version. |
| 1730 | """ |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 1731 | tarinfo = self._getmember(name) |
| 1732 | if tarinfo is None: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 1733 | raise KeyError("filename %r not found" % name) |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 1734 | return tarinfo |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1735 | |
| 1736 | def getmembers(self): |
| 1737 | """Return the members of the archive as a list of TarInfo objects. The |
| 1738 | list has the same order as the members in the archive. |
| 1739 | """ |
| 1740 | self._check() |
| 1741 | if not self._loaded: # if we want to obtain a list of |
| 1742 | self._load() # all members, we first have to |
| 1743 | # scan the whole archive. |
| 1744 | return self.members |
| 1745 | |
| 1746 | def getnames(self): |
| 1747 | """Return the members of the archive as a list of their names. It has |
| 1748 | the same order as the list returned by getmembers(). |
| 1749 | """ |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 1750 | return [tarinfo.name for tarinfo in self.getmembers()] |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1751 | |
| 1752 | def gettarinfo(self, name=None, arcname=None, fileobj=None): |
| 1753 | """Create a TarInfo object for either the file `name' or the file |
| 1754 | object `fileobj' (using os.fstat on its file descriptor). You can |
| 1755 | modify some of the TarInfo's attributes before you add it using |
| 1756 | addfile(). If given, `arcname' specifies an alternative name for the |
| 1757 | file in the archive. |
| 1758 | """ |
| 1759 | self._check("aw") |
| 1760 | |
| 1761 | # When fileobj is given, replace name by |
| 1762 | # fileobj's real name. |
| 1763 | if fileobj is not None: |
| 1764 | name = fileobj.name |
| 1765 | |
| 1766 | # Building the name of the member in the archive. |
| 1767 | # Backward slashes are converted to forward slashes, |
| 1768 | # Absolute paths are turned to relative paths. |
| 1769 | if arcname is None: |
| 1770 | arcname = name |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1771 | drv, arcname = os.path.splitdrive(arcname) |
Lars Gustäbel | bfdfdda | 2009-08-28 19:59:59 +0000 | [diff] [blame] | 1772 | arcname = arcname.replace(os.sep, "/") |
| 1773 | arcname = arcname.lstrip("/") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1774 | |
| 1775 | # Now, fill the TarInfo object with |
| 1776 | # information specific for the file. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1777 | tarinfo = self.tarinfo() |
| 1778 | tarinfo.tarfile = self |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1779 | |
| 1780 | # Use os.stat or os.lstat, depending on platform |
| 1781 | # and if symlinks shall be resolved. |
| 1782 | if fileobj is None: |
| 1783 | if hasattr(os, "lstat") and not self.dereference: |
| 1784 | statres = os.lstat(name) |
| 1785 | else: |
| 1786 | statres = os.stat(name) |
| 1787 | else: |
| 1788 | statres = os.fstat(fileobj.fileno()) |
| 1789 | linkname = "" |
| 1790 | |
| 1791 | stmd = statres.st_mode |
| 1792 | if stat.S_ISREG(stmd): |
| 1793 | inode = (statres.st_ino, statres.st_dev) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1794 | if not self.dereference and statres.st_nlink > 1 and \ |
| 1795 | inode in self.inodes and arcname != self.inodes[inode]: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1796 | # Is it a hardlink to an already |
| 1797 | # archived file? |
| 1798 | type = LNKTYPE |
| 1799 | linkname = self.inodes[inode] |
| 1800 | else: |
| 1801 | # The inode is added only if its valid. |
| 1802 | # For win32 it is always 0. |
| 1803 | type = REGTYPE |
| 1804 | if inode[0]: |
| 1805 | self.inodes[inode] = arcname |
| 1806 | elif stat.S_ISDIR(stmd): |
| 1807 | type = DIRTYPE |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1808 | elif stat.S_ISFIFO(stmd): |
| 1809 | type = FIFOTYPE |
| 1810 | elif stat.S_ISLNK(stmd): |
| 1811 | type = SYMTYPE |
| 1812 | linkname = os.readlink(name) |
| 1813 | elif stat.S_ISCHR(stmd): |
| 1814 | type = CHRTYPE |
| 1815 | elif stat.S_ISBLK(stmd): |
| 1816 | type = BLKTYPE |
| 1817 | else: |
| 1818 | return None |
| 1819 | |
| 1820 | # Fill the TarInfo object with all |
| 1821 | # information we can get. |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1822 | tarinfo.name = arcname |
| 1823 | tarinfo.mode = stmd |
| 1824 | tarinfo.uid = statres.st_uid |
| 1825 | tarinfo.gid = statres.st_gid |
Lars Gustäbel | 2470ff1 | 2010-06-03 10:11:52 +0000 | [diff] [blame] | 1826 | if type == REGTYPE: |
Martin v. Löwis | 61d77e0 | 2004-08-20 06:35:46 +0000 | [diff] [blame] | 1827 | tarinfo.size = statres.st_size |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1828 | else: |
Guido van Rossum | e2a383d | 2007-01-15 16:59:06 +0000 | [diff] [blame] | 1829 | tarinfo.size = 0 |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1830 | tarinfo.mtime = statres.st_mtime |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1831 | tarinfo.type = type |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1832 | tarinfo.linkname = linkname |
| 1833 | if pwd: |
| 1834 | try: |
| 1835 | tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0] |
| 1836 | except KeyError: |
| 1837 | pass |
| 1838 | if grp: |
| 1839 | try: |
| 1840 | tarinfo.gname = grp.getgrgid(tarinfo.gid)[0] |
| 1841 | except KeyError: |
| 1842 | pass |
| 1843 | |
| 1844 | if type in (CHRTYPE, BLKTYPE): |
| 1845 | if hasattr(os, "major") and hasattr(os, "minor"): |
| 1846 | tarinfo.devmajor = os.major(statres.st_rdev) |
| 1847 | tarinfo.devminor = os.minor(statres.st_rdev) |
| 1848 | return tarinfo |
| 1849 | |
| 1850 | def list(self, verbose=True): |
| 1851 | """Print a table of contents to sys.stdout. If `verbose' is False, only |
| 1852 | the names of the members are printed. If it is True, an `ls -l'-like |
| 1853 | output is produced. |
| 1854 | """ |
| 1855 | self._check() |
| 1856 | |
| 1857 | for tarinfo in self: |
| 1858 | if verbose: |
Giampaolo Rodola' | ffa1d0b | 2012-05-15 15:30:25 +0200 | [diff] [blame] | 1859 | print(stat.filemode(tarinfo.mode), end=' ') |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1860 | print("%s/%s" % (tarinfo.uname or tarinfo.uid, |
| 1861 | tarinfo.gname or tarinfo.gid), end=' ') |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1862 | if tarinfo.ischr() or tarinfo.isblk(): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1863 | print("%10s" % ("%d,%d" \ |
| 1864 | % (tarinfo.devmajor, tarinfo.devminor)), end=' ') |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1865 | else: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1866 | print("%10d" % tarinfo.size, end=' ') |
| 1867 | print("%d-%02d-%02d %02d:%02d:%02d" \ |
| 1868 | % time.localtime(tarinfo.mtime)[:6], end=' ') |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1869 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1870 | print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ') |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1871 | |
| 1872 | if verbose: |
| 1873 | if tarinfo.issym(): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1874 | print("->", tarinfo.linkname, end=' ') |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1875 | if tarinfo.islnk(): |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 1876 | print("link to", tarinfo.linkname, end=' ') |
| 1877 | print() |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1878 | |
Raymond Hettinger | a63a312 | 2011-01-26 20:34:14 +0000 | [diff] [blame] | 1879 | def add(self, name, arcname=None, recursive=True, exclude=None, *, filter=None): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1880 | """Add the file `name' to the archive. `name' may be any type of file |
| 1881 | (directory, fifo, symbolic link, etc.). If given, `arcname' |
| 1882 | specifies an alternative name for the file in the archive. |
| 1883 | Directories are added recursively by default. This can be avoided by |
Guido van Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 1884 | setting `recursive' to False. `exclude' is a function that should |
Lars Gustäbel | 049d2aa | 2009-09-12 10:44:00 +0000 | [diff] [blame] | 1885 | return True for each filename to be excluded. `filter' is a function |
| 1886 | that expects a TarInfo object argument and returns the changed |
| 1887 | TarInfo object, if it returns None the TarInfo object will be |
| 1888 | excluded from the archive. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1889 | """ |
| 1890 | self._check("aw") |
| 1891 | |
| 1892 | if arcname is None: |
| 1893 | arcname = name |
| 1894 | |
Guido van Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 1895 | # Exclude pathnames. |
Lars Gustäbel | 049d2aa | 2009-09-12 10:44:00 +0000 | [diff] [blame] | 1896 | if exclude is not None: |
| 1897 | import warnings |
| 1898 | warnings.warn("use the filter argument instead", |
| 1899 | DeprecationWarning, 2) |
| 1900 | if exclude(name): |
| 1901 | self._dbg(2, "tarfile: Excluded %r" % name) |
| 1902 | return |
Guido van Rossum | 486364b | 2007-06-30 05:01:58 +0000 | [diff] [blame] | 1903 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1904 | # Skip if somebody tries to archive the archive... |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 1905 | if self.name is not None and os.path.abspath(name) == self.name: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1906 | self._dbg(2, "tarfile: Skipped %r" % name) |
| 1907 | return |
| 1908 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1909 | self._dbg(1, name) |
| 1910 | |
| 1911 | # Create a TarInfo object from the file. |
| 1912 | tarinfo = self.gettarinfo(name, arcname) |
| 1913 | |
| 1914 | if tarinfo is None: |
| 1915 | self._dbg(1, "tarfile: Unsupported type %r" % name) |
| 1916 | return |
| 1917 | |
Lars Gustäbel | 049d2aa | 2009-09-12 10:44:00 +0000 | [diff] [blame] | 1918 | # Change or exclude the TarInfo object. |
| 1919 | if filter is not None: |
| 1920 | tarinfo = filter(tarinfo) |
| 1921 | if tarinfo is None: |
| 1922 | self._dbg(2, "tarfile: Excluded %r" % name) |
| 1923 | return |
| 1924 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1925 | # Append the tar header and data to the archive. |
| 1926 | if tarinfo.isreg(): |
Andrew Svetlov | 718df1d | 2012-11-29 14:20:47 +0200 | [diff] [blame] | 1927 | with bltn_open(name, "rb") as f: |
| 1928 | self.addfile(tarinfo, f) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1929 | |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1930 | elif tarinfo.isdir(): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1931 | self.addfile(tarinfo) |
| 1932 | if recursive: |
| 1933 | for f in os.listdir(name): |
Lars Gustäbel | 049d2aa | 2009-09-12 10:44:00 +0000 | [diff] [blame] | 1934 | self.add(os.path.join(name, f), os.path.join(arcname, f), |
Raymond Hettinger | a63a312 | 2011-01-26 20:34:14 +0000 | [diff] [blame] | 1935 | recursive, exclude, filter=filter) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1936 | |
Martin v. Löwis | 5dbdc59 | 2005-08-27 10:07:56 +0000 | [diff] [blame] | 1937 | else: |
| 1938 | self.addfile(tarinfo) |
| 1939 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1940 | def addfile(self, tarinfo, fileobj=None): |
| 1941 | """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is |
| 1942 | given, tarinfo.size bytes are read from it and added to the archive. |
| 1943 | You can create TarInfo objects using gettarinfo(). |
| 1944 | On Windows platforms, `fileobj' should always be opened with mode |
| 1945 | 'rb' to avoid irritation about the file size. |
| 1946 | """ |
| 1947 | self._check("aw") |
| 1948 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1949 | tarinfo = copy.copy(tarinfo) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1950 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 1951 | buf = tarinfo.tobuf(self.format, self.encoding, self.errors) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 1952 | self.fileobj.write(buf) |
| 1953 | self.offset += len(buf) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1954 | |
| 1955 | # If there's data to follow, append it. |
| 1956 | if fileobj is not None: |
| 1957 | copyfileobj(fileobj, self.fileobj, tarinfo.size) |
| 1958 | blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) |
| 1959 | if remainder > 0: |
| 1960 | self.fileobj.write(NUL * (BLOCKSIZE - remainder)) |
| 1961 | blocks += 1 |
| 1962 | self.offset += blocks * BLOCKSIZE |
| 1963 | |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 1964 | self.members.append(tarinfo) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 1965 | |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 1966 | def extractall(self, path=".", members=None): |
| 1967 | """Extract all members from the archive to the current working |
| 1968 | directory and set owner, modification time and permissions on |
| 1969 | directories afterwards. `path' specifies a different directory |
| 1970 | to extract to. `members' is optional and must be a subset of the |
| 1971 | list returned by getmembers(). |
| 1972 | """ |
| 1973 | directories = [] |
| 1974 | |
| 1975 | if members is None: |
| 1976 | members = self |
| 1977 | |
| 1978 | for tarinfo in members: |
| 1979 | if tarinfo.isdir(): |
Christian Heimes | 2202f87 | 2008-02-06 14:31:34 +0000 | [diff] [blame] | 1980 | # Extract directories with a safe mode. |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 1981 | directories.append(tarinfo) |
Christian Heimes | 2202f87 | 2008-02-06 14:31:34 +0000 | [diff] [blame] | 1982 | tarinfo = copy.copy(tarinfo) |
| 1983 | tarinfo.mode = 0o700 |
Martin v. Löwis | 16f344d | 2010-11-01 21:39:13 +0000 | [diff] [blame] | 1984 | # Do not set_attrs directories, as we will do that further down |
| 1985 | self.extract(tarinfo, path, set_attrs=not tarinfo.isdir()) |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 1986 | |
| 1987 | # Reverse sort directories. |
Raymond Hettinger | d4cb56d | 2008-01-30 02:55:10 +0000 | [diff] [blame] | 1988 | directories.sort(key=lambda a: a.name) |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 1989 | directories.reverse() |
| 1990 | |
| 1991 | # Set correct owner, mtime and filemode on directories. |
| 1992 | for tarinfo in directories: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1993 | dirpath = os.path.join(path, tarinfo.name) |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 1994 | try: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1995 | self.chown(tarinfo, dirpath) |
| 1996 | self.utime(tarinfo, dirpath) |
| 1997 | self.chmod(tarinfo, dirpath) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 1998 | except ExtractError as e: |
Martin v. Löwis | 00a73e7 | 2005-03-04 19:40:34 +0000 | [diff] [blame] | 1999 | if self.errorlevel > 1: |
| 2000 | raise |
| 2001 | else: |
| 2002 | self._dbg(1, "tarfile: %s" % e) |
| 2003 | |
Martin v. Löwis | 16f344d | 2010-11-01 21:39:13 +0000 | [diff] [blame] | 2004 | def extract(self, member, path="", set_attrs=True): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2005 | """Extract a member from the archive to the current working directory, |
| 2006 | using its full name. Its file information is extracted as accurately |
| 2007 | as possible. `member' may be a filename or a TarInfo object. You can |
Martin v. Löwis | 16f344d | 2010-11-01 21:39:13 +0000 | [diff] [blame] | 2008 | specify a different directory using `path'. File attributes (owner, |
| 2009 | mtime, mode) are set unless `set_attrs' is False. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2010 | """ |
| 2011 | self._check("r") |
| 2012 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 2013 | if isinstance(member, str): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2014 | tarinfo = self.getmember(member) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2015 | else: |
| 2016 | tarinfo = member |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2017 | |
Neal Norwitz | a4f651a | 2004-07-20 22:07:44 +0000 | [diff] [blame] | 2018 | # Prepare the link target for makelink(). |
| 2019 | if tarinfo.islnk(): |
| 2020 | tarinfo._link_target = os.path.join(path, tarinfo.linkname) |
| 2021 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2022 | try: |
Martin v. Löwis | 16f344d | 2010-11-01 21:39:13 +0000 | [diff] [blame] | 2023 | self._extract_member(tarinfo, os.path.join(path, tarinfo.name), |
| 2024 | set_attrs=set_attrs) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 2025 | except EnvironmentError as e: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2026 | if self.errorlevel > 0: |
| 2027 | raise |
| 2028 | else: |
| 2029 | if e.filename is None: |
| 2030 | self._dbg(1, "tarfile: %s" % e.strerror) |
| 2031 | else: |
| 2032 | self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 2033 | except ExtractError as e: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2034 | if self.errorlevel > 1: |
| 2035 | raise |
| 2036 | else: |
| 2037 | self._dbg(1, "tarfile: %s" % e) |
| 2038 | |
| 2039 | def extractfile(self, member): |
| 2040 | """Extract a member from the archive as a file object. `member' may be |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 2041 | a filename or a TarInfo object. If `member' is a regular file or a |
| 2042 | link, an io.BufferedReader object is returned. Otherwise, None is |
| 2043 | returned. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2044 | """ |
| 2045 | self._check("r") |
| 2046 | |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 2047 | if isinstance(member, str): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2048 | tarinfo = self.getmember(member) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2049 | else: |
| 2050 | tarinfo = member |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2051 | |
Lars Gustäbel | 7a919e9 | 2012-05-05 18:15:03 +0200 | [diff] [blame] | 2052 | if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES: |
| 2053 | # Members with unknown types are treated as regular files. |
Lars Gustäbel | b062a2f | 2012-05-14 13:18:16 +0200 | [diff] [blame] | 2054 | return self.fileobject(self, tarinfo) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2055 | |
| 2056 | elif tarinfo.islnk() or tarinfo.issym(): |
| 2057 | if isinstance(self.fileobj, _Stream): |
| 2058 | # A small but ugly workaround for the case that someone tries |
| 2059 | # to extract a (sym)link as a file-object from a non-seekable |
| 2060 | # stream of tar blocks. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2061 | raise StreamError("cannot extract (sym)link as file object") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2062 | else: |
Georg Brandl | 7eb4b7d | 2005-07-22 21:49:32 +0000 | [diff] [blame] | 2063 | # A (sym)link's file object is its target's file object. |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2064 | return self.extractfile(self._find_link_target(tarinfo)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2065 | else: |
| 2066 | # If there's no data associated with the member (directory, chrdev, |
| 2067 | # blkdev, etc.), return None instead of a file object. |
| 2068 | return None |
| 2069 | |
Martin v. Löwis | 16f344d | 2010-11-01 21:39:13 +0000 | [diff] [blame] | 2070 | def _extract_member(self, tarinfo, targetpath, set_attrs=True): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2071 | """Extract the TarInfo object tarinfo to a physical |
| 2072 | file called targetpath. |
| 2073 | """ |
| 2074 | # Fetch the TarInfo object for the given name |
| 2075 | # and build the destination pathname, replacing |
| 2076 | # forward slashes to platform specific separators. |
Lars Gustäbel | bfdfdda | 2009-08-28 19:59:59 +0000 | [diff] [blame] | 2077 | targetpath = targetpath.rstrip("/") |
| 2078 | targetpath = targetpath.replace("/", os.sep) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2079 | |
| 2080 | # Create all upper directories. |
| 2081 | upperdirs = os.path.dirname(targetpath) |
| 2082 | if upperdirs and not os.path.exists(upperdirs): |
Christian Heimes | 2202f87 | 2008-02-06 14:31:34 +0000 | [diff] [blame] | 2083 | # Create directories that are not part of the archive with |
| 2084 | # default permissions. |
Thomas Wouters | b213704 | 2007-02-01 18:02:27 +0000 | [diff] [blame] | 2085 | os.makedirs(upperdirs) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2086 | |
| 2087 | if tarinfo.islnk() or tarinfo.issym(): |
| 2088 | self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname)) |
| 2089 | else: |
| 2090 | self._dbg(1, tarinfo.name) |
| 2091 | |
| 2092 | if tarinfo.isreg(): |
| 2093 | self.makefile(tarinfo, targetpath) |
| 2094 | elif tarinfo.isdir(): |
| 2095 | self.makedir(tarinfo, targetpath) |
| 2096 | elif tarinfo.isfifo(): |
| 2097 | self.makefifo(tarinfo, targetpath) |
| 2098 | elif tarinfo.ischr() or tarinfo.isblk(): |
| 2099 | self.makedev(tarinfo, targetpath) |
| 2100 | elif tarinfo.islnk() or tarinfo.issym(): |
| 2101 | self.makelink(tarinfo, targetpath) |
| 2102 | elif tarinfo.type not in SUPPORTED_TYPES: |
| 2103 | self.makeunknown(tarinfo, targetpath) |
| 2104 | else: |
| 2105 | self.makefile(tarinfo, targetpath) |
| 2106 | |
Martin v. Löwis | 16f344d | 2010-11-01 21:39:13 +0000 | [diff] [blame] | 2107 | if set_attrs: |
| 2108 | self.chown(tarinfo, targetpath) |
| 2109 | if not tarinfo.issym(): |
| 2110 | self.chmod(tarinfo, targetpath) |
| 2111 | self.utime(tarinfo, targetpath) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2112 | |
| 2113 | #-------------------------------------------------------------------------- |
| 2114 | # Below are the different file methods. They are called via |
| 2115 | # _extract_member() when extract() is called. They can be replaced in a |
| 2116 | # subclass to implement other functionality. |
| 2117 | |
| 2118 | def makedir(self, tarinfo, targetpath): |
| 2119 | """Make a directory called targetpath. |
| 2120 | """ |
| 2121 | try: |
Christian Heimes | 2202f87 | 2008-02-06 14:31:34 +0000 | [diff] [blame] | 2122 | # Use a safe mode for the directory, the real mode is set |
| 2123 | # later in _extract_member(). |
| 2124 | os.mkdir(targetpath, 0o700) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 2125 | except FileExistsError: |
| 2126 | pass |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2127 | |
| 2128 | def makefile(self, tarinfo, targetpath): |
| 2129 | """Make a file called targetpath. |
| 2130 | """ |
Lars Gustäbel | 9cbdd75 | 2010-10-29 09:08:19 +0000 | [diff] [blame] | 2131 | source = self.fileobj |
| 2132 | source.seek(tarinfo.offset_data) |
Andrew Svetlov | 718df1d | 2012-11-29 14:20:47 +0200 | [diff] [blame] | 2133 | with bltn_open(targetpath, "wb") as target: |
| 2134 | if tarinfo.sparse is not None: |
| 2135 | for offset, size in tarinfo.sparse: |
| 2136 | target.seek(offset) |
| 2137 | copyfileobj(source, target, size) |
| 2138 | else: |
| 2139 | copyfileobj(source, target, tarinfo.size) |
| 2140 | target.seek(tarinfo.size) |
| 2141 | target.truncate() |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2142 | |
| 2143 | def makeunknown(self, tarinfo, targetpath): |
| 2144 | """Make a file from a TarInfo object with an unknown type |
| 2145 | at targetpath. |
| 2146 | """ |
| 2147 | self.makefile(tarinfo, targetpath) |
| 2148 | self._dbg(1, "tarfile: Unknown file type %r, " \ |
| 2149 | "extracted as regular file." % tarinfo.type) |
| 2150 | |
| 2151 | def makefifo(self, tarinfo, targetpath): |
| 2152 | """Make a fifo called targetpath. |
| 2153 | """ |
| 2154 | if hasattr(os, "mkfifo"): |
| 2155 | os.mkfifo(targetpath) |
| 2156 | else: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2157 | raise ExtractError("fifo not supported by system") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2158 | |
| 2159 | def makedev(self, tarinfo, targetpath): |
| 2160 | """Make a character or block device called targetpath. |
| 2161 | """ |
| 2162 | if not hasattr(os, "mknod") or not hasattr(os, "makedev"): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2163 | raise ExtractError("special devices not supported by system") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2164 | |
| 2165 | mode = tarinfo.mode |
| 2166 | if tarinfo.isblk(): |
| 2167 | mode |= stat.S_IFBLK |
| 2168 | else: |
| 2169 | mode |= stat.S_IFCHR |
| 2170 | |
| 2171 | os.mknod(targetpath, mode, |
| 2172 | os.makedev(tarinfo.devmajor, tarinfo.devminor)) |
| 2173 | |
| 2174 | def makelink(self, tarinfo, targetpath): |
| 2175 | """Make a (symbolic) link called targetpath. If it cannot be created |
| 2176 | (platform limitation), we try to make a copy of the referenced file |
| 2177 | instead of a link. |
| 2178 | """ |
Brian Curtin | d40e6f7 | 2010-07-08 21:39:08 +0000 | [diff] [blame] | 2179 | try: |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2180 | # For systems that support symbolic and hard links. |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2181 | if tarinfo.issym(): |
Lars Gustäbel | bfdfdda | 2009-08-28 19:59:59 +0000 | [diff] [blame] | 2182 | os.symlink(tarinfo.linkname, targetpath) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2183 | else: |
Neal Norwitz | a4f651a | 2004-07-20 22:07:44 +0000 | [diff] [blame] | 2184 | # See extract(). |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2185 | if os.path.exists(tarinfo._link_target): |
| 2186 | os.link(tarinfo._link_target, targetpath) |
| 2187 | else: |
Brian Curtin | 82df53e | 2010-09-24 21:04:05 +0000 | [diff] [blame] | 2188 | self._extract_member(self._find_link_target(tarinfo), |
| 2189 | targetpath) |
Brian Curtin | 16633fa | 2010-07-09 13:54:27 +0000 | [diff] [blame] | 2190 | except symlink_exception: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2191 | try: |
Brian Curtin | 16633fa | 2010-07-09 13:54:27 +0000 | [diff] [blame] | 2192 | self._extract_member(self._find_link_target(tarinfo), |
| 2193 | targetpath) |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2194 | except KeyError: |
| 2195 | raise ExtractError("unable to resolve link inside archive") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2196 | |
| 2197 | def chown(self, tarinfo, targetpath): |
| 2198 | """Set owner of targetpath according to tarinfo. |
| 2199 | """ |
| 2200 | if pwd and hasattr(os, "geteuid") and os.geteuid() == 0: |
| 2201 | # We have to be root to do so. |
| 2202 | try: |
| 2203 | g = grp.getgrnam(tarinfo.gname)[2] |
| 2204 | except KeyError: |
Lars Gustäbel | 2e7ddd3 | 2011-09-05 16:58:14 +0200 | [diff] [blame] | 2205 | g = tarinfo.gid |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2206 | try: |
| 2207 | u = pwd.getpwnam(tarinfo.uname)[2] |
| 2208 | except KeyError: |
Lars Gustäbel | 2e7ddd3 | 2011-09-05 16:58:14 +0200 | [diff] [blame] | 2209 | u = tarinfo.uid |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2210 | try: |
| 2211 | if tarinfo.issym() and hasattr(os, "lchown"): |
| 2212 | os.lchown(targetpath, u, g) |
| 2213 | else: |
Andrew MacIntyre | 7970d20 | 2003-02-19 12:51:34 +0000 | [diff] [blame] | 2214 | if sys.platform != "os2emx": |
| 2215 | os.chown(targetpath, u, g) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 2216 | except EnvironmentError as e: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2217 | raise ExtractError("could not change owner") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2218 | |
| 2219 | def chmod(self, tarinfo, targetpath): |
| 2220 | """Set file permissions of targetpath according to tarinfo. |
| 2221 | """ |
Jack Jansen | 834eff6 | 2003-03-07 12:47:06 +0000 | [diff] [blame] | 2222 | if hasattr(os, 'chmod'): |
| 2223 | try: |
| 2224 | os.chmod(targetpath, tarinfo.mode) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 2225 | except EnvironmentError as e: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2226 | raise ExtractError("could not change mode") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2227 | |
| 2228 | def utime(self, tarinfo, targetpath): |
| 2229 | """Set modification time of targetpath according to tarinfo. |
| 2230 | """ |
Jack Jansen | 834eff6 | 2003-03-07 12:47:06 +0000 | [diff] [blame] | 2231 | if not hasattr(os, 'utime'): |
Tim Peters | f934778 | 2003-03-07 15:36:41 +0000 | [diff] [blame] | 2232 | return |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2233 | try: |
| 2234 | os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 2235 | except EnvironmentError as e: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2236 | raise ExtractError("could not change modification time") |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2237 | |
| 2238 | #-------------------------------------------------------------------------- |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2239 | def next(self): |
| 2240 | """Return the next member of the archive as a TarInfo object, when |
| 2241 | TarFile is opened for reading. Return None if there is no more |
| 2242 | available. |
| 2243 | """ |
| 2244 | self._check("ra") |
| 2245 | if self.firstmember is not None: |
| 2246 | m = self.firstmember |
| 2247 | self.firstmember = None |
| 2248 | return m |
| 2249 | |
| 2250 | # Read the next block. |
Andrew M. Kuchling | 864bba1 | 2004-07-10 22:02:11 +0000 | [diff] [blame] | 2251 | self.fileobj.seek(self.offset) |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 2252 | tarinfo = None |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2253 | while True: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2254 | try: |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2255 | tarinfo = self.tarinfo.fromtarfile(self) |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 2256 | except EOFHeaderError as e: |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2257 | if self.ignore_zeros: |
Thomas Wouters | 902d6eb | 2007-01-09 23:18:33 +0000 | [diff] [blame] | 2258 | self._dbg(2, "0x%X: %s" % (self.offset, e)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2259 | self.offset += BLOCKSIZE |
| 2260 | continue |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 2261 | except InvalidHeaderError as e: |
| 2262 | if self.ignore_zeros: |
| 2263 | self._dbg(2, "0x%X: %s" % (self.offset, e)) |
| 2264 | self.offset += BLOCKSIZE |
| 2265 | continue |
| 2266 | elif self.offset == 0: |
| 2267 | raise ReadError(str(e)) |
| 2268 | except EmptyHeaderError: |
| 2269 | if self.offset == 0: |
| 2270 | raise ReadError("empty file") |
| 2271 | except TruncatedHeaderError as e: |
| 2272 | if self.offset == 0: |
| 2273 | raise ReadError(str(e)) |
| 2274 | except SubsequentHeaderError as e: |
| 2275 | raise ReadError(str(e)) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2276 | break |
| 2277 | |
Lars Gustäbel | 9520a43 | 2009-11-22 18:48:49 +0000 | [diff] [blame] | 2278 | if tarinfo is not None: |
| 2279 | self.members.append(tarinfo) |
| 2280 | else: |
| 2281 | self._loaded = True |
| 2282 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2283 | return tarinfo |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2284 | |
| 2285 | #-------------------------------------------------------------------------- |
| 2286 | # Little helper methods: |
| 2287 | |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2288 | def _getmember(self, name, tarinfo=None, normalize=False): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2289 | """Find an archive member by name from bottom to top. |
| 2290 | If tarinfo is given, it is used as the starting point. |
| 2291 | """ |
Martin v. Löwis | f3c5611 | 2004-09-18 09:08:52 +0000 | [diff] [blame] | 2292 | # Ensure that all members have been loaded. |
| 2293 | members = self.getmembers() |
| 2294 | |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2295 | # Limit the member search list up to tarinfo. |
| 2296 | if tarinfo is not None: |
| 2297 | members = members[:members.index(tarinfo)] |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2298 | |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2299 | if normalize: |
| 2300 | name = os.path.normpath(name) |
| 2301 | |
| 2302 | for member in reversed(members): |
| 2303 | if normalize: |
| 2304 | member_name = os.path.normpath(member.name) |
| 2305 | else: |
| 2306 | member_name = member.name |
| 2307 | |
| 2308 | if name == member_name: |
| 2309 | return member |
Andrew M. Kuchling | 864bba1 | 2004-07-10 22:02:11 +0000 | [diff] [blame] | 2310 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2311 | def _load(self): |
| 2312 | """Read through the entire archive file and look for readable |
| 2313 | members. |
| 2314 | """ |
| 2315 | while True: |
| 2316 | tarinfo = self.next() |
| 2317 | if tarinfo is None: |
| 2318 | break |
| 2319 | self._loaded = True |
| 2320 | |
| 2321 | def _check(self, mode=None): |
| 2322 | """Check if TarFile is still open, and if the operation's mode |
| 2323 | corresponds to TarFile's mode. |
| 2324 | """ |
| 2325 | if self.closed: |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 2326 | raise IOError("%s is closed" % self.__class__.__name__) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 2327 | if mode is not None and self.mode not in mode: |
| 2328 | raise IOError("bad operation for mode %r" % self.mode) |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2329 | |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2330 | def _find_link_target(self, tarinfo): |
| 2331 | """Find the target member of a symlink or hardlink member in the |
| 2332 | archive. |
| 2333 | """ |
| 2334 | if tarinfo.issym(): |
| 2335 | # Always search the entire archive. |
Lars Gustäbel | 1ef9eda | 2012-04-24 21:04:40 +0200 | [diff] [blame] | 2336 | linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname))) |
Lars Gustäbel | 1b51272 | 2010-06-03 12:45:16 +0000 | [diff] [blame] | 2337 | limit = None |
| 2338 | else: |
| 2339 | # Search the archive before the link, because a hard link is |
| 2340 | # just a reference to an already archived file. |
| 2341 | linkname = tarinfo.linkname |
| 2342 | limit = tarinfo |
| 2343 | |
| 2344 | member = self._getmember(linkname, tarinfo=limit, normalize=True) |
| 2345 | if member is None: |
| 2346 | raise KeyError("linkname %r not found" % linkname) |
| 2347 | return member |
| 2348 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2349 | def __iter__(self): |
| 2350 | """Provide an iterator object. |
| 2351 | """ |
| 2352 | if self._loaded: |
| 2353 | return iter(self.members) |
| 2354 | else: |
| 2355 | return TarIter(self) |
| 2356 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2357 | def _dbg(self, level, msg): |
| 2358 | """Write debugging output to sys.stderr. |
| 2359 | """ |
| 2360 | if level <= self.debug: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 2361 | print(msg, file=sys.stderr) |
Lars Gustäbel | 0138581 | 2010-03-03 12:08:54 +0000 | [diff] [blame] | 2362 | |
| 2363 | def __enter__(self): |
| 2364 | self._check() |
| 2365 | return self |
| 2366 | |
| 2367 | def __exit__(self, type, value, traceback): |
| 2368 | if type is None: |
| 2369 | self.close() |
| 2370 | else: |
| 2371 | # An exception occurred. We must not call close() because |
| 2372 | # it would try to write end-of-archive blocks and padding. |
| 2373 | if not self._extfileobj: |
| 2374 | self.fileobj.close() |
| 2375 | self.closed = True |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2376 | # class TarFile |
| 2377 | |
| 2378 | class TarIter: |
| 2379 | """Iterator Class. |
| 2380 | |
| 2381 | for tarinfo in TarFile(...): |
| 2382 | suite... |
| 2383 | """ |
| 2384 | |
| 2385 | def __init__(self, tarfile): |
| 2386 | """Construct a TarIter object. |
| 2387 | """ |
| 2388 | self.tarfile = tarfile |
Martin v. Löwis | 637431b | 2005-03-03 23:12:42 +0000 | [diff] [blame] | 2389 | self.index = 0 |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2390 | def __iter__(self): |
| 2391 | """Return iterator object. |
| 2392 | """ |
| 2393 | return self |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 2394 | def __next__(self): |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2395 | """Return the next item using TarFile's next() method. |
| 2396 | When all members have been read, set TarFile as _loaded. |
| 2397 | """ |
Martin v. Löwis | 637431b | 2005-03-03 23:12:42 +0000 | [diff] [blame] | 2398 | # Fix for SF #1100429: Under rare circumstances it can |
| 2399 | # happen that getmembers() is called during iteration, |
| 2400 | # which will cause TarIter to stop prematurely. |
| 2401 | if not self.tarfile._loaded: |
| 2402 | tarinfo = self.tarfile.next() |
| 2403 | if not tarinfo: |
| 2404 | self.tarfile._loaded = True |
| 2405 | raise StopIteration |
| 2406 | else: |
| 2407 | try: |
| 2408 | tarinfo = self.tarfile.members[self.index] |
| 2409 | except IndexError: |
| 2410 | raise StopIteration |
| 2411 | self.index += 1 |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2412 | return tarinfo |
| 2413 | |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2414 | #-------------------- |
| 2415 | # exported functions |
| 2416 | #-------------------- |
| 2417 | def is_tarfile(name): |
| 2418 | """Return True if name points to a tar archive that we |
| 2419 | are able to handle, else return False. |
| 2420 | """ |
| 2421 | try: |
| 2422 | t = open(name) |
| 2423 | t.close() |
| 2424 | return True |
| 2425 | except TarError: |
| 2426 | return False |
| 2427 | |
Guido van Rossum | e7ba495 | 2007-06-06 23:52:48 +0000 | [diff] [blame] | 2428 | bltn_open = open |
Neal Norwitz | b9ef4ae | 2003-01-05 23:19:43 +0000 | [diff] [blame] | 2429 | open = TarFile.open |