blob: 80b6e35d42983f3911e30c8957b2304796f67652 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002#-------------------------------------------------------------------
3# tarfile.py
4#-------------------------------------------------------------------
Christian Heimes9c1257e2007-11-04 11:37:22 +00005# Copyright (C) 2002 Lars Gustaebel <lars@gustaebel.de>
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00006# 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 Rossumd8faa362007-04-27 19:54:29 +000032version = "0.9.0"
Guido van Rossum98297ee2007-11-06 21:34:58 +000033__author__ = "Lars Gust\u00e4bel (lars@gustaebel.de)"
Senthil Kumaran7c9719c2011-07-28 22:32:49 +080034__date__ = "$Date: 2011-02-25 17:42:01 +0200 (Fri, 25 Feb 2011) $"
35__cvsid__ = "$Id: tarfile.py 88586 2011-02-25 15:42:01Z marc-andre.lemburg $"
Guido van Rossum98297ee2007-11-06 21:34:58 +000036__credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000037
38#---------
39# Imports
40#---------
Serhiy Storchakacf4a2f22015-03-11 17:18:03 +020041from builtins import open as bltn_open
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000042import sys
43import os
Eli Bendersky74c503b2012-01-03 06:26:13 +020044import io
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000045import shutil
46import stat
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000047import time
48import struct
Thomas Wouters89f507f2006-12-13 04:49:30 +000049import copy
Guido van Rossumd8faa362007-04-27 19:54:29 +000050import re
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000051
52try:
53 import grp, pwd
Brett Cannoncd171c82013-07-04 17:43:24 -040054except ImportError:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000055 grp = pwd = None
56
Brian Curtin16633fa2010-07-09 13:54:27 +000057# os.symlink on Windows prior to 6.0 raises NotImplementedError
58symlink_exception = (AttributeError, NotImplementedError)
59try:
Andrew Svetlov2606a6f2012-12-19 14:33:35 +020060 # OSError (winerror=1314) will be raised if the caller does not hold the
Brian Curtin16633fa2010-07-09 13:54:27 +000061 # SeCreateSymbolicLinkPrivilege privilege
Andrew Svetlov2606a6f2012-12-19 14:33:35 +020062 symlink_exception += (OSError,)
Brian Curtin16633fa2010-07-09 13:54:27 +000063except NameError:
64 pass
65
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000066# from tarfile import *
67__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"]
68
69#---------------------------------------------------------
70# tar constants
71#---------------------------------------------------------
Lars Gustäbelb506dc32007-08-07 18:36:16 +000072NUL = b"\0" # the null character
Guido van Rossumd8faa362007-04-27 19:54:29 +000073BLOCKSIZE = 512 # length of processing blocks
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000074RECORDSIZE = BLOCKSIZE * 20 # length of records
Lars Gustäbelb506dc32007-08-07 18:36:16 +000075GNU_MAGIC = b"ustar \0" # magic gnu tar string
76POSIX_MAGIC = b"ustar\x0000" # magic posix tar string
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000077
Guido van Rossumd8faa362007-04-27 19:54:29 +000078LENGTH_NAME = 100 # maximum length of a filename
79LENGTH_LINK = 100 # maximum length of a linkname
80LENGTH_PREFIX = 155 # maximum length of the prefix field
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000081
Lars Gustäbelb506dc32007-08-07 18:36:16 +000082REGTYPE = b"0" # regular file
83AREGTYPE = b"\0" # regular file
84LNKTYPE = b"1" # link (inside tarfile)
85SYMTYPE = b"2" # symbolic link
86CHRTYPE = b"3" # character special device
87BLKTYPE = b"4" # block special device
88DIRTYPE = b"5" # directory
89FIFOTYPE = b"6" # fifo special device
90CONTTYPE = b"7" # contiguous file
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000091
Lars Gustäbelb506dc32007-08-07 18:36:16 +000092GNUTYPE_LONGNAME = b"L" # GNU tar longname
93GNUTYPE_LONGLINK = b"K" # GNU tar longlink
94GNUTYPE_SPARSE = b"S" # GNU tar sparse file
Guido van Rossumd8faa362007-04-27 19:54:29 +000095
Lars Gustäbelb506dc32007-08-07 18:36:16 +000096XHDTYPE = b"x" # POSIX.1-2001 extended header
97XGLTYPE = b"g" # POSIX.1-2001 global header
98SOLARIS_XHDTYPE = b"X" # Solaris extended header
Guido van Rossumd8faa362007-04-27 19:54:29 +000099
100USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format
101GNU_FORMAT = 1 # GNU tar format
102PAX_FORMAT = 2 # POSIX.1-2001 (pax) format
103DEFAULT_FORMAT = GNU_FORMAT
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000104
105#---------------------------------------------------------
106# tarfile constants
107#---------------------------------------------------------
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108# File types that tarfile supports:
109SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,
110 SYMTYPE, DIRTYPE, FIFOTYPE,
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000111 CONTTYPE, CHRTYPE, BLKTYPE,
112 GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
113 GNUTYPE_SPARSE)
114
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115# File types that will be treated as a regular file.
116REGULAR_TYPES = (REGTYPE, AREGTYPE,
117 CONTTYPE, GNUTYPE_SPARSE)
118
119# File types that are part of the GNU tar format.
120GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
121 GNUTYPE_SPARSE)
122
123# Fields from a pax header that override a TarInfo attribute.
124PAX_FIELDS = ("path", "linkpath", "size", "mtime",
125 "uid", "gid", "uname", "gname")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000126
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000127# Fields from a pax header that are affected by hdrcharset.
128PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"}
129
Guido van Rossume7ba4952007-06-06 23:52:48 +0000130# Fields in a pax header that are numbers, all other fields
131# are treated as strings.
132PAX_NUMBER_FIELDS = {
133 "atime": float,
134 "ctime": float,
135 "mtime": float,
136 "uid": int,
137 "gid": int,
138 "size": int
139}
140
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000141#---------------------------------------------------------
Guido van Rossumd8faa362007-04-27 19:54:29 +0000142# initialization
143#---------------------------------------------------------
Victor Stinner0f35e2c2010-06-11 23:46:47 +0000144if os.name in ("nt", "ce"):
145 ENCODING = "utf-8"
146else:
147 ENCODING = sys.getfilesystemencoding()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148
149#---------------------------------------------------------
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000150# Some useful functions
151#---------------------------------------------------------
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000152
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000153def stn(s, length, encoding, errors):
154 """Convert a string to a null-terminated bytes object.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000155 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000156 s = s.encode(encoding, errors)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000157 return s[:length] + (length - len(s)) * NUL
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000159def nts(s, encoding, errors):
160 """Convert a null-terminated bytes object to a string.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000161 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000162 p = s.find(b"\0")
163 if p != -1:
164 s = s[:p]
165 return s.decode(encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166
Thomas Wouters477c8d52006-05-27 19:21:47 +0000167def nti(s):
168 """Convert a number field to a python number.
169 """
170 # There are two possible encodings for a number field, see
171 # itn() below.
Lars Gustäbelac3d1372011-10-14 12:46:40 +0200172 if s[0] in (0o200, 0o377):
173 n = 0
174 for i in range(len(s) - 1):
175 n <<= 8
176 n += s[i + 1]
177 if s[0] == 0o377:
178 n = -(256 ** (len(s) - 1) - n)
179 else:
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000180 try:
Lars Gustäbelb7a688b2015-07-02 19:38:38 +0200181 s = nts(s, "ascii", "strict")
182 n = int(s.strip() or "0", 8)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000183 except ValueError:
Lars Gustäbel9520a432009-11-22 18:48:49 +0000184 raise InvalidHeaderError("invalid header")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000185 return n
186
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187def itn(n, digits=8, format=DEFAULT_FORMAT):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000188 """Convert a python number to a number field.
189 """
190 # POSIX 1003.1-1988 requires numbers to be encoded as a string of
191 # octal digits followed by a null-byte, this allows values up to
192 # (8**(digits-1))-1. GNU tar allows storing numbers greater than
Lars Gustäbelac3d1372011-10-14 12:46:40 +0200193 # that if necessary. A leading 0o200 or 0o377 byte indicate this
194 # particular encoding, the following digits-1 bytes are a big-endian
195 # base-256 representation. This allows values up to (256**(digits-1))-1.
196 # A 0o200 byte indicates a positive number, a 0o377 byte a negative
197 # number.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000198 if 0 <= n < 8 ** (digits - 1):
Ethan Furmandf3ed242014-01-05 06:50:30 -0800199 s = bytes("%0*o" % (digits - 1, int(n)), "ascii") + NUL
Lars Gustäbelac3d1372011-10-14 12:46:40 +0200200 elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1):
201 if n >= 0:
202 s = bytearray([0o200])
203 else:
204 s = bytearray([0o377])
205 n = 256 ** digits + n
Thomas Wouters477c8d52006-05-27 19:21:47 +0000206
Guido van Rossum805365e2007-05-07 22:24:25 +0000207 for i in range(digits - 1):
Lars Gustäbelac3d1372011-10-14 12:46:40 +0200208 s.insert(1, n & 0o377)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000209 n >>= 8
Lars Gustäbelac3d1372011-10-14 12:46:40 +0200210 else:
211 raise ValueError("overflow in number field")
212
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213 return s
214
215def calc_chksums(buf):
216 """Calculate the checksum for a member's header by summing up all
217 characters except for the chksum field which is treated as if
218 it was filled with spaces. According to the GNU tar sources,
219 some tars (Sun and NeXT) calculate chksum with signed char,
220 which will be different if there are chars in the buffer with
221 the high bit set. So we calculate two checksums, unsigned and
222 signed.
223 """
Ross Lagerwall468ff4c2012-05-17 19:49:27 +0200224 unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf))
225 signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000226 return unsigned_chksum, signed_chksum
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000227
Lars Gustäbel03572682015-07-06 09:27:24 +0200228def copyfileobj(src, dst, length=None, exception=OSError):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000229 """Copy length bytes from fileobj src to fileobj dst.
230 If length is None, copy the entire content.
231 """
232 if length == 0:
233 return
234 if length is None:
235 shutil.copyfileobj(src, dst)
236 return
237
238 BUFSIZE = 16 * 1024
239 blocks, remainder = divmod(length, BUFSIZE)
Guido van Rossum805365e2007-05-07 22:24:25 +0000240 for b in range(blocks):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000241 buf = src.read(BUFSIZE)
242 if len(buf) < BUFSIZE:
Lars Gustäbel03572682015-07-06 09:27:24 +0200243 raise exception("unexpected end of data")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000244 dst.write(buf)
245
246 if remainder != 0:
247 buf = src.read(remainder)
248 if len(buf) < remainder:
Lars Gustäbel03572682015-07-06 09:27:24 +0200249 raise exception("unexpected end of data")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000250 dst.write(buf)
251 return
252
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000253def filemode(mode):
Giampaolo Rodola'ffa1d0b2012-05-15 15:30:25 +0200254 """Deprecated in this location; use stat.filemode."""
255 import warnings
256 warnings.warn("deprecated in favor of stat.filemode",
257 DeprecationWarning, 2)
258 return stat.filemode(mode)
259
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +0200260def _safe_print(s):
261 encoding = getattr(sys.stdout, 'encoding', None)
262 if encoding is not None:
263 s = s.encode(encoding, 'backslashreplace').decode(encoding)
264 print(s, end=' ')
265
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000266
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000267class TarError(Exception):
268 """Base exception."""
269 pass
270class ExtractError(TarError):
271 """General exception for extract errors."""
272 pass
273class ReadError(TarError):
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300274 """Exception for unreadable tar archives."""
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000275 pass
276class CompressionError(TarError):
277 """Exception for unavailable compression methods."""
278 pass
279class StreamError(TarError):
280 """Exception for unsupported operations on stream-like TarFiles."""
281 pass
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000282class HeaderError(TarError):
Lars Gustäbel9520a432009-11-22 18:48:49 +0000283 """Base exception for header errors."""
284 pass
285class EmptyHeaderError(HeaderError):
286 """Exception for empty headers."""
287 pass
288class TruncatedHeaderError(HeaderError):
289 """Exception for truncated headers."""
290 pass
291class EOFHeaderError(HeaderError):
292 """Exception for end of file headers."""
293 pass
294class InvalidHeaderError(HeaderError):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000295 """Exception for invalid headers."""
296 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000297class SubsequentHeaderError(HeaderError):
298 """Exception for missing and invalid extended headers."""
299 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000300
301#---------------------------
302# internal stream interface
303#---------------------------
304class _LowLevelFile:
305 """Low-level file object. Supports reading and writing.
306 It is used instead of a regular file object for streaming
307 access.
308 """
309
310 def __init__(self, name, mode):
311 mode = {
312 "r": os.O_RDONLY,
313 "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
314 }[mode]
315 if hasattr(os, "O_BINARY"):
316 mode |= os.O_BINARY
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +0000317 self.fd = os.open(name, mode, 0o666)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000318
319 def close(self):
320 os.close(self.fd)
321
322 def read(self, size):
323 return os.read(self.fd, size)
324
325 def write(self, s):
326 os.write(self.fd, s)
327
328class _Stream:
329 """Class that serves as an adapter between TarFile and
330 a stream-like object. The stream-like object only
331 needs to have a read() or write() method and is accessed
332 blockwise. Use of gzip or bzip2 compression is possible.
333 A stream-like object could be for example: sys.stdin,
334 sys.stdout, a socket, a tape device etc.
335
336 _Stream is intended to be used only internally.
337 """
338
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000339 def __init__(self, name, mode, comptype, fileobj, bufsize):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000340 """Construct a _Stream object.
341 """
342 self._extfileobj = True
343 if fileobj is None:
344 fileobj = _LowLevelFile(name, mode)
345 self._extfileobj = False
346
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000347 if comptype == '*':
348 # Enable transparent compression detection for the
349 # stream interface
350 fileobj = _StreamProxy(fileobj)
351 comptype = fileobj.getcomptype()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000352
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000353 self.name = name or ""
354 self.mode = mode
355 self.comptype = comptype
356 self.fileobj = fileobj
357 self.bufsize = bufsize
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000358 self.buf = b""
Guido van Rossume2a383d2007-01-15 16:59:06 +0000359 self.pos = 0
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000360 self.closed = False
361
Antoine Pitrou605c2932010-09-23 20:15:14 +0000362 try:
363 if comptype == "gz":
364 try:
365 import zlib
Brett Cannoncd171c82013-07-04 17:43:24 -0400366 except ImportError:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000367 raise CompressionError("zlib module is not available")
368 self.zlib = zlib
369 self.crc = zlib.crc32(b"")
370 if mode == "r":
371 self._init_read_gz()
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100372 self.exception = zlib.error
Antoine Pitrou605c2932010-09-23 20:15:14 +0000373 else:
374 self._init_write_gz()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000375
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100376 elif comptype == "bz2":
Antoine Pitrou605c2932010-09-23 20:15:14 +0000377 try:
378 import bz2
Brett Cannoncd171c82013-07-04 17:43:24 -0400379 except ImportError:
Antoine Pitrou605c2932010-09-23 20:15:14 +0000380 raise CompressionError("bz2 module is not available")
381 if mode == "r":
382 self.dbuf = b""
383 self.cmp = bz2.BZ2Decompressor()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200384 self.exception = OSError
Antoine Pitrou605c2932010-09-23 20:15:14 +0000385 else:
386 self.cmp = bz2.BZ2Compressor()
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100387
388 elif comptype == "xz":
389 try:
390 import lzma
Brett Cannoncd171c82013-07-04 17:43:24 -0400391 except ImportError:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100392 raise CompressionError("lzma module is not available")
393 if mode == "r":
394 self.dbuf = b""
395 self.cmp = lzma.LZMADecompressor()
396 self.exception = lzma.LZMAError
397 else:
398 self.cmp = lzma.LZMACompressor()
399
400 elif comptype != "tar":
401 raise CompressionError("unknown compression type %r" % comptype)
402
Antoine Pitrou605c2932010-09-23 20:15:14 +0000403 except:
404 if not self._extfileobj:
405 self.fileobj.close()
406 self.closed = True
407 raise
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000408
409 def __del__(self):
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000410 if hasattr(self, "closed") and not self.closed:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000411 self.close()
412
413 def _init_write_gz(self):
414 """Initialize for writing with gzip compression.
415 """
416 self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED,
417 -self.zlib.MAX_WBITS,
418 self.zlib.DEF_MEM_LEVEL,
419 0)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000420 timestamp = struct.pack("<L", int(time.time()))
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000421 self.__write(b"\037\213\010\010" + timestamp + b"\002\377")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000422 if self.name.endswith(".gz"):
423 self.name = self.name[:-3]
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000424 # RFC1952 says we must use ISO-8859-1 for the FNAME field.
425 self.__write(self.name.encode("iso-8859-1", "replace") + NUL)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000426
427 def write(self, s):
428 """Write string s to the stream.
429 """
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000430 if self.comptype == "gz":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000431 self.crc = self.zlib.crc32(s, self.crc)
432 self.pos += len(s)
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000433 if self.comptype != "tar":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000434 s = self.cmp.compress(s)
435 self.__write(s)
436
437 def __write(self, s):
438 """Write string s to the stream if a whole new block
439 is ready to be written.
440 """
441 self.buf += s
442 while len(self.buf) > self.bufsize:
443 self.fileobj.write(self.buf[:self.bufsize])
444 self.buf = self.buf[self.bufsize:]
445
446 def close(self):
447 """Close the _Stream object. No operation should be
448 done on it afterwards.
449 """
450 if self.closed:
451 return
452
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000453 self.closed = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300454 try:
455 if self.mode == "w" and self.comptype != "tar":
456 self.buf += self.cmp.flush()
457
458 if self.mode == "w" and self.buf:
459 self.fileobj.write(self.buf)
460 self.buf = b""
461 if self.comptype == "gz":
Martin Panterb82032f2015-12-11 05:19:29 +0000462 self.fileobj.write(struct.pack("<L", self.crc))
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300463 self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF))
464 finally:
465 if not self._extfileobj:
466 self.fileobj.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000467
468 def _init_read_gz(self):
469 """Initialize for reading a gzip compressed fileobj.
470 """
471 self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000472 self.dbuf = b""
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000473
474 # taken from gzip.GzipFile with some alterations
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000475 if self.__read(2) != b"\037\213":
Thomas Wouters477c8d52006-05-27 19:21:47 +0000476 raise ReadError("not a gzip file")
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000477 if self.__read(1) != b"\010":
Thomas Wouters477c8d52006-05-27 19:21:47 +0000478 raise CompressionError("unsupported compression method")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000479
480 flag = ord(self.__read(1))
481 self.__read(6)
482
483 if flag & 4:
484 xlen = ord(self.__read(1)) + 256 * ord(self.__read(1))
485 self.read(xlen)
486 if flag & 8:
487 while True:
488 s = self.__read(1)
489 if not s or s == NUL:
490 break
491 if flag & 16:
492 while True:
493 s = self.__read(1)
494 if not s or s == NUL:
495 break
496 if flag & 2:
497 self.__read(2)
498
499 def tell(self):
500 """Return the stream's file pointer position.
501 """
502 return self.pos
503
504 def seek(self, pos=0):
505 """Set the stream's file pointer to pos. Negative seeking
506 is forbidden.
507 """
508 if pos - self.pos >= 0:
509 blocks, remainder = divmod(pos - self.pos, self.bufsize)
Guido van Rossum805365e2007-05-07 22:24:25 +0000510 for i in range(blocks):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000511 self.read(self.bufsize)
512 self.read(remainder)
513 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000514 raise StreamError("seeking backwards is not allowed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000515 return self.pos
516
517 def read(self, size=None):
518 """Return the next size number of bytes from the stream.
519 If size is not defined, return all bytes of the stream
520 up to EOF.
521 """
522 if size is None:
523 t = []
524 while True:
525 buf = self._read(self.bufsize)
526 if not buf:
527 break
528 t.append(buf)
529 buf = "".join(t)
530 else:
531 buf = self._read(size)
532 self.pos += len(buf)
533 return buf
534
535 def _read(self, size):
536 """Return size bytes from the stream.
537 """
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000538 if self.comptype == "tar":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000539 return self.__read(size)
540
541 c = len(self.dbuf)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000542 while c < size:
543 buf = self.__read(self.bufsize)
544 if not buf:
545 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000546 try:
547 buf = self.cmp.decompress(buf)
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100548 except self.exception:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000549 raise ReadError("invalid compressed data")
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000550 self.dbuf += buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000551 c += len(buf)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000552 buf = self.dbuf[:size]
553 self.dbuf = self.dbuf[size:]
554 return buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000555
556 def __read(self, size):
557 """Return size bytes from stream. If internal buffer is empty,
558 read another block from the stream.
559 """
560 c = len(self.buf)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000561 while c < size:
562 buf = self.fileobj.read(self.bufsize)
563 if not buf:
564 break
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000565 self.buf += buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000566 c += len(buf)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000567 buf = self.buf[:size]
568 self.buf = self.buf[size:]
569 return buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000570# class _Stream
571
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000572class _StreamProxy(object):
573 """Small proxy class that enables transparent compression
574 detection for the Stream interface (mode 'r|*').
575 """
576
577 def __init__(self, fileobj):
578 self.fileobj = fileobj
579 self.buf = self.fileobj.read(BLOCKSIZE)
580
581 def read(self, size):
582 self.read = self.fileobj.read
583 return self.buf
584
585 def getcomptype(self):
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100586 if self.buf.startswith(b"\x1f\x8b\x08"):
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000587 return "gz"
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100588 elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY":
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000589 return "bz2"
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100590 elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")):
591 return "xz"
592 else:
593 return "tar"
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000594
595 def close(self):
596 self.fileobj.close()
597# class StreamProxy
598
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000599#------------------------
600# Extraction file object
601#------------------------
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000602class _FileInFile(object):
603 """A thin wrapper around an existing file object that
604 provides a part of its data as an individual file
605 object.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000606 """
607
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000608 def __init__(self, fileobj, offset, size, blockinfo=None):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000609 self.fileobj = fileobj
610 self.offset = offset
611 self.size = size
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000612 self.position = 0
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200613 self.name = getattr(fileobj, "name", None)
614 self.closed = False
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000615
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000616 if blockinfo is None:
617 blockinfo = [(0, size)]
618
619 # Construct a map with data and zero blocks.
620 self.map_index = 0
621 self.map = []
622 lastpos = 0
623 realpos = self.offset
624 for offset, size in blockinfo:
625 if offset > lastpos:
626 self.map.append((False, lastpos, offset, None))
627 self.map.append((True, offset, offset + size, realpos))
628 realpos += size
629 lastpos = offset + size
630 if lastpos < self.size:
631 self.map.append((False, lastpos, self.size, None))
632
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200633 def flush(self):
634 pass
635
636 def readable(self):
637 return True
638
639 def writable(self):
640 return False
641
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000642 def seekable(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000643 return self.fileobj.seekable()
644
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000645 def tell(self):
646 """Return the current file position.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000647 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000648 return self.position
649
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200650 def seek(self, position, whence=io.SEEK_SET):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000651 """Seek to a position in the file.
652 """
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200653 if whence == io.SEEK_SET:
654 self.position = min(max(position, 0), self.size)
655 elif whence == io.SEEK_CUR:
656 if position < 0:
657 self.position = max(self.position + position, 0)
658 else:
659 self.position = min(self.position + position, self.size)
660 elif whence == io.SEEK_END:
661 self.position = max(min(self.size + position, self.size), 0)
662 else:
663 raise ValueError("Invalid argument")
664 return self.position
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000665
666 def read(self, size=None):
667 """Read data from the file.
668 """
669 if size is None:
670 size = self.size - self.position
671 else:
672 size = min(size, self.size - self.position)
673
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000674 buf = b""
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000675 while size > 0:
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000676 while True:
677 data, start, stop, offset = self.map[self.map_index]
678 if start <= self.position < stop:
679 break
680 else:
681 self.map_index += 1
682 if self.map_index == len(self.map):
683 self.map_index = 0
684 length = min(size, stop - self.position)
685 if data:
Lars Gustäbeldd071042011-02-23 11:42:22 +0000686 self.fileobj.seek(offset + (self.position - start))
Lars Gustäbel03572682015-07-06 09:27:24 +0200687 b = self.fileobj.read(length)
688 if len(b) != length:
689 raise ReadError("unexpected end of data")
690 buf += b
Lars Gustäbel9cbdd752010-10-29 09:08:19 +0000691 else:
692 buf += NUL * length
693 size -= length
694 self.position += length
695 return buf
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000696
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200697 def readinto(self, b):
698 buf = self.read(len(b))
699 b[:len(buf)] = buf
700 return len(buf)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000701
702 def close(self):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000703 self.closed = True
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200704#class _FileInFile
Martin v. Löwisdf241532005-03-03 08:17:42 +0000705
Lars Gustäbelb062a2f2012-05-14 13:18:16 +0200706class ExFileObject(io.BufferedReader):
707
708 def __init__(self, tarfile, tarinfo):
709 fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data,
710 tarinfo.size, tarinfo.sparse)
711 super().__init__(fileobj)
712#class ExFileObject
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000713
714#------------------
715# Exported Classes
716#------------------
717class TarInfo(object):
718 """Informational class which holds the details about an
719 archive member given by a tar header block.
720 TarInfo objects are returned by TarFile.getmember(),
721 TarFile.getmembers() and TarFile.gettarinfo() and are
722 usually created internally.
723 """
724
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +0000725 __slots__ = ("name", "mode", "uid", "gid", "size", "mtime",
726 "chksum", "type", "linkname", "uname", "gname",
727 "devmajor", "devminor",
728 "offset", "offset_data", "pax_headers", "sparse",
729 "tarfile", "_sparse_structs", "_link_target")
730
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000731 def __init__(self, name=""):
732 """Construct a TarInfo object. name is the optional name
733 of the member.
734 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735 self.name = name # member name
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000736 self.mode = 0o644 # file permissions
Thomas Wouters477c8d52006-05-27 19:21:47 +0000737 self.uid = 0 # user id
738 self.gid = 0 # group id
739 self.size = 0 # file size
740 self.mtime = 0 # modification time
741 self.chksum = 0 # header checksum
742 self.type = REGTYPE # member type
743 self.linkname = "" # link name
Lars Gustäbel331b8002010-10-04 15:18:47 +0000744 self.uname = "" # user name
745 self.gname = "" # group name
Thomas Wouters477c8d52006-05-27 19:21:47 +0000746 self.devmajor = 0 # device major number
747 self.devminor = 0 # device minor number
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000748
Thomas Wouters477c8d52006-05-27 19:21:47 +0000749 self.offset = 0 # the tar header starts here
750 self.offset_data = 0 # the file's data starts here
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000751
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +0000752 self.sparse = None # sparse member information
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753 self.pax_headers = {} # pax header information
754
755 # In pax headers the "name" and "linkname" field are called
756 # "path" and "linkpath".
757 def _getpath(self):
758 return self.name
759 def _setpath(self, name):
760 self.name = name
761 path = property(_getpath, _setpath)
762
763 def _getlinkpath(self):
764 return self.linkname
765 def _setlinkpath(self, linkname):
766 self.linkname = linkname
767 linkpath = property(_getlinkpath, _setlinkpath)
768
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000769 def __repr__(self):
770 return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
771
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000772 def get_info(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000773 """Return the TarInfo's attributes as a dictionary.
774 """
775 info = {
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000776 "name": self.name,
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000777 "mode": self.mode & 0o7777,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000778 "uid": self.uid,
779 "gid": self.gid,
780 "size": self.size,
781 "mtime": self.mtime,
782 "chksum": self.chksum,
783 "type": self.type,
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000784 "linkname": self.linkname,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000785 "uname": self.uname,
786 "gname": self.gname,
787 "devmajor": self.devmajor,
788 "devminor": self.devminor
789 }
790
791 if info["type"] == DIRTYPE and not info["name"].endswith("/"):
792 info["name"] += "/"
793
794 return info
795
Victor Stinnerde629d42010-05-05 21:43:57 +0000796 def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000797 """Return a tar header as a string of 512 byte blocks.
798 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000799 info = self.get_info()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000800
Guido van Rossumd8faa362007-04-27 19:54:29 +0000801 if format == USTAR_FORMAT:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000802 return self.create_ustar_header(info, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000803 elif format == GNU_FORMAT:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000804 return self.create_gnu_header(info, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000805 elif format == PAX_FORMAT:
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000806 return self.create_pax_header(info, encoding)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000807 else:
808 raise ValueError("invalid format")
809
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000810 def create_ustar_header(self, info, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000811 """Return the object as a ustar header block.
812 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000813 info["magic"] = POSIX_MAGIC
814
815 if len(info["linkname"]) > LENGTH_LINK:
816 raise ValueError("linkname is too long")
817
818 if len(info["name"]) > LENGTH_NAME:
819 info["prefix"], info["name"] = self._posix_split_name(info["name"])
820
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000821 return self._create_header(info, USTAR_FORMAT, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000822
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000823 def create_gnu_header(self, info, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000824 """Return the object as a GNU header block sequence.
825 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000826 info["magic"] = GNU_MAGIC
827
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000828 buf = b""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000829 if len(info["linkname"]) > LENGTH_LINK:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000830 buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000831
832 if len(info["name"]) > LENGTH_NAME:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000833 buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000834
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000835 return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000836
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000837 def create_pax_header(self, info, encoding):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000838 """Return the object as a ustar header block. If it cannot be
839 represented this way, prepend a pax extended header sequence
840 with supplement information.
841 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000842 info["magic"] = POSIX_MAGIC
843 pax_headers = self.pax_headers.copy()
844
845 # Test string fields for values that exceed the field length or cannot
846 # be represented in ASCII encoding.
847 for name, hname, length in (
848 ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
849 ("uname", "uname", 32), ("gname", "gname", 32)):
850
Guido van Rossume7ba4952007-06-06 23:52:48 +0000851 if hname in pax_headers:
852 # The pax header has priority.
853 continue
854
Guido van Rossumd8faa362007-04-27 19:54:29 +0000855 # Try to encode the string as ASCII.
856 try:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000857 info[name].encode("ascii", "strict")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000858 except UnicodeEncodeError:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000859 pax_headers[hname] = info[name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000860 continue
861
Guido van Rossume7ba4952007-06-06 23:52:48 +0000862 if len(info[name]) > length:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000863 pax_headers[hname] = info[name]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864
865 # Test number fields for values that exceed the field limit or values
866 # that like to be stored as float.
867 for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
Guido van Rossume7ba4952007-06-06 23:52:48 +0000868 if name in pax_headers:
869 # The pax header has priority. Avoid overflow.
870 info[name] = 0
871 continue
872
Guido van Rossumd8faa362007-04-27 19:54:29 +0000873 val = info[name]
874 if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000875 pax_headers[name] = str(val)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000876 info[name] = 0
877
Guido van Rossume7ba4952007-06-06 23:52:48 +0000878 # Create a pax extended header if necessary.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000879 if pax_headers:
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000880 buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000881 else:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000882 buf = b""
Guido van Rossumd8faa362007-04-27 19:54:29 +0000883
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000884 return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000885
886 @classmethod
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000887 def create_pax_global_header(cls, pax_headers):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000888 """Return the object as a pax global header block sequence.
889 """
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000890 return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000891
892 def _posix_split_name(self, name):
893 """Split a name longer than 100 chars into a prefix
894 and a name part.
895 """
896 prefix = name[:LENGTH_PREFIX + 1]
897 while prefix and prefix[-1] != "/":
898 prefix = prefix[:-1]
899
900 name = name[len(prefix):]
901 prefix = prefix[:-1]
902
903 if not prefix or len(name) > LENGTH_NAME:
904 raise ValueError("name is too long")
905 return prefix, name
906
907 @staticmethod
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000908 def _create_header(info, format, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000909 """Return a header block. info is a dictionary with file
910 information, format must be one of the *_FORMAT constants.
911 """
912 parts = [
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000913 stn(info.get("name", ""), 100, encoding, errors),
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000914 itn(info.get("mode", 0) & 0o7777, 8, format),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000915 itn(info.get("uid", 0), 8, format),
916 itn(info.get("gid", 0), 8, format),
917 itn(info.get("size", 0), 12, format),
918 itn(info.get("mtime", 0), 12, format),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000919 b" ", # checksum field
Guido van Rossumd8faa362007-04-27 19:54:29 +0000920 info.get("type", REGTYPE),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000921 stn(info.get("linkname", ""), 100, encoding, errors),
922 info.get("magic", POSIX_MAGIC),
Lars Gustäbel331b8002010-10-04 15:18:47 +0000923 stn(info.get("uname", ""), 32, encoding, errors),
924 stn(info.get("gname", ""), 32, encoding, errors),
Guido van Rossumd8faa362007-04-27 19:54:29 +0000925 itn(info.get("devmajor", 0), 8, format),
926 itn(info.get("devminor", 0), 8, format),
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000927 stn(info.get("prefix", ""), 155, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000928 ]
929
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000930 buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000931 chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
Lars Gustäbela280ca752007-08-28 07:34:33 +0000932 buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933 return buf
934
935 @staticmethod
936 def _create_payload(payload):
937 """Return the string payload filled with zero bytes
938 up to the next 512 byte border.
939 """
940 blocks, remainder = divmod(len(payload), BLOCKSIZE)
941 if remainder > 0:
942 payload += (BLOCKSIZE - remainder) * NUL
943 return payload
944
945 @classmethod
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000946 def _create_gnu_long_header(cls, name, type, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000947 """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
948 for name.
949 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000950 name = name.encode(encoding, errors) + NUL
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951
952 info = {}
953 info["name"] = "././@LongLink"
954 info["type"] = type
955 info["size"] = len(name)
956 info["magic"] = GNU_MAGIC
957
958 # create extended header + name blocks.
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000959 return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960 cls._create_payload(name)
961
962 @classmethod
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000963 def _create_pax_generic_header(cls, pax_headers, type, encoding):
964 """Return a POSIX.1-2008 extended or global header sequence
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965 that contains a list of keyword, value pairs. The values
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000966 must be strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000967 """
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000968 # Check if one of the fields contains surrogate characters and thereby
969 # forces hdrcharset=BINARY, see _proc_pax() for more information.
970 binary = False
971 for keyword, value in pax_headers.items():
972 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000973 value.encode("utf-8", "strict")
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000974 except UnicodeEncodeError:
975 binary = True
976 break
977
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000978 records = b""
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000979 if binary:
980 # Put the hdrcharset field at the beginning of the header.
981 records += b"21 hdrcharset=BINARY\n"
982
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 for keyword, value in pax_headers.items():
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000984 keyword = keyword.encode("utf-8")
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000985 if binary:
986 # Try to restore the original byte representation of `value'.
987 # Needless to say, that the encoding must match the string.
988 value = value.encode(encoding, "surrogateescape")
989 else:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000990 value = value.encode("utf-8")
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000991
Guido van Rossumd8faa362007-04-27 19:54:29 +0000992 l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n'
993 n = p = 0
994 while True:
995 n = l + len(str(p))
996 if n == p:
997 break
998 p = n
Lars Gustäbela280ca752007-08-28 07:34:33 +0000999 records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001000
1001 # We use a hardcoded "././@PaxHeader" name like star does
1002 # instead of the one that POSIX recommends.
1003 info = {}
1004 info["name"] = "././@PaxHeader"
1005 info["type"] = type
1006 info["size"] = len(records)
1007 info["magic"] = POSIX_MAGIC
1008
1009 # Create pax header + record blocks.
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001010 return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \
Guido van Rossumd8faa362007-04-27 19:54:29 +00001011 cls._create_payload(records)
1012
Guido van Rossum75b64e62005-01-16 00:16:11 +00001013 @classmethod
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001014 def frombuf(cls, buf, encoding, errors):
1015 """Construct a TarInfo object from a 512 byte bytes object.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001016 """
Lars Gustäbel9520a432009-11-22 18:48:49 +00001017 if len(buf) == 0:
1018 raise EmptyHeaderError("empty header")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001019 if len(buf) != BLOCKSIZE:
Lars Gustäbel9520a432009-11-22 18:48:49 +00001020 raise TruncatedHeaderError("truncated header")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001021 if buf.count(NUL) == BLOCKSIZE:
Lars Gustäbel9520a432009-11-22 18:48:49 +00001022 raise EOFHeaderError("end of file header")
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001023
1024 chksum = nti(buf[148:156])
1025 if chksum not in calc_chksums(buf):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001026 raise InvalidHeaderError("bad checksum")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001027
Guido van Rossumd8faa362007-04-27 19:54:29 +00001028 obj = cls()
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001029 obj.name = nts(buf[0:100], encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030 obj.mode = nti(buf[100:108])
1031 obj.uid = nti(buf[108:116])
1032 obj.gid = nti(buf[116:124])
1033 obj.size = nti(buf[124:136])
1034 obj.mtime = nti(buf[136:148])
1035 obj.chksum = chksum
1036 obj.type = buf[156:157]
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001037 obj.linkname = nts(buf[157:257], encoding, errors)
1038 obj.uname = nts(buf[265:297], encoding, errors)
1039 obj.gname = nts(buf[297:329], encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001040 obj.devmajor = nti(buf[329:337])
1041 obj.devminor = nti(buf[337:345])
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001042 prefix = nts(buf[345:500], encoding, errors)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043
Guido van Rossumd8faa362007-04-27 19:54:29 +00001044 # Old V7 tar format represents a directory as a regular
1045 # file with a trailing slash.
1046 if obj.type == AREGTYPE and obj.name.endswith("/"):
1047 obj.type = DIRTYPE
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001048
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001049 # The old GNU sparse format occupies some of the unused
1050 # space in the buffer for up to 4 sparse structures.
1051 # Save the them for later processing in _proc_sparse().
1052 if obj.type == GNUTYPE_SPARSE:
1053 pos = 386
1054 structs = []
1055 for i in range(4):
1056 try:
1057 offset = nti(buf[pos:pos + 12])
1058 numbytes = nti(buf[pos + 12:pos + 24])
1059 except ValueError:
1060 break
1061 structs.append((offset, numbytes))
1062 pos += 24
1063 isextended = bool(buf[482])
1064 origsize = nti(buf[483:495])
1065 obj._sparse_structs = (structs, isextended, origsize)
1066
Guido van Rossumd8faa362007-04-27 19:54:29 +00001067 # Remove redundant slashes from directories.
1068 if obj.isdir():
1069 obj.name = obj.name.rstrip("/")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001070
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071 # Reconstruct a ustar longname.
1072 if prefix and obj.type not in GNU_TYPES:
1073 obj.name = prefix + "/" + obj.name
1074 return obj
1075
1076 @classmethod
1077 def fromtarfile(cls, tarfile):
1078 """Return the next TarInfo object from TarFile object
1079 tarfile.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001080 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001081 buf = tarfile.fileobj.read(BLOCKSIZE)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001082 obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083 obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
1084 return obj._proc_member(tarfile)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001085
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086 #--------------------------------------------------------------------------
1087 # The following are methods that are called depending on the type of a
1088 # member. The entry point is _proc_member() which can be overridden in a
1089 # subclass to add custom _proc_*() methods. A _proc_*() method MUST
1090 # implement the following
1091 # operations:
1092 # 1. Set self.offset_data to the position where the data blocks begin,
1093 # if there is data that follows.
1094 # 2. Set tarfile.offset to the position where the next member's header will
1095 # begin.
1096 # 3. Return self or another valid TarInfo object.
1097 def _proc_member(self, tarfile):
1098 """Choose the right processing method depending on
1099 the type and call it.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001100 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001101 if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
1102 return self._proc_gnulong(tarfile)
1103 elif self.type == GNUTYPE_SPARSE:
1104 return self._proc_sparse(tarfile)
1105 elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
1106 return self._proc_pax(tarfile)
1107 else:
1108 return self._proc_builtin(tarfile)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001109
Guido van Rossumd8faa362007-04-27 19:54:29 +00001110 def _proc_builtin(self, tarfile):
1111 """Process a builtin type or an unknown type which
1112 will be treated as a regular file.
1113 """
1114 self.offset_data = tarfile.fileobj.tell()
1115 offset = self.offset_data
1116 if self.isreg() or self.type not in SUPPORTED_TYPES:
1117 # Skip the following data blocks.
1118 offset += self._block(self.size)
1119 tarfile.offset = offset
Thomas Wouters89f507f2006-12-13 04:49:30 +00001120
Guido van Rossume7ba4952007-06-06 23:52:48 +00001121 # Patch the TarInfo object with saved global
Guido van Rossumd8faa362007-04-27 19:54:29 +00001122 # header information.
Guido van Rossume7ba4952007-06-06 23:52:48 +00001123 self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001124
1125 return self
1126
1127 def _proc_gnulong(self, tarfile):
1128 """Process the blocks that hold a GNU longname
1129 or longlink member.
1130 """
1131 buf = tarfile.fileobj.read(self._block(self.size))
1132
1133 # Fetch the next header and process it.
Lars Gustäbel9520a432009-11-22 18:48:49 +00001134 try:
1135 next = self.fromtarfile(tarfile)
1136 except HeaderError:
1137 raise SubsequentHeaderError("missing or bad subsequent header")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138
1139 # Patch the TarInfo object from the next header with
1140 # the longname information.
1141 next.offset = self.offset
1142 if self.type == GNUTYPE_LONGNAME:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001143 next.name = nts(buf, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001144 elif self.type == GNUTYPE_LONGLINK:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001145 next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001146
1147 return next
1148
1149 def _proc_sparse(self, tarfile):
1150 """Process a GNU sparse header plus extra headers.
1151 """
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001152 # We already collected some sparse structures in frombuf().
1153 structs, isextended, origsize = self._sparse_structs
1154 del self._sparse_structs
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001156 # Collect sparse structures from extended header blocks.
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001157 while isextended:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001158 buf = tarfile.fileobj.read(BLOCKSIZE)
1159 pos = 0
Guido van Rossum805365e2007-05-07 22:24:25 +00001160 for i in range(21):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001161 try:
1162 offset = nti(buf[pos:pos + 12])
1163 numbytes = nti(buf[pos + 12:pos + 24])
1164 except ValueError:
1165 break
Lars Gustäbel9cbdd752010-10-29 09:08:19 +00001166 if offset and numbytes:
1167 structs.append((offset, numbytes))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001168 pos += 24
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001169 isextended = bool(buf[504])
Lars Gustäbel9cbdd752010-10-29 09:08:19 +00001170 self.sparse = structs
Guido van Rossumd8faa362007-04-27 19:54:29 +00001171
1172 self.offset_data = tarfile.fileobj.tell()
1173 tarfile.offset = self.offset_data + self._block(self.size)
1174 self.size = origsize
Guido van Rossumd8faa362007-04-27 19:54:29 +00001175 return self
1176
1177 def _proc_pax(self, tarfile):
1178 """Process an extended or global header as described in
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001179 POSIX.1-2008.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001180 """
1181 # Read the header information.
1182 buf = tarfile.fileobj.read(self._block(self.size))
1183
1184 # A pax header stores supplemental information for either
1185 # the following file (extended) or all following files
1186 # (global).
1187 if self.type == XGLTYPE:
1188 pax_headers = tarfile.pax_headers
1189 else:
1190 pax_headers = tarfile.pax_headers.copy()
1191
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001192 # Check if the pax header contains a hdrcharset field. This tells us
1193 # the encoding of the path, linkpath, uname and gname fields. Normally,
1194 # these fields are UTF-8 encoded but since POSIX.1-2008 tar
1195 # implementations are allowed to store them as raw binary strings if
1196 # the translation to UTF-8 fails.
1197 match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
1198 if match is not None:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001199 pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001200
1201 # For the time being, we don't care about anything other than "BINARY".
1202 # The only other value that is currently allowed by the standard is
1203 # "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1204 hdrcharset = pax_headers.get("hdrcharset")
1205 if hdrcharset == "BINARY":
1206 encoding = tarfile.encoding
1207 else:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001208 encoding = "utf-8"
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001209
Guido van Rossumd8faa362007-04-27 19:54:29 +00001210 # Parse pax header information. A record looks like that:
1211 # "%d %s=%s\n" % (length, keyword, value). length is the size
1212 # of the complete record including the length field itself and
Guido van Rossume7ba4952007-06-06 23:52:48 +00001213 # the newline. keyword and value are both UTF-8 encoded strings.
Antoine Pitroufd036452008-08-19 17:56:33 +00001214 regex = re.compile(br"(\d+) ([^=]+)=")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001215 pos = 0
1216 while True:
1217 match = regex.match(buf, pos)
1218 if not match:
1219 break
1220
1221 length, keyword = match.groups()
1222 length = int(length)
1223 value = buf[match.end(2) + 1:match.start(1) + length - 1]
1224
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001225 # Normally, we could just use "utf-8" as the encoding and "strict"
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001226 # as the error handler, but we better not take the risk. For
1227 # example, GNU tar <= 1.23 is known to store filenames it cannot
1228 # translate to UTF-8 as raw strings (unfortunately without a
1229 # hdrcharset=BINARY header).
1230 # We first try the strict standard encoding, and if that fails we
1231 # fall back on the user's encoding and error handler.
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001232 keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001233 tarfile.errors)
1234 if keyword in PAX_NAME_FIELDS:
1235 value = self._decode_pax_field(value, encoding, tarfile.encoding,
1236 tarfile.errors)
1237 else:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001238 value = self._decode_pax_field(value, "utf-8", "utf-8",
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001239 tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001240
1241 pax_headers[keyword] = value
1242 pos += length
1243
Guido van Rossume7ba4952007-06-06 23:52:48 +00001244 # Fetch the next header.
Lars Gustäbel9520a432009-11-22 18:48:49 +00001245 try:
1246 next = self.fromtarfile(tarfile)
1247 except HeaderError:
1248 raise SubsequentHeaderError("missing or bad subsequent header")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001249
Lars Gustäbel9cbdd752010-10-29 09:08:19 +00001250 # Process GNU sparse information.
1251 if "GNU.sparse.map" in pax_headers:
1252 # GNU extended sparse format version 0.1.
1253 self._proc_gnusparse_01(next, pax_headers)
1254
1255 elif "GNU.sparse.size" in pax_headers:
1256 # GNU extended sparse format version 0.0.
1257 self._proc_gnusparse_00(next, pax_headers, buf)
1258
1259 elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
1260 # GNU extended sparse format version 1.0.
1261 self._proc_gnusparse_10(next, pax_headers, tarfile)
1262
Guido van Rossume7ba4952007-06-06 23:52:48 +00001263 if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001264 # Patch the TarInfo object with the extended header info.
1265 next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
1266 next.offset = self.offset
1267
1268 if "size" in pax_headers:
1269 # If the extended header replaces the size field,
1270 # we need to recalculate the offset where the next
1271 # header starts.
1272 offset = next.offset_data
1273 if next.isreg() or next.type not in SUPPORTED_TYPES:
1274 offset += next._block(next.size)
1275 tarfile.offset = offset
1276
1277 return next
1278
Lars Gustäbel9cbdd752010-10-29 09:08:19 +00001279 def _proc_gnusparse_00(self, next, pax_headers, buf):
1280 """Process a GNU tar extended sparse header, version 0.0.
1281 """
1282 offsets = []
1283 for match in re.finditer(br"\d+ GNU.sparse.offset=(\d+)\n", buf):
1284 offsets.append(int(match.group(1)))
1285 numbytes = []
1286 for match in re.finditer(br"\d+ GNU.sparse.numbytes=(\d+)\n", buf):
1287 numbytes.append(int(match.group(1)))
1288 next.sparse = list(zip(offsets, numbytes))
1289
1290 def _proc_gnusparse_01(self, next, pax_headers):
1291 """Process a GNU tar extended sparse header, version 0.1.
1292 """
1293 sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")]
1294 next.sparse = list(zip(sparse[::2], sparse[1::2]))
1295
1296 def _proc_gnusparse_10(self, next, pax_headers, tarfile):
1297 """Process a GNU tar extended sparse header, version 1.0.
1298 """
1299 fields = None
1300 sparse = []
1301 buf = tarfile.fileobj.read(BLOCKSIZE)
1302 fields, buf = buf.split(b"\n", 1)
1303 fields = int(fields)
1304 while len(sparse) < fields * 2:
1305 if b"\n" not in buf:
1306 buf += tarfile.fileobj.read(BLOCKSIZE)
1307 number, buf = buf.split(b"\n", 1)
1308 sparse.append(int(number))
1309 next.offset_data = tarfile.fileobj.tell()
1310 next.sparse = list(zip(sparse[::2], sparse[1::2]))
1311
Guido van Rossume7ba4952007-06-06 23:52:48 +00001312 def _apply_pax_info(self, pax_headers, encoding, errors):
1313 """Replace fields with supplemental information from a previous
1314 pax extended or global header.
1315 """
1316 for keyword, value in pax_headers.items():
Lars Gustäbel9cbdd752010-10-29 09:08:19 +00001317 if keyword == "GNU.sparse.name":
1318 setattr(self, "path", value)
1319 elif keyword == "GNU.sparse.size":
1320 setattr(self, "size", int(value))
1321 elif keyword == "GNU.sparse.realsize":
1322 setattr(self, "size", int(value))
1323 elif keyword in PAX_FIELDS:
1324 if keyword in PAX_NUMBER_FIELDS:
1325 try:
1326 value = PAX_NUMBER_FIELDS[keyword](value)
1327 except ValueError:
1328 value = 0
1329 if keyword == "path":
1330 value = value.rstrip("/")
1331 setattr(self, keyword, value)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001332
1333 self.pax_headers = pax_headers.copy()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001334
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001335 def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
1336 """Decode a single field from a pax record.
1337 """
1338 try:
1339 return value.decode(encoding, "strict")
1340 except UnicodeDecodeError:
1341 return value.decode(fallback_encoding, fallback_errors)
1342
Guido van Rossumd8faa362007-04-27 19:54:29 +00001343 def _block(self, count):
1344 """Round up a byte count by BLOCKSIZE and return it,
1345 e.g. _block(834) => 1024.
1346 """
1347 blocks, remainder = divmod(count, BLOCKSIZE)
1348 if remainder:
1349 blocks += 1
1350 return blocks * BLOCKSIZE
Thomas Wouters89f507f2006-12-13 04:49:30 +00001351
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001352 def isreg(self):
1353 return self.type in REGULAR_TYPES
1354 def isfile(self):
1355 return self.isreg()
1356 def isdir(self):
1357 return self.type == DIRTYPE
1358 def issym(self):
1359 return self.type == SYMTYPE
1360 def islnk(self):
1361 return self.type == LNKTYPE
1362 def ischr(self):
1363 return self.type == CHRTYPE
1364 def isblk(self):
1365 return self.type == BLKTYPE
1366 def isfifo(self):
1367 return self.type == FIFOTYPE
1368 def issparse(self):
Lars Gustäbel9cbdd752010-10-29 09:08:19 +00001369 return self.sparse is not None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001370 def isdev(self):
1371 return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
1372# class TarInfo
1373
1374class TarFile(object):
1375 """The TarFile Class provides an interface to tar archives.
1376 """
1377
1378 debug = 0 # May be set from 0 (no msgs) to 3 (all msgs)
1379
1380 dereference = False # If true, add content of linked file to the
1381 # tar file, else the link.
1382
1383 ignore_zeros = False # If true, skips empty or invalid blocks and
1384 # continues processing.
1385
Lars Gustäbel365aff32009-12-13 11:42:29 +00001386 errorlevel = 1 # If 0, fatal errors only appear in debug
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001387 # messages (if debug >= 0). If > 0, errors
1388 # are passed to the caller as exceptions.
1389
Guido van Rossumd8faa362007-04-27 19:54:29 +00001390 format = DEFAULT_FORMAT # The format to use when creating an archive.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001391
Guido van Rossume7ba4952007-06-06 23:52:48 +00001392 encoding = ENCODING # Encoding for 8-bit character strings.
1393
1394 errors = None # Error handler for unicode conversion.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001395
Guido van Rossumd8faa362007-04-27 19:54:29 +00001396 tarinfo = TarInfo # The default TarInfo class to use.
1397
Lars Gustäbelb062a2f2012-05-14 13:18:16 +02001398 fileobject = ExFileObject # The file-object for extractfile().
Guido van Rossumd8faa362007-04-27 19:54:29 +00001399
1400 def __init__(self, name=None, mode="r", fileobj=None, format=None,
1401 tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
Victor Stinnerde629d42010-05-05 21:43:57 +00001402 errors="surrogateescape", pax_headers=None, debug=None, errorlevel=None):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001403 """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
1404 read from an existing archive, 'a' to append data to an existing
1405 file or 'w' to create a new file overwriting an existing one. `mode'
1406 defaults to 'r'.
1407 If `fileobj' is given, it is used for reading or writing data. If it
1408 can be determined, `mode' is overridden by `fileobj's mode.
1409 `fileobj' is not closed, when TarFile is closed.
1410 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001411 modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +02001412 if mode not in modes:
Berker Peksag0fe63252015-02-13 21:02:12 +02001413 raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001414 self.mode = mode
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +02001415 self._mode = modes[mode]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001416
1417 if not fileobj:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001418 if self.mode == "a" and not os.path.exists(name):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001419 # Create nonexistent files in append mode.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001420 self.mode = "w"
1421 self._mode = "wb"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001422 fileobj = bltn_open(name, self._mode)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001423 self._extfileobj = False
1424 else:
Serhiy Storchaka2c6a3ae2014-07-16 23:58:58 +03001425 if (name is None and hasattr(fileobj, "name") and
1426 isinstance(fileobj.name, (str, bytes))):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001427 name = fileobj.name
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001428 if hasattr(fileobj, "mode"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429 self._mode = fileobj.mode
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001430 self._extfileobj = True
Thomas Woutersed03b412007-08-28 21:37:11 +00001431 self.name = os.path.abspath(name) if name else None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001432 self.fileobj = fileobj
1433
Guido van Rossumd8faa362007-04-27 19:54:29 +00001434 # Init attributes.
1435 if format is not None:
1436 self.format = format
1437 if tarinfo is not None:
1438 self.tarinfo = tarinfo
1439 if dereference is not None:
1440 self.dereference = dereference
1441 if ignore_zeros is not None:
1442 self.ignore_zeros = ignore_zeros
1443 if encoding is not None:
1444 self.encoding = encoding
Victor Stinnerde629d42010-05-05 21:43:57 +00001445 self.errors = errors
Guido van Rossume7ba4952007-06-06 23:52:48 +00001446
1447 if pax_headers is not None and self.format == PAX_FORMAT:
1448 self.pax_headers = pax_headers
1449 else:
1450 self.pax_headers = {}
1451
Guido van Rossumd8faa362007-04-27 19:54:29 +00001452 if debug is not None:
1453 self.debug = debug
1454 if errorlevel is not None:
1455 self.errorlevel = errorlevel
1456
1457 # Init datastructures.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001458 self.closed = False
1459 self.members = [] # list of members as TarInfo objects
1460 self._loaded = False # flag if all members have been read
Christian Heimesd8654cf2007-12-02 15:22:16 +00001461 self.offset = self.fileobj.tell()
1462 # current position in the archive file
Thomas Wouters477c8d52006-05-27 19:21:47 +00001463 self.inodes = {} # dictionary caching the inodes of
1464 # archive members already added
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001465
Lars Gustäbel7b465392009-11-18 20:29:25 +00001466 try:
1467 if self.mode == "r":
1468 self.firstmember = None
1469 self.firstmember = self.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001470
Lars Gustäbel7b465392009-11-18 20:29:25 +00001471 if self.mode == "a":
1472 # Move to the end of the archive,
1473 # before the first empty block.
Lars Gustäbel7b465392009-11-18 20:29:25 +00001474 while True:
Lars Gustäbel9520a432009-11-22 18:48:49 +00001475 self.fileobj.seek(self.offset)
1476 try:
1477 tarinfo = self.tarinfo.fromtarfile(self)
1478 self.members.append(tarinfo)
1479 except EOFHeaderError:
1480 self.fileobj.seek(self.offset)
Lars Gustäbel7b465392009-11-18 20:29:25 +00001481 break
Lars Gustäbel9520a432009-11-22 18:48:49 +00001482 except HeaderError as e:
1483 raise ReadError(str(e))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001484
Lars Gustäbel20703c62015-05-27 12:53:44 +02001485 if self.mode in ("a", "w", "x"):
Lars Gustäbel7b465392009-11-18 20:29:25 +00001486 self._loaded = True
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001487
Lars Gustäbel7b465392009-11-18 20:29:25 +00001488 if self.pax_headers:
1489 buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
1490 self.fileobj.write(buf)
1491 self.offset += len(buf)
1492 except:
1493 if not self._extfileobj:
1494 self.fileobj.close()
1495 self.closed = True
1496 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001498 #--------------------------------------------------------------------------
1499 # Below are the classmethods which act as alternate constructors to the
1500 # TarFile class. The open() method is the only one that is needed for
1501 # public use; it is the "super"-constructor and is able to select an
1502 # adequate "sub"-constructor for a particular compression using the mapping
1503 # from OPEN_METH.
1504 #
1505 # This concept allows one to subclass TarFile without losing the comfort of
1506 # the super-constructor. A sub-constructor is registered and made available
1507 # by adding it to the mapping in OPEN_METH.
1508
Guido van Rossum75b64e62005-01-16 00:16:11 +00001509 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001510 def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001511 """Open a tar archive for reading, writing or appending. Return
1512 an appropriate TarFile class.
1513
1514 mode:
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001515 'r' or 'r:*' open for reading with transparent compression
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001516 'r:' open for reading exclusively uncompressed
1517 'r:gz' open for reading with gzip compression
1518 'r:bz2' open for reading with bzip2 compression
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001519 'r:xz' open for reading with lzma compression
Thomas Wouterscf297e42007-02-23 15:07:44 +00001520 'a' or 'a:' open for appending, creating the file if necessary
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001521 'w' or 'w:' open for writing without compression
1522 'w:gz' open for writing with gzip compression
1523 'w:bz2' open for writing with bzip2 compression
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001524 'w:xz' open for writing with lzma compression
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001525
Berker Peksag0fe63252015-02-13 21:02:12 +02001526 'x' or 'x:' create a tarfile exclusively without compression, raise
1527 an exception if the file is already created
1528 'x:gz' create an gzip compressed tarfile, raise an exception
1529 if the file is already created
1530 'x:bz2' create an bzip2 compressed tarfile, raise an exception
1531 if the file is already created
1532 'x:xz' create an lzma compressed tarfile, raise an exception
1533 if the file is already created
1534
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001535 'r|*' open a stream of tar blocks with transparent compression
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001536 'r|' open an uncompressed stream of tar blocks for reading
1537 'r|gz' open a gzip compressed stream of tar blocks
1538 'r|bz2' open a bzip2 compressed stream of tar blocks
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001539 'r|xz' open an lzma compressed stream of tar blocks
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001540 'w|' open an uncompressed stream for writing
1541 'w|gz' open a gzip compressed stream for writing
1542 'w|bz2' open a bzip2 compressed stream for writing
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001543 'w|xz' open an lzma compressed stream for writing
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001544 """
1545
1546 if not name and not fileobj:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001547 raise ValueError("nothing to open")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001548
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001549 if mode in ("r", "r:*"):
1550 # Find out which *open() is appropriate for opening the file.
1551 for comptype in cls.OPEN_METH:
1552 func = getattr(cls, cls.OPEN_METH[comptype])
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001553 if fileobj is not None:
1554 saved_pos = fileobj.tell()
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001555 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001556 return func(name, "r", fileobj, **kwargs)
1557 except (ReadError, CompressionError) as e:
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001558 if fileobj is not None:
1559 fileobj.seek(saved_pos)
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001560 continue
Thomas Wouters477c8d52006-05-27 19:21:47 +00001561 raise ReadError("file could not be opened successfully")
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001562
1563 elif ":" in mode:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001564 filemode, comptype = mode.split(":", 1)
1565 filemode = filemode or "r"
1566 comptype = comptype or "tar"
1567
1568 # Select the *open() function according to
1569 # given compression.
1570 if comptype in cls.OPEN_METH:
1571 func = getattr(cls, cls.OPEN_METH[comptype])
1572 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573 raise CompressionError("unknown compression type %r" % comptype)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001574 return func(name, filemode, fileobj, **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001575
1576 elif "|" in mode:
1577 filemode, comptype = mode.split("|", 1)
1578 filemode = filemode or "r"
1579 comptype = comptype or "tar"
1580
Serhiy Storchaka53ad0cd2014-01-18 15:35:37 +02001581 if filemode not in ("r", "w"):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001582 raise ValueError("mode must be 'r' or 'w'")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001583
Antoine Pitrou605c2932010-09-23 20:15:14 +00001584 stream = _Stream(name, filemode, comptype, fileobj, bufsize)
1585 try:
1586 t = cls(name, filemode, stream, **kwargs)
1587 except:
1588 stream.close()
1589 raise
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001590 t._extfileobj = False
1591 return t
1592
Berker Peksag0fe63252015-02-13 21:02:12 +02001593 elif mode in ("a", "w", "x"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001594 return cls.taropen(name, mode, fileobj, **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001595
Thomas Wouters477c8d52006-05-27 19:21:47 +00001596 raise ValueError("undiscernible mode")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001597
Guido van Rossum75b64e62005-01-16 00:16:11 +00001598 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001599 def taropen(cls, name, mode="r", fileobj=None, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001600 """Open uncompressed tar archive name for reading or writing.
1601 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001602 if mode not in ("r", "a", "w", "x"):
1603 raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001604 return cls(name, mode, fileobj, **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001605
Guido van Rossum75b64e62005-01-16 00:16:11 +00001606 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001607 def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001608 """Open gzip compressed tar archive name for reading or writing.
1609 Appending is not allowed.
1610 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001611 if mode not in ("r", "w", "x"):
1612 raise ValueError("mode must be 'r', 'w' or 'x'")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001613
1614 try:
1615 import gzip
Neal Norwitz4ec68242003-04-11 03:05:56 +00001616 gzip.GzipFile
1617 except (ImportError, AttributeError):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618 raise CompressionError("gzip module is not available")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001619
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001620 try:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001621 fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj)
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001622 except OSError:
1623 if fileobj is not None and mode == 'r':
1624 raise ReadError("not a gzip file")
1625 raise
1626
1627 try:
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001628 t = cls.taropen(name, mode, fileobj, **kwargs)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001629 except OSError:
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001630 fileobj.close()
1631 if mode == 'r':
1632 raise ReadError("not a gzip file")
1633 raise
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001634 except:
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001635 fileobj.close()
Antoine Pitroue1eca4e2010-10-29 23:49:49 +00001636 raise
Serhiy Storchaka9fbec7a2014-01-18 15:53:05 +02001637 t._extfileobj = False
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001638 return t
1639
Guido van Rossum75b64e62005-01-16 00:16:11 +00001640 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001641 def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001642 """Open bzip2 compressed tar archive name for reading or writing.
1643 Appending is not allowed.
1644 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001645 if mode not in ("r", "w", "x"):
1646 raise ValueError("mode must be 'r', 'w' or 'x'")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001647
1648 try:
1649 import bz2
Brett Cannoncd171c82013-07-04 17:43:24 -04001650 except ImportError:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651 raise CompressionError("bz2 module is not available")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001652
Nadeem Vawdaaebcdba2012-06-04 23:31:20 +02001653 fileobj = bz2.BZ2File(fileobj or name, mode,
1654 compresslevel=compresslevel)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001655
1656 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001657 t = cls.taropen(name, mode, fileobj, **kwargs)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001658 except (OSError, EOFError):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001659 fileobj.close()
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001660 if mode == 'r':
1661 raise ReadError("not a bzip2 file")
1662 raise
Serhiy Storchakae413cde2014-01-18 16:28:08 +02001663 except:
1664 fileobj.close()
1665 raise
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001666 t._extfileobj = False
1667 return t
1668
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001669 @classmethod
Lars Gustäbelc5e11992012-01-18 14:01:17 +01001670 def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001671 """Open lzma compressed tar archive name for reading or writing.
1672 Appending is not allowed.
1673 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001674 if mode not in ("r", "w", "x"):
1675 raise ValueError("mode must be 'r', 'w' or 'x'")
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001676
1677 try:
1678 import lzma
Brett Cannoncd171c82013-07-04 17:43:24 -04001679 except ImportError:
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001680 raise CompressionError("lzma module is not available")
1681
Nadeem Vawda33c34da2012-06-04 23:34:07 +02001682 fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset)
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001683
1684 try:
1685 t = cls.taropen(name, mode, fileobj, **kwargs)
1686 except (lzma.LZMAError, EOFError):
1687 fileobj.close()
Serhiy Storchakac2d01422014-01-18 16:14:10 +02001688 if mode == 'r':
1689 raise ReadError("not an lzma file")
1690 raise
Serhiy Storchakae413cde2014-01-18 16:28:08 +02001691 except:
1692 fileobj.close()
1693 raise
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001694 t._extfileobj = False
1695 return t
1696
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001697 # All *open() methods are registered here.
1698 OPEN_METH = {
1699 "tar": "taropen", # uncompressed tar
1700 "gz": "gzopen", # gzip compressed tar
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +01001701 "bz2": "bz2open", # bzip2 compressed tar
1702 "xz": "xzopen" # lzma compressed tar
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001703 }
1704
1705 #--------------------------------------------------------------------------
1706 # The public methods which TarFile provides:
1707
1708 def close(self):
1709 """Close the TarFile. In write-mode, two finishing zero blocks are
1710 appended to the archive.
1711 """
1712 if self.closed:
1713 return
1714
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001715 self.closed = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +03001716 try:
Lars Gustäbel20703c62015-05-27 12:53:44 +02001717 if self.mode in ("a", "w", "x"):
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +03001718 self.fileobj.write(NUL * (BLOCKSIZE * 2))
1719 self.offset += (BLOCKSIZE * 2)
1720 # fill up the end with zero-blocks
1721 # (like option -b20 for tar does)
1722 blocks, remainder = divmod(self.offset, RECORDSIZE)
1723 if remainder > 0:
1724 self.fileobj.write(NUL * (RECORDSIZE - remainder))
1725 finally:
1726 if not self._extfileobj:
1727 self.fileobj.close()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001728
1729 def getmember(self, name):
1730 """Return a TarInfo object for member `name'. If `name' can not be
1731 found in the archive, KeyError is raised. If a member occurs more
Mark Dickinson934896d2009-02-21 20:59:32 +00001732 than once in the archive, its last occurrence is assumed to be the
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001733 most up-to-date version.
1734 """
Martin v. Löwisf3c56112004-09-18 09:08:52 +00001735 tarinfo = self._getmember(name)
1736 if tarinfo is None:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001737 raise KeyError("filename %r not found" % name)
Martin v. Löwisf3c56112004-09-18 09:08:52 +00001738 return tarinfo
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001739
1740 def getmembers(self):
1741 """Return the members of the archive as a list of TarInfo objects. The
1742 list has the same order as the members in the archive.
1743 """
1744 self._check()
1745 if not self._loaded: # if we want to obtain a list of
1746 self._load() # all members, we first have to
1747 # scan the whole archive.
1748 return self.members
1749
1750 def getnames(self):
1751 """Return the members of the archive as a list of their names. It has
1752 the same order as the list returned by getmembers().
1753 """
Martin v. Löwisf3c56112004-09-18 09:08:52 +00001754 return [tarinfo.name for tarinfo in self.getmembers()]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001755
1756 def gettarinfo(self, name=None, arcname=None, fileobj=None):
1757 """Create a TarInfo object for either the file `name' or the file
1758 object `fileobj' (using os.fstat on its file descriptor). You can
1759 modify some of the TarInfo's attributes before you add it using
1760 addfile(). If given, `arcname' specifies an alternative name for the
1761 file in the archive.
1762 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001763 self._check("awx")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001764
1765 # When fileobj is given, replace name by
1766 # fileobj's real name.
1767 if fileobj is not None:
1768 name = fileobj.name
1769
1770 # Building the name of the member in the archive.
1771 # Backward slashes are converted to forward slashes,
1772 # Absolute paths are turned to relative paths.
1773 if arcname is None:
1774 arcname = name
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001775 drv, arcname = os.path.splitdrive(arcname)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001776 arcname = arcname.replace(os.sep, "/")
1777 arcname = arcname.lstrip("/")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001778
1779 # Now, fill the TarInfo object with
1780 # information specific for the file.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001781 tarinfo = self.tarinfo()
1782 tarinfo.tarfile = self
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001783
1784 # Use os.stat or os.lstat, depending on platform
1785 # and if symlinks shall be resolved.
1786 if fileobj is None:
1787 if hasattr(os, "lstat") and not self.dereference:
1788 statres = os.lstat(name)
1789 else:
1790 statres = os.stat(name)
1791 else:
1792 statres = os.fstat(fileobj.fileno())
1793 linkname = ""
1794
1795 stmd = statres.st_mode
1796 if stat.S_ISREG(stmd):
1797 inode = (statres.st_ino, statres.st_dev)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001798 if not self.dereference and statres.st_nlink > 1 and \
1799 inode in self.inodes and arcname != self.inodes[inode]:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001800 # Is it a hardlink to an already
1801 # archived file?
1802 type = LNKTYPE
1803 linkname = self.inodes[inode]
1804 else:
1805 # The inode is added only if its valid.
1806 # For win32 it is always 0.
1807 type = REGTYPE
1808 if inode[0]:
1809 self.inodes[inode] = arcname
1810 elif stat.S_ISDIR(stmd):
1811 type = DIRTYPE
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001812 elif stat.S_ISFIFO(stmd):
1813 type = FIFOTYPE
1814 elif stat.S_ISLNK(stmd):
1815 type = SYMTYPE
1816 linkname = os.readlink(name)
1817 elif stat.S_ISCHR(stmd):
1818 type = CHRTYPE
1819 elif stat.S_ISBLK(stmd):
1820 type = BLKTYPE
1821 else:
1822 return None
1823
1824 # Fill the TarInfo object with all
1825 # information we can get.
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001826 tarinfo.name = arcname
1827 tarinfo.mode = stmd
1828 tarinfo.uid = statres.st_uid
1829 tarinfo.gid = statres.st_gid
Lars Gustäbel2470ff12010-06-03 10:11:52 +00001830 if type == REGTYPE:
Martin v. Löwis61d77e02004-08-20 06:35:46 +00001831 tarinfo.size = statres.st_size
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001832 else:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001833 tarinfo.size = 0
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001834 tarinfo.mtime = statres.st_mtime
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001835 tarinfo.type = type
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001836 tarinfo.linkname = linkname
1837 if pwd:
1838 try:
1839 tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
1840 except KeyError:
1841 pass
1842 if grp:
1843 try:
1844 tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
1845 except KeyError:
1846 pass
1847
1848 if type in (CHRTYPE, BLKTYPE):
1849 if hasattr(os, "major") and hasattr(os, "minor"):
1850 tarinfo.devmajor = os.major(statres.st_rdev)
1851 tarinfo.devminor = os.minor(statres.st_rdev)
1852 return tarinfo
1853
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +03001854 def list(self, verbose=True, *, members=None):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001855 """Print a table of contents to sys.stdout. If `verbose' is False, only
1856 the names of the members are printed. If it is True, an `ls -l'-like
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +03001857 output is produced. `members' is optional and must be a subset of the
1858 list returned by getmembers().
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001859 """
1860 self._check()
1861
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +03001862 if members is None:
1863 members = self
1864 for tarinfo in members:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001865 if verbose:
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +02001866 _safe_print(stat.filemode(tarinfo.mode))
1867 _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid,
1868 tarinfo.gname or tarinfo.gid))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001869 if tarinfo.ischr() or tarinfo.isblk():
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +02001870 _safe_print("%10s" %
1871 ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor)))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001872 else:
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +02001873 _safe_print("%10d" % tarinfo.size)
1874 _safe_print("%d-%02d-%02d %02d:%02d:%02d" \
1875 % time.localtime(tarinfo.mtime)[:6])
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001876
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +02001877 _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else ""))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001878
1879 if verbose:
1880 if tarinfo.issym():
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +02001881 _safe_print("-> " + tarinfo.linkname)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001882 if tarinfo.islnk():
Serhiy Storchaka3b4f1592014-02-05 20:53:36 +02001883 _safe_print("link to " + tarinfo.linkname)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001884 print()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001885
Raymond Hettingera63a3122011-01-26 20:34:14 +00001886 def add(self, name, arcname=None, recursive=True, exclude=None, *, filter=None):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001887 """Add the file `name' to the archive. `name' may be any type of file
1888 (directory, fifo, symbolic link, etc.). If given, `arcname'
1889 specifies an alternative name for the file in the archive.
1890 Directories are added recursively by default. This can be avoided by
Guido van Rossum486364b2007-06-30 05:01:58 +00001891 setting `recursive' to False. `exclude' is a function that should
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001892 return True for each filename to be excluded. `filter' is a function
1893 that expects a TarInfo object argument and returns the changed
1894 TarInfo object, if it returns None the TarInfo object will be
1895 excluded from the archive.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001896 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001897 self._check("awx")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001898
1899 if arcname is None:
1900 arcname = name
1901
Guido van Rossum486364b2007-06-30 05:01:58 +00001902 # Exclude pathnames.
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001903 if exclude is not None:
1904 import warnings
1905 warnings.warn("use the filter argument instead",
1906 DeprecationWarning, 2)
1907 if exclude(name):
1908 self._dbg(2, "tarfile: Excluded %r" % name)
1909 return
Guido van Rossum486364b2007-06-30 05:01:58 +00001910
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001911 # Skip if somebody tries to archive the archive...
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001912 if self.name is not None and os.path.abspath(name) == self.name:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001913 self._dbg(2, "tarfile: Skipped %r" % name)
1914 return
1915
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001916 self._dbg(1, name)
1917
1918 # Create a TarInfo object from the file.
1919 tarinfo = self.gettarinfo(name, arcname)
1920
1921 if tarinfo is None:
1922 self._dbg(1, "tarfile: Unsupported type %r" % name)
1923 return
1924
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001925 # Change or exclude the TarInfo object.
1926 if filter is not None:
1927 tarinfo = filter(tarinfo)
1928 if tarinfo is None:
1929 self._dbg(2, "tarfile: Excluded %r" % name)
1930 return
1931
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001932 # Append the tar header and data to the archive.
1933 if tarinfo.isreg():
Andrew Svetlov718df1d2012-11-29 14:20:47 +02001934 with bltn_open(name, "rb") as f:
1935 self.addfile(tarinfo, f)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001936
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001937 elif tarinfo.isdir():
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001938 self.addfile(tarinfo)
1939 if recursive:
1940 for f in os.listdir(name):
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001941 self.add(os.path.join(name, f), os.path.join(arcname, f),
Raymond Hettingera63a3122011-01-26 20:34:14 +00001942 recursive, exclude, filter=filter)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001943
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001944 else:
1945 self.addfile(tarinfo)
1946
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001947 def addfile(self, tarinfo, fileobj=None):
1948 """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
1949 given, tarinfo.size bytes are read from it and added to the archive.
1950 You can create TarInfo objects using gettarinfo().
1951 On Windows platforms, `fileobj' should always be opened with mode
1952 'rb' to avoid irritation about the file size.
1953 """
Berker Peksag0fe63252015-02-13 21:02:12 +02001954 self._check("awx")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001955
Thomas Wouters89f507f2006-12-13 04:49:30 +00001956 tarinfo = copy.copy(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001957
Guido van Rossume7ba4952007-06-06 23:52:48 +00001958 buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001959 self.fileobj.write(buf)
1960 self.offset += len(buf)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001961
1962 # If there's data to follow, append it.
1963 if fileobj is not None:
1964 copyfileobj(fileobj, self.fileobj, tarinfo.size)
1965 blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
1966 if remainder > 0:
1967 self.fileobj.write(NUL * (BLOCKSIZE - remainder))
1968 blocks += 1
1969 self.offset += blocks * BLOCKSIZE
1970
Martin v. Löwisf3c56112004-09-18 09:08:52 +00001971 self.members.append(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001972
Eric V. Smith7a803892015-04-15 10:27:58 -04001973 def extractall(self, path=".", members=None, *, numeric_owner=False):
Martin v. Löwis00a73e72005-03-04 19:40:34 +00001974 """Extract all members from the archive to the current working
1975 directory and set owner, modification time and permissions on
1976 directories afterwards. `path' specifies a different directory
1977 to extract to. `members' is optional and must be a subset of the
Eric V. Smith7a803892015-04-15 10:27:58 -04001978 list returned by getmembers(). If `numeric_owner` is True, only
1979 the numbers for user/group names are used and not the names.
Martin v. Löwis00a73e72005-03-04 19:40:34 +00001980 """
1981 directories = []
1982
1983 if members is None:
1984 members = self
1985
1986 for tarinfo in members:
1987 if tarinfo.isdir():
Christian Heimes2202f872008-02-06 14:31:34 +00001988 # Extract directories with a safe mode.
Martin v. Löwis00a73e72005-03-04 19:40:34 +00001989 directories.append(tarinfo)
Christian Heimes2202f872008-02-06 14:31:34 +00001990 tarinfo = copy.copy(tarinfo)
1991 tarinfo.mode = 0o700
Martin v. Löwis16f344d2010-11-01 21:39:13 +00001992 # Do not set_attrs directories, as we will do that further down
Eric V. Smith7a803892015-04-15 10:27:58 -04001993 self.extract(tarinfo, path, set_attrs=not tarinfo.isdir(),
1994 numeric_owner=numeric_owner)
Martin v. Löwis00a73e72005-03-04 19:40:34 +00001995
1996 # Reverse sort directories.
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00001997 directories.sort(key=lambda a: a.name)
Martin v. Löwis00a73e72005-03-04 19:40:34 +00001998 directories.reverse()
1999
2000 # Set correct owner, mtime and filemode on directories.
2001 for tarinfo in directories:
Christian Heimesfaf2f632008-01-06 16:59:19 +00002002 dirpath = os.path.join(path, tarinfo.name)
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002003 try:
Eric V. Smith7a803892015-04-15 10:27:58 -04002004 self.chown(tarinfo, dirpath, numeric_owner=numeric_owner)
Christian Heimesfaf2f632008-01-06 16:59:19 +00002005 self.utime(tarinfo, dirpath)
2006 self.chmod(tarinfo, dirpath)
Guido van Rossumb940e112007-01-10 16:19:56 +00002007 except ExtractError as e:
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002008 if self.errorlevel > 1:
2009 raise
2010 else:
2011 self._dbg(1, "tarfile: %s" % e)
2012
Eric V. Smith7a803892015-04-15 10:27:58 -04002013 def extract(self, member, path="", set_attrs=True, *, numeric_owner=False):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002014 """Extract a member from the archive to the current working directory,
2015 using its full name. Its file information is extracted as accurately
2016 as possible. `member' may be a filename or a TarInfo object. You can
Martin v. Löwis16f344d2010-11-01 21:39:13 +00002017 specify a different directory using `path'. File attributes (owner,
Eric V. Smith7a803892015-04-15 10:27:58 -04002018 mtime, mode) are set unless `set_attrs' is False. If `numeric_owner`
2019 is True, only the numbers for user/group names are used and not
2020 the names.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002021 """
2022 self._check("r")
2023
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002024 if isinstance(member, str):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002025 tarinfo = self.getmember(member)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002026 else:
2027 tarinfo = member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002028
Neal Norwitza4f651a2004-07-20 22:07:44 +00002029 # Prepare the link target for makelink().
2030 if tarinfo.islnk():
2031 tarinfo._link_target = os.path.join(path, tarinfo.linkname)
2032
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002033 try:
Martin v. Löwis16f344d2010-11-01 21:39:13 +00002034 self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
Eric V. Smith7a803892015-04-15 10:27:58 -04002035 set_attrs=set_attrs,
2036 numeric_owner=numeric_owner)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002037 except OSError as e:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002038 if self.errorlevel > 0:
2039 raise
2040 else:
2041 if e.filename is None:
2042 self._dbg(1, "tarfile: %s" % e.strerror)
2043 else:
2044 self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
Guido van Rossumb940e112007-01-10 16:19:56 +00002045 except ExtractError as e:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002046 if self.errorlevel > 1:
2047 raise
2048 else:
2049 self._dbg(1, "tarfile: %s" % e)
2050
2051 def extractfile(self, member):
2052 """Extract a member from the archive as a file object. `member' may be
Lars Gustäbel7a919e92012-05-05 18:15:03 +02002053 a filename or a TarInfo object. If `member' is a regular file or a
2054 link, an io.BufferedReader object is returned. Otherwise, None is
2055 returned.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002056 """
2057 self._check("r")
2058
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002059 if isinstance(member, str):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002060 tarinfo = self.getmember(member)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002061 else:
2062 tarinfo = member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002063
Lars Gustäbel7a919e92012-05-05 18:15:03 +02002064 if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
2065 # Members with unknown types are treated as regular files.
Lars Gustäbelb062a2f2012-05-14 13:18:16 +02002066 return self.fileobject(self, tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002067
2068 elif tarinfo.islnk() or tarinfo.issym():
2069 if isinstance(self.fileobj, _Stream):
2070 # A small but ugly workaround for the case that someone tries
2071 # to extract a (sym)link as a file-object from a non-seekable
2072 # stream of tar blocks.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002073 raise StreamError("cannot extract (sym)link as file object")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002074 else:
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00002075 # A (sym)link's file object is its target's file object.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002076 return self.extractfile(self._find_link_target(tarinfo))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002077 else:
2078 # If there's no data associated with the member (directory, chrdev,
2079 # blkdev, etc.), return None instead of a file object.
2080 return None
2081
Eric V. Smith7a803892015-04-15 10:27:58 -04002082 def _extract_member(self, tarinfo, targetpath, set_attrs=True,
2083 numeric_owner=False):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002084 """Extract the TarInfo object tarinfo to a physical
2085 file called targetpath.
2086 """
2087 # Fetch the TarInfo object for the given name
2088 # and build the destination pathname, replacing
2089 # forward slashes to platform specific separators.
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00002090 targetpath = targetpath.rstrip("/")
2091 targetpath = targetpath.replace("/", os.sep)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002092
2093 # Create all upper directories.
2094 upperdirs = os.path.dirname(targetpath)
2095 if upperdirs and not os.path.exists(upperdirs):
Christian Heimes2202f872008-02-06 14:31:34 +00002096 # Create directories that are not part of the archive with
2097 # default permissions.
Thomas Woutersb2137042007-02-01 18:02:27 +00002098 os.makedirs(upperdirs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002099
2100 if tarinfo.islnk() or tarinfo.issym():
2101 self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
2102 else:
2103 self._dbg(1, tarinfo.name)
2104
2105 if tarinfo.isreg():
2106 self.makefile(tarinfo, targetpath)
2107 elif tarinfo.isdir():
2108 self.makedir(tarinfo, targetpath)
2109 elif tarinfo.isfifo():
2110 self.makefifo(tarinfo, targetpath)
2111 elif tarinfo.ischr() or tarinfo.isblk():
2112 self.makedev(tarinfo, targetpath)
2113 elif tarinfo.islnk() or tarinfo.issym():
2114 self.makelink(tarinfo, targetpath)
2115 elif tarinfo.type not in SUPPORTED_TYPES:
2116 self.makeunknown(tarinfo, targetpath)
2117 else:
2118 self.makefile(tarinfo, targetpath)
2119
Martin v. Löwis16f344d2010-11-01 21:39:13 +00002120 if set_attrs:
Eric V. Smith7a803892015-04-15 10:27:58 -04002121 self.chown(tarinfo, targetpath, numeric_owner)
Martin v. Löwis16f344d2010-11-01 21:39:13 +00002122 if not tarinfo.issym():
2123 self.chmod(tarinfo, targetpath)
2124 self.utime(tarinfo, targetpath)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002125
2126 #--------------------------------------------------------------------------
2127 # Below are the different file methods. They are called via
2128 # _extract_member() when extract() is called. They can be replaced in a
2129 # subclass to implement other functionality.
2130
2131 def makedir(self, tarinfo, targetpath):
2132 """Make a directory called targetpath.
2133 """
2134 try:
Christian Heimes2202f872008-02-06 14:31:34 +00002135 # Use a safe mode for the directory, the real mode is set
2136 # later in _extract_member().
2137 os.mkdir(targetpath, 0o700)
Florent Xicluna68f71a32011-10-28 16:06:23 +02002138 except FileExistsError:
2139 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002140
2141 def makefile(self, tarinfo, targetpath):
2142 """Make a file called targetpath.
2143 """
Lars Gustäbel9cbdd752010-10-29 09:08:19 +00002144 source = self.fileobj
2145 source.seek(tarinfo.offset_data)
Andrew Svetlov718df1d2012-11-29 14:20:47 +02002146 with bltn_open(targetpath, "wb") as target:
2147 if tarinfo.sparse is not None:
2148 for offset, size in tarinfo.sparse:
2149 target.seek(offset)
Lars Gustäbel03572682015-07-06 09:27:24 +02002150 copyfileobj(source, target, size, ReadError)
Andrew Svetlov718df1d2012-11-29 14:20:47 +02002151 else:
Lars Gustäbel03572682015-07-06 09:27:24 +02002152 copyfileobj(source, target, tarinfo.size, ReadError)
Andrew Svetlov718df1d2012-11-29 14:20:47 +02002153 target.seek(tarinfo.size)
2154 target.truncate()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002155
2156 def makeunknown(self, tarinfo, targetpath):
2157 """Make a file from a TarInfo object with an unknown type
2158 at targetpath.
2159 """
2160 self.makefile(tarinfo, targetpath)
2161 self._dbg(1, "tarfile: Unknown file type %r, " \
2162 "extracted as regular file." % tarinfo.type)
2163
2164 def makefifo(self, tarinfo, targetpath):
2165 """Make a fifo called targetpath.
2166 """
2167 if hasattr(os, "mkfifo"):
2168 os.mkfifo(targetpath)
2169 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002170 raise ExtractError("fifo not supported by system")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002171
2172 def makedev(self, tarinfo, targetpath):
2173 """Make a character or block device called targetpath.
2174 """
2175 if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002176 raise ExtractError("special devices not supported by system")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002177
2178 mode = tarinfo.mode
2179 if tarinfo.isblk():
2180 mode |= stat.S_IFBLK
2181 else:
2182 mode |= stat.S_IFCHR
2183
2184 os.mknod(targetpath, mode,
2185 os.makedev(tarinfo.devmajor, tarinfo.devminor))
2186
2187 def makelink(self, tarinfo, targetpath):
2188 """Make a (symbolic) link called targetpath. If it cannot be created
2189 (platform limitation), we try to make a copy of the referenced file
2190 instead of a link.
2191 """
Brian Curtind40e6f72010-07-08 21:39:08 +00002192 try:
Lars Gustäbel1b512722010-06-03 12:45:16 +00002193 # For systems that support symbolic and hard links.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002194 if tarinfo.issym():
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00002195 os.symlink(tarinfo.linkname, targetpath)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002196 else:
Neal Norwitza4f651a2004-07-20 22:07:44 +00002197 # See extract().
Lars Gustäbel1b512722010-06-03 12:45:16 +00002198 if os.path.exists(tarinfo._link_target):
2199 os.link(tarinfo._link_target, targetpath)
2200 else:
Brian Curtin82df53e2010-09-24 21:04:05 +00002201 self._extract_member(self._find_link_target(tarinfo),
2202 targetpath)
Brian Curtin16633fa2010-07-09 13:54:27 +00002203 except symlink_exception:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002204 try:
Brian Curtin16633fa2010-07-09 13:54:27 +00002205 self._extract_member(self._find_link_target(tarinfo),
2206 targetpath)
Lars Gustäbel1b512722010-06-03 12:45:16 +00002207 except KeyError:
2208 raise ExtractError("unable to resolve link inside archive")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002209
Eric V. Smith7a803892015-04-15 10:27:58 -04002210 def chown(self, tarinfo, targetpath, numeric_owner):
2211 """Set owner of targetpath according to tarinfo. If numeric_owner
2212 is True, use .gid/.uid instead of .gname/.uname.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002213 """
2214 if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
2215 # We have to be root to do so.
Eric V. Smith7a803892015-04-15 10:27:58 -04002216 if numeric_owner:
Lars Gustäbel2e7ddd32011-09-05 16:58:14 +02002217 g = tarinfo.gid
Lars Gustäbel2e7ddd32011-09-05 16:58:14 +02002218 u = tarinfo.uid
Eric V. Smith7a803892015-04-15 10:27:58 -04002219 else:
2220 try:
2221 g = grp.getgrnam(tarinfo.gname)[2]
2222 except KeyError:
2223 g = tarinfo.gid
2224 try:
2225 u = pwd.getpwnam(tarinfo.uname)[2]
2226 except KeyError:
2227 u = tarinfo.uid
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002228 try:
2229 if tarinfo.issym() and hasattr(os, "lchown"):
2230 os.lchown(targetpath, u, g)
2231 else:
Jesus Cea4791a242012-10-05 03:15:39 +02002232 os.chown(targetpath, u, g)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002233 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002234 raise ExtractError("could not change owner")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002235
2236 def chmod(self, tarinfo, targetpath):
2237 """Set file permissions of targetpath according to tarinfo.
2238 """
Jack Jansen834eff62003-03-07 12:47:06 +00002239 if hasattr(os, 'chmod'):
2240 try:
2241 os.chmod(targetpath, tarinfo.mode)
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002242 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002243 raise ExtractError("could not change mode")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002244
2245 def utime(self, tarinfo, targetpath):
2246 """Set modification time of targetpath according to tarinfo.
2247 """
Jack Jansen834eff62003-03-07 12:47:06 +00002248 if not hasattr(os, 'utime'):
Tim Petersf9347782003-03-07 15:36:41 +00002249 return
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002250 try:
2251 os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
Andrew Svetlov3438fa42012-12-17 23:35:18 +02002252 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002253 raise ExtractError("could not change modification time")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002254
2255 #--------------------------------------------------------------------------
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002256 def next(self):
2257 """Return the next member of the archive as a TarInfo object, when
2258 TarFile is opened for reading. Return None if there is no more
2259 available.
2260 """
2261 self._check("ra")
2262 if self.firstmember is not None:
2263 m = self.firstmember
2264 self.firstmember = None
2265 return m
2266
Lars Gustäbel03572682015-07-06 09:27:24 +02002267 # Advance the file pointer.
2268 if self.offset != self.fileobj.tell():
2269 self.fileobj.seek(self.offset - 1)
2270 if not self.fileobj.read(1):
2271 raise ReadError("unexpected end of data")
2272
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002273 # Read the next block.
Lars Gustäbel9520a432009-11-22 18:48:49 +00002274 tarinfo = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002275 while True:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002276 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002277 tarinfo = self.tarinfo.fromtarfile(self)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002278 except EOFHeaderError as e:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002279 if self.ignore_zeros:
Thomas Wouters902d6eb2007-01-09 23:18:33 +00002280 self._dbg(2, "0x%X: %s" % (self.offset, e))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002281 self.offset += BLOCKSIZE
2282 continue
Lars Gustäbel9520a432009-11-22 18:48:49 +00002283 except InvalidHeaderError as e:
2284 if self.ignore_zeros:
2285 self._dbg(2, "0x%X: %s" % (self.offset, e))
2286 self.offset += BLOCKSIZE
2287 continue
2288 elif self.offset == 0:
2289 raise ReadError(str(e))
2290 except EmptyHeaderError:
2291 if self.offset == 0:
2292 raise ReadError("empty file")
2293 except TruncatedHeaderError as e:
2294 if self.offset == 0:
2295 raise ReadError(str(e))
2296 except SubsequentHeaderError as e:
2297 raise ReadError(str(e))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002298 break
2299
Lars Gustäbel9520a432009-11-22 18:48:49 +00002300 if tarinfo is not None:
2301 self.members.append(tarinfo)
2302 else:
2303 self._loaded = True
2304
Thomas Wouters477c8d52006-05-27 19:21:47 +00002305 return tarinfo
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002306
2307 #--------------------------------------------------------------------------
2308 # Little helper methods:
2309
Lars Gustäbel1b512722010-06-03 12:45:16 +00002310 def _getmember(self, name, tarinfo=None, normalize=False):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002311 """Find an archive member by name from bottom to top.
2312 If tarinfo is given, it is used as the starting point.
2313 """
Martin v. Löwisf3c56112004-09-18 09:08:52 +00002314 # Ensure that all members have been loaded.
2315 members = self.getmembers()
2316
Lars Gustäbel1b512722010-06-03 12:45:16 +00002317 # Limit the member search list up to tarinfo.
2318 if tarinfo is not None:
2319 members = members[:members.index(tarinfo)]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002320
Lars Gustäbel1b512722010-06-03 12:45:16 +00002321 if normalize:
2322 name = os.path.normpath(name)
2323
2324 for member in reversed(members):
2325 if normalize:
2326 member_name = os.path.normpath(member.name)
2327 else:
2328 member_name = member.name
2329
2330 if name == member_name:
2331 return member
Andrew M. Kuchling864bba12004-07-10 22:02:11 +00002332
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002333 def _load(self):
2334 """Read through the entire archive file and look for readable
2335 members.
2336 """
2337 while True:
2338 tarinfo = self.next()
2339 if tarinfo is None:
2340 break
2341 self._loaded = True
2342
2343 def _check(self, mode=None):
2344 """Check if TarFile is still open, and if the operation's mode
2345 corresponds to TarFile's mode.
2346 """
2347 if self.closed:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002348 raise OSError("%s is closed" % self.__class__.__name__)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002349 if mode is not None and self.mode not in mode:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002350 raise OSError("bad operation for mode %r" % self.mode)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002351
Lars Gustäbel1b512722010-06-03 12:45:16 +00002352 def _find_link_target(self, tarinfo):
2353 """Find the target member of a symlink or hardlink member in the
2354 archive.
2355 """
2356 if tarinfo.issym():
2357 # Always search the entire archive.
Lars Gustäbel1ef9eda2012-04-24 21:04:40 +02002358 linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname)))
Lars Gustäbel1b512722010-06-03 12:45:16 +00002359 limit = None
2360 else:
2361 # Search the archive before the link, because a hard link is
2362 # just a reference to an already archived file.
2363 linkname = tarinfo.linkname
2364 limit = tarinfo
2365
2366 member = self._getmember(linkname, tarinfo=limit, normalize=True)
2367 if member is None:
2368 raise KeyError("linkname %r not found" % linkname)
2369 return member
2370
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002371 def __iter__(self):
2372 """Provide an iterator object.
2373 """
2374 if self._loaded:
Serhiy Storchakaa2549212015-12-19 09:43:14 +02002375 yield from self.members
2376 return
2377
2378 # Yield items using TarFile's next() method.
2379 # When all members have been read, set TarFile as _loaded.
2380 index = 0
2381 # Fix for SF #1100429: Under rare circumstances it can
2382 # happen that getmembers() is called during iteration,
2383 # which will have already exhausted the next() method.
2384 if self.firstmember is not None:
2385 tarinfo = self.next()
2386 index += 1
2387 yield tarinfo
2388
2389 while True:
2390 if index < len(self.members):
2391 tarinfo = self.members[index]
2392 elif not self._loaded:
2393 tarinfo = self.next()
2394 if not tarinfo:
2395 self._loaded = True
2396 return
2397 else:
2398 return
2399 index += 1
2400 yield tarinfo
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002401
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002402 def _dbg(self, level, msg):
2403 """Write debugging output to sys.stderr.
2404 """
2405 if level <= self.debug:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002406 print(msg, file=sys.stderr)
Lars Gustäbel01385812010-03-03 12:08:54 +00002407
2408 def __enter__(self):
2409 self._check()
2410 return self
2411
2412 def __exit__(self, type, value, traceback):
2413 if type is None:
2414 self.close()
2415 else:
2416 # An exception occurred. We must not call close() because
2417 # it would try to write end-of-archive blocks and padding.
2418 if not self._extfileobj:
2419 self.fileobj.close()
2420 self.closed = True
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002421
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002422#--------------------
2423# exported functions
2424#--------------------
2425def is_tarfile(name):
2426 """Return True if name points to a tar archive that we
2427 are able to handle, else return False.
2428 """
2429 try:
2430 t = open(name)
2431 t.close()
2432 return True
2433 except TarError:
2434 return False
2435
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002436open = TarFile.open
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002437
2438
2439def main():
2440 import argparse
2441
2442 description = 'A simple command line interface for tarfile module.'
2443 parser = argparse.ArgumentParser(description=description)
2444 parser.add_argument('-v', '--verbose', action='store_true', default=False,
2445 help='Verbose output')
2446 group = parser.add_mutually_exclusive_group()
2447 group.add_argument('-l', '--list', metavar='<tarfile>',
2448 help='Show listing of a tarfile')
2449 group.add_argument('-e', '--extract', nargs='+',
2450 metavar=('<tarfile>', '<output_dir>'),
2451 help='Extract tarfile into target dir')
2452 group.add_argument('-c', '--create', nargs='+',
2453 metavar=('<name>', '<file>'),
2454 help='Create tarfile from sources')
2455 group.add_argument('-t', '--test', metavar='<tarfile>',
2456 help='Test if a tarfile is valid')
2457 args = parser.parse_args()
2458
2459 if args.test:
2460 src = args.test
2461 if is_tarfile(src):
2462 with open(src, 'r') as tar:
2463 tar.getmembers()
2464 print(tar.getmembers(), file=sys.stderr)
2465 if args.verbose:
2466 print('{!r} is a tar archive.'.format(src))
2467 else:
2468 parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
2469
2470 elif args.list:
2471 src = args.list
2472 if is_tarfile(src):
2473 with TarFile.open(src, 'r:*') as tf:
2474 tf.list(verbose=args.verbose)
2475 else:
2476 parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
2477
2478 elif args.extract:
2479 if len(args.extract) == 1:
2480 src = args.extract[0]
2481 curdir = os.curdir
2482 elif len(args.extract) == 2:
2483 src, curdir = args.extract
2484 else:
2485 parser.exit(1, parser.format_help())
2486
2487 if is_tarfile(src):
2488 with TarFile.open(src, 'r:*') as tf:
2489 tf.extractall(path=curdir)
2490 if args.verbose:
2491 if curdir == '.':
2492 msg = '{!r} file is extracted.'.format(src)
2493 else:
2494 msg = ('{!r} file is extracted '
2495 'into {!r} directory.').format(src, curdir)
2496 print(msg)
2497 else:
2498 parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
2499
2500 elif args.create:
2501 tar_name = args.create.pop(0)
2502 _, ext = os.path.splitext(tar_name)
2503 compressions = {
2504 # gz
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002505 '.gz': 'gz',
2506 '.tgz': 'gz',
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002507 # xz
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002508 '.xz': 'xz',
2509 '.txz': 'xz',
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002510 # bz2
Serhiy Storchaka832dd5f2015-02-10 08:45:53 +02002511 '.bz2': 'bz2',
2512 '.tbz': 'bz2',
2513 '.tbz2': 'bz2',
2514 '.tb2': 'bz2',
Serhiy Storchakad27b4552013-11-24 01:53:29 +02002515 }
2516 tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w'
2517 tar_files = args.create
2518
2519 with TarFile.open(tar_name, tar_mode) as tf:
2520 for file_name in tar_files:
2521 tf.add(file_name)
2522
2523 if args.verbose:
2524 print('{!r} file created.'.format(tar_name))
2525
2526 else:
2527 parser.exit(1, parser.format_help())
2528
2529if __name__ == '__main__':
2530 main()