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