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