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