blob: bfdba58efe98a75a73140e3258be4a166a7e6891 [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
32__version__ = "$Revision$"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000033
Guido van Rossumd8faa362007-04-27 19:54:29 +000034version = "0.9.0"
Guido van Rossum98297ee2007-11-06 21:34:58 +000035__author__ = "Lars Gust\u00e4bel (lars@gustaebel.de)"
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000036__date__ = "$Date$"
37__cvsid__ = "$Id$"
Guido van Rossum98297ee2007-11-06 21:34:58 +000038__credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000039
40#---------
41# Imports
42#---------
43import sys
44import os
45import shutil
46import stat
47import errno
48import time
49import struct
Thomas Wouters89f507f2006-12-13 04:49:30 +000050import copy
Guido van Rossumd8faa362007-04-27 19:54:29 +000051import re
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000052
53try:
54 import grp, pwd
55except ImportError:
56 grp = pwd = None
57
Brian Curtin16633fa2010-07-09 13:54:27 +000058# os.symlink on Windows prior to 6.0 raises NotImplementedError
59symlink_exception = (AttributeError, NotImplementedError)
60try:
61 # WindowsError (1314) will be raised if the caller does not hold the
62 # SeCreateSymbolicLinkPrivilege privilege
63 symlink_exception += (WindowsError,)
64except NameError:
65 pass
66
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000067# from tarfile import *
68__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"]
69
Georg Brandl1a3284e2007-12-02 09:40:06 +000070from builtins import open as _open # Since 'open' is TarFile.open
Guido van Rossum8f78fe92006-08-24 04:03:53 +000071
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000072#---------------------------------------------------------
73# tar constants
74#---------------------------------------------------------
Lars Gustäbelb506dc32007-08-07 18:36:16 +000075NUL = b"\0" # the null character
Guido van Rossumd8faa362007-04-27 19:54:29 +000076BLOCKSIZE = 512 # length of processing blocks
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000077RECORDSIZE = BLOCKSIZE * 20 # length of records
Lars Gustäbelb506dc32007-08-07 18:36:16 +000078GNU_MAGIC = b"ustar \0" # magic gnu tar string
79POSIX_MAGIC = b"ustar\x0000" # magic posix tar string
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000080
Guido van Rossumd8faa362007-04-27 19:54:29 +000081LENGTH_NAME = 100 # maximum length of a filename
82LENGTH_LINK = 100 # maximum length of a linkname
83LENGTH_PREFIX = 155 # maximum length of the prefix field
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000084
Lars Gustäbelb506dc32007-08-07 18:36:16 +000085REGTYPE = b"0" # regular file
86AREGTYPE = b"\0" # regular file
87LNKTYPE = b"1" # link (inside tarfile)
88SYMTYPE = b"2" # symbolic link
89CHRTYPE = b"3" # character special device
90BLKTYPE = b"4" # block special device
91DIRTYPE = b"5" # directory
92FIFOTYPE = b"6" # fifo special device
93CONTTYPE = b"7" # contiguous file
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +000094
Lars Gustäbelb506dc32007-08-07 18:36:16 +000095GNUTYPE_LONGNAME = b"L" # GNU tar longname
96GNUTYPE_LONGLINK = b"K" # GNU tar longlink
97GNUTYPE_SPARSE = b"S" # GNU tar sparse file
Guido van Rossumd8faa362007-04-27 19:54:29 +000098
Lars Gustäbelb506dc32007-08-07 18:36:16 +000099XHDTYPE = b"x" # POSIX.1-2001 extended header
100XGLTYPE = b"g" # POSIX.1-2001 global header
101SOLARIS_XHDTYPE = b"X" # Solaris extended header
Guido van Rossumd8faa362007-04-27 19:54:29 +0000102
103USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format
104GNU_FORMAT = 1 # GNU tar format
105PAX_FORMAT = 2 # POSIX.1-2001 (pax) format
106DEFAULT_FORMAT = GNU_FORMAT
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000107
108#---------------------------------------------------------
109# tarfile constants
110#---------------------------------------------------------
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111# File types that tarfile supports:
112SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,
113 SYMTYPE, DIRTYPE, FIFOTYPE,
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000114 CONTTYPE, CHRTYPE, BLKTYPE,
115 GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
116 GNUTYPE_SPARSE)
117
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118# File types that will be treated as a regular file.
119REGULAR_TYPES = (REGTYPE, AREGTYPE,
120 CONTTYPE, GNUTYPE_SPARSE)
121
122# File types that are part of the GNU tar format.
123GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
124 GNUTYPE_SPARSE)
125
126# Fields from a pax header that override a TarInfo attribute.
127PAX_FIELDS = ("path", "linkpath", "size", "mtime",
128 "uid", "gid", "uname", "gname")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000129
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000130# Fields from a pax header that are affected by hdrcharset.
131PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"}
132
Guido van Rossume7ba4952007-06-06 23:52:48 +0000133# Fields in a pax header that are numbers, all other fields
134# are treated as strings.
135PAX_NUMBER_FIELDS = {
136 "atime": float,
137 "ctime": float,
138 "mtime": float,
139 "uid": int,
140 "gid": int,
141 "size": int
142}
143
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000144#---------------------------------------------------------
145# Bits used in the mode field, values in octal.
146#---------------------------------------------------------
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000147S_IFLNK = 0o120000 # symbolic link
148S_IFREG = 0o100000 # regular file
149S_IFBLK = 0o060000 # block device
150S_IFDIR = 0o040000 # directory
151S_IFCHR = 0o020000 # character device
152S_IFIFO = 0o010000 # fifo
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000153
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000154TSUID = 0o4000 # set UID on execution
155TSGID = 0o2000 # set GID on execution
156TSVTX = 0o1000 # reserved
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000157
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000158TUREAD = 0o400 # read by owner
159TUWRITE = 0o200 # write by owner
160TUEXEC = 0o100 # execute/search by owner
161TGREAD = 0o040 # read by group
162TGWRITE = 0o020 # write by group
163TGEXEC = 0o010 # execute/search by group
164TOREAD = 0o004 # read by other
165TOWRITE = 0o002 # write by other
166TOEXEC = 0o001 # execute/search by other
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000167
168#---------------------------------------------------------
Guido van Rossumd8faa362007-04-27 19:54:29 +0000169# initialization
170#---------------------------------------------------------
Victor Stinner0f35e2c2010-06-11 23:46:47 +0000171if os.name in ("nt", "ce"):
172 ENCODING = "utf-8"
173else:
174 ENCODING = sys.getfilesystemencoding()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000175
176#---------------------------------------------------------
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000177# Some useful functions
178#---------------------------------------------------------
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000179
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000180def stn(s, length, encoding, errors):
181 """Convert a string to a null-terminated bytes object.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000182 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000183 s = s.encode(encoding, errors)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000184 return s[:length] + (length - len(s)) * NUL
Thomas Wouters477c8d52006-05-27 19:21:47 +0000185
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000186def nts(s, encoding, errors):
187 """Convert a null-terminated bytes object to a string.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000188 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000189 p = s.find(b"\0")
190 if p != -1:
191 s = s[:p]
192 return s.decode(encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000193
Thomas Wouters477c8d52006-05-27 19:21:47 +0000194def nti(s):
195 """Convert a number field to a python number.
196 """
197 # There are two possible encodings for a number field, see
198 # itn() below.
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000199 if s[0] != chr(0o200):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000200 try:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000201 n = int(nts(s, "ascii", "strict") or "0", 8)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000202 except ValueError:
Lars Gustäbel9520a432009-11-22 18:48:49 +0000203 raise InvalidHeaderError("invalid header")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000204 else:
Guido van Rossume2a383d2007-01-15 16:59:06 +0000205 n = 0
Guido van Rossum805365e2007-05-07 22:24:25 +0000206 for i in range(len(s) - 1):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000207 n <<= 8
208 n += ord(s[i + 1])
209 return n
210
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211def itn(n, digits=8, format=DEFAULT_FORMAT):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000212 """Convert a python number to a number field.
213 """
214 # POSIX 1003.1-1988 requires numbers to be encoded as a string of
215 # octal digits followed by a null-byte, this allows values up to
216 # (8**(digits-1))-1. GNU tar allows storing numbers greater than
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000217 # that if necessary. A leading 0o200 byte indicates this particular
Thomas Wouters477c8d52006-05-27 19:21:47 +0000218 # encoding, the following digits-1 bytes are a big-endian
219 # representation. This allows values up to (256**(digits-1))-1.
220 if 0 <= n < 8 ** (digits - 1):
Lars Gustäbela280ca752007-08-28 07:34:33 +0000221 s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL
Thomas Wouters477c8d52006-05-27 19:21:47 +0000222 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 if format != GNU_FORMAT or n >= 256 ** (digits - 1):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000224 raise ValueError("overflow in number field")
225
226 if n < 0:
227 # XXX We mimic GNU tar's behaviour with negative numbers,
228 # this could raise OverflowError.
229 n = struct.unpack("L", struct.pack("l", n))[0]
230
Guido van Rossum254348e2007-11-21 19:29:53 +0000231 s = bytearray()
Guido van Rossum805365e2007-05-07 22:24:25 +0000232 for i in range(digits - 1):
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000233 s.insert(0, n & 0o377)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000234 n >>= 8
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000235 s.insert(0, 0o200)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000236 return s
237
238def calc_chksums(buf):
239 """Calculate the checksum for a member's header by summing up all
240 characters except for the chksum field which is treated as if
241 it was filled with spaces. According to the GNU tar sources,
242 some tars (Sun and NeXT) calculate chksum with signed char,
243 which will be different if there are chars in the buffer with
244 the high bit set. So we calculate two checksums, unsigned and
245 signed.
246 """
247 unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512]))
248 signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512]))
249 return unsigned_chksum, signed_chksum
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000250
251def copyfileobj(src, dst, length=None):
252 """Copy length bytes from fileobj src to fileobj dst.
253 If length is None, copy the entire content.
254 """
255 if length == 0:
256 return
257 if length is None:
258 shutil.copyfileobj(src, dst)
259 return
260
261 BUFSIZE = 16 * 1024
262 blocks, remainder = divmod(length, BUFSIZE)
Guido van Rossum805365e2007-05-07 22:24:25 +0000263 for b in range(blocks):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000264 buf = src.read(BUFSIZE)
265 if len(buf) < BUFSIZE:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000266 raise IOError("end of file reached")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000267 dst.write(buf)
268
269 if remainder != 0:
270 buf = src.read(remainder)
271 if len(buf) < remainder:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000272 raise IOError("end of file reached")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000273 dst.write(buf)
274 return
275
276filemode_table = (
Andrew M. Kuchling8bc462f2004-10-20 11:48:42 +0000277 ((S_IFLNK, "l"),
278 (S_IFREG, "-"),
279 (S_IFBLK, "b"),
280 (S_IFDIR, "d"),
281 (S_IFCHR, "c"),
282 (S_IFIFO, "p")),
283
284 ((TUREAD, "r"),),
285 ((TUWRITE, "w"),),
286 ((TUEXEC|TSUID, "s"),
287 (TSUID, "S"),
288 (TUEXEC, "x")),
289
290 ((TGREAD, "r"),),
291 ((TGWRITE, "w"),),
292 ((TGEXEC|TSGID, "s"),
293 (TSGID, "S"),
294 (TGEXEC, "x")),
295
296 ((TOREAD, "r"),),
297 ((TOWRITE, "w"),),
298 ((TOEXEC|TSVTX, "t"),
299 (TSVTX, "T"),
300 (TOEXEC, "x"))
301)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000302
303def filemode(mode):
304 """Convert a file's mode to a string of the form
305 -rwxrwxrwx.
306 Used by TarFile.list()
307 """
Andrew M. Kuchling8bc462f2004-10-20 11:48:42 +0000308 perm = []
309 for table in filemode_table:
310 for bit, char in table:
311 if mode & bit == bit:
312 perm.append(char)
313 break
314 else:
315 perm.append("-")
316 return "".join(perm)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000317
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000318class TarError(Exception):
319 """Base exception."""
320 pass
321class ExtractError(TarError):
322 """General exception for extract errors."""
323 pass
324class ReadError(TarError):
325 """Exception for unreadble tar archives."""
326 pass
327class CompressionError(TarError):
328 """Exception for unavailable compression methods."""
329 pass
330class StreamError(TarError):
331 """Exception for unsupported operations on stream-like TarFiles."""
332 pass
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000333class HeaderError(TarError):
Lars Gustäbel9520a432009-11-22 18:48:49 +0000334 """Base exception for header errors."""
335 pass
336class EmptyHeaderError(HeaderError):
337 """Exception for empty headers."""
338 pass
339class TruncatedHeaderError(HeaderError):
340 """Exception for truncated headers."""
341 pass
342class EOFHeaderError(HeaderError):
343 """Exception for end of file headers."""
344 pass
345class InvalidHeaderError(HeaderError):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000346 """Exception for invalid headers."""
347 pass
Lars Gustäbel9520a432009-11-22 18:48:49 +0000348class SubsequentHeaderError(HeaderError):
349 """Exception for missing and invalid extended headers."""
350 pass
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000351
352#---------------------------
353# internal stream interface
354#---------------------------
355class _LowLevelFile:
356 """Low-level file object. Supports reading and writing.
357 It is used instead of a regular file object for streaming
358 access.
359 """
360
361 def __init__(self, name, mode):
362 mode = {
363 "r": os.O_RDONLY,
364 "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
365 }[mode]
366 if hasattr(os, "O_BINARY"):
367 mode |= os.O_BINARY
Lars Gustäbeld6eb70b2010-04-29 15:37:02 +0000368 self.fd = os.open(name, mode, 0o666)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000369
370 def close(self):
371 os.close(self.fd)
372
373 def read(self, size):
374 return os.read(self.fd, size)
375
376 def write(self, s):
377 os.write(self.fd, s)
378
379class _Stream:
380 """Class that serves as an adapter between TarFile and
381 a stream-like object. The stream-like object only
382 needs to have a read() or write() method and is accessed
383 blockwise. Use of gzip or bzip2 compression is possible.
384 A stream-like object could be for example: sys.stdin,
385 sys.stdout, a socket, a tape device etc.
386
387 _Stream is intended to be used only internally.
388 """
389
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000390 def __init__(self, name, mode, comptype, fileobj, bufsize):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000391 """Construct a _Stream object.
392 """
393 self._extfileobj = True
394 if fileobj is None:
395 fileobj = _LowLevelFile(name, mode)
396 self._extfileobj = False
397
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000398 if comptype == '*':
399 # Enable transparent compression detection for the
400 # stream interface
401 fileobj = _StreamProxy(fileobj)
402 comptype = fileobj.getcomptype()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000403
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000404 self.name = name or ""
405 self.mode = mode
406 self.comptype = comptype
407 self.fileobj = fileobj
408 self.bufsize = bufsize
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000409 self.buf = b""
Guido van Rossume2a383d2007-01-15 16:59:06 +0000410 self.pos = 0
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000411 self.closed = False
412
413 if comptype == "gz":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000414 try:
415 import zlib
416 except ImportError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000417 raise CompressionError("zlib module is not available")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000418 self.zlib = zlib
Antoine Pitrou77b338b2009-12-14 18:00:06 +0000419 self.crc = zlib.crc32(b"")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000420 if mode == "r":
421 self._init_read_gz()
422 else:
423 self._init_write_gz()
424
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000425 if comptype == "bz2":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000426 try:
427 import bz2
428 except ImportError:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000429 raise CompressionError("bz2 module is not available")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000430 if mode == "r":
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000431 self.dbuf = b""
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000432 self.cmp = bz2.BZ2Decompressor()
433 else:
434 self.cmp = bz2.BZ2Compressor()
435
436 def __del__(self):
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000437 if hasattr(self, "closed") and not self.closed:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000438 self.close()
439
440 def _init_write_gz(self):
441 """Initialize for writing with gzip compression.
442 """
443 self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED,
444 -self.zlib.MAX_WBITS,
445 self.zlib.DEF_MEM_LEVEL,
446 0)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000447 timestamp = struct.pack("<L", int(time.time()))
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000448 self.__write(b"\037\213\010\010" + timestamp + b"\002\377")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000449 if self.name.endswith(".gz"):
450 self.name = self.name[:-3]
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000451 # RFC1952 says we must use ISO-8859-1 for the FNAME field.
452 self.__write(self.name.encode("iso-8859-1", "replace") + NUL)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000453
454 def write(self, s):
455 """Write string s to the stream.
456 """
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000457 if self.comptype == "gz":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000458 self.crc = self.zlib.crc32(s, self.crc)
459 self.pos += len(s)
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000460 if self.comptype != "tar":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000461 s = self.cmp.compress(s)
462 self.__write(s)
463
464 def __write(self, s):
465 """Write string s to the stream if a whole new block
466 is ready to be written.
467 """
468 self.buf += s
469 while len(self.buf) > self.bufsize:
470 self.fileobj.write(self.buf[:self.bufsize])
471 self.buf = self.buf[self.bufsize:]
472
473 def close(self):
474 """Close the _Stream object. No operation should be
475 done on it afterwards.
476 """
477 if self.closed:
478 return
479
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000480 if self.mode == "w" and self.comptype != "tar":
Martin v. Löwisc234a522004-08-22 21:28:33 +0000481 self.buf += self.cmp.flush()
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000482
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000483 if self.mode == "w" and self.buf:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000484 self.fileobj.write(self.buf)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000485 self.buf = b""
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000486 if self.comptype == "gz":
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000487 # The native zlib crc is an unsigned 32-bit integer, but
488 # the Python wrapper implicitly casts that to a signed C
489 # long. So, on a 32-bit box self.crc may "look negative",
490 # while the same crc on a 64-bit box may "look positive".
491 # To avoid irksome warnings from the `struct` module, force
492 # it to look positive on all boxes.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000493 self.fileobj.write(struct.pack("<L", self.crc & 0xffffffff))
494 self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000495
496 if not self._extfileobj:
497 self.fileobj.close()
498
499 self.closed = True
500
501 def _init_read_gz(self):
502 """Initialize for reading a gzip compressed fileobj.
503 """
504 self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000505 self.dbuf = b""
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000506
507 # taken from gzip.GzipFile with some alterations
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000508 if self.__read(2) != b"\037\213":
Thomas Wouters477c8d52006-05-27 19:21:47 +0000509 raise ReadError("not a gzip file")
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000510 if self.__read(1) != b"\010":
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511 raise CompressionError("unsupported compression method")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000512
513 flag = ord(self.__read(1))
514 self.__read(6)
515
516 if flag & 4:
517 xlen = ord(self.__read(1)) + 256 * ord(self.__read(1))
518 self.read(xlen)
519 if flag & 8:
520 while True:
521 s = self.__read(1)
522 if not s or s == NUL:
523 break
524 if flag & 16:
525 while True:
526 s = self.__read(1)
527 if not s or s == NUL:
528 break
529 if flag & 2:
530 self.__read(2)
531
532 def tell(self):
533 """Return the stream's file pointer position.
534 """
535 return self.pos
536
537 def seek(self, pos=0):
538 """Set the stream's file pointer to pos. Negative seeking
539 is forbidden.
540 """
541 if pos - self.pos >= 0:
542 blocks, remainder = divmod(pos - self.pos, self.bufsize)
Guido van Rossum805365e2007-05-07 22:24:25 +0000543 for i in range(blocks):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000544 self.read(self.bufsize)
545 self.read(remainder)
546 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547 raise StreamError("seeking backwards is not allowed")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000548 return self.pos
549
550 def read(self, size=None):
551 """Return the next size number of bytes from the stream.
552 If size is not defined, return all bytes of the stream
553 up to EOF.
554 """
555 if size is None:
556 t = []
557 while True:
558 buf = self._read(self.bufsize)
559 if not buf:
560 break
561 t.append(buf)
562 buf = "".join(t)
563 else:
564 buf = self._read(size)
565 self.pos += len(buf)
566 return buf
567
568 def _read(self, size):
569 """Return size bytes from the stream.
570 """
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000571 if self.comptype == "tar":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000572 return self.__read(size)
573
574 c = len(self.dbuf)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000575 while c < size:
576 buf = self.__read(self.bufsize)
577 if not buf:
578 break
Guido van Rossumd8faa362007-04-27 19:54:29 +0000579 try:
580 buf = self.cmp.decompress(buf)
581 except IOError:
582 raise ReadError("invalid compressed data")
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000583 self.dbuf += buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000584 c += len(buf)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000585 buf = self.dbuf[:size]
586 self.dbuf = self.dbuf[size:]
587 return buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000588
589 def __read(self, size):
590 """Return size bytes from stream. If internal buffer is empty,
591 read another block from the stream.
592 """
593 c = len(self.buf)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000594 while c < size:
595 buf = self.fileobj.read(self.bufsize)
596 if not buf:
597 break
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000598 self.buf += buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000599 c += len(buf)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000600 buf = self.buf[:size]
601 self.buf = self.buf[size:]
602 return buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000603# class _Stream
604
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000605class _StreamProxy(object):
606 """Small proxy class that enables transparent compression
607 detection for the Stream interface (mode 'r|*').
608 """
609
610 def __init__(self, fileobj):
611 self.fileobj = fileobj
612 self.buf = self.fileobj.read(BLOCKSIZE)
613
614 def read(self, size):
615 self.read = self.fileobj.read
616 return self.buf
617
618 def getcomptype(self):
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000619 if self.buf.startswith(b"\037\213\010"):
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000620 return "gz"
Lars Gustäbela280ca752007-08-28 07:34:33 +0000621 if self.buf.startswith(b"BZh91"):
Martin v. Löwis78be7df2005-03-05 12:47:42 +0000622 return "bz2"
623 return "tar"
624
625 def close(self):
626 self.fileobj.close()
627# class StreamProxy
628
Thomas Wouters477c8d52006-05-27 19:21:47 +0000629class _BZ2Proxy(object):
630 """Small proxy class that enables external file object
631 support for "r:bz2" and "w:bz2" modes. This is actually
632 a workaround for a limitation in bz2 module's BZ2File
633 class which (unlike gzip.GzipFile) has no support for
634 a file object argument.
635 """
636
637 blocksize = 16 * 1024
638
639 def __init__(self, fileobj, mode):
640 self.fileobj = fileobj
641 self.mode = mode
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642 self.name = getattr(self.fileobj, "name", None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000643 self.init()
644
645 def init(self):
646 import bz2
647 self.pos = 0
648 if self.mode == "r":
649 self.bz2obj = bz2.BZ2Decompressor()
650 self.fileobj.seek(0)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000651 self.buf = b""
Thomas Wouters477c8d52006-05-27 19:21:47 +0000652 else:
653 self.bz2obj = bz2.BZ2Compressor()
654
655 def read(self, size):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000656 x = len(self.buf)
657 while x < size:
Lars Gustäbel42e00912009-03-22 20:34:29 +0000658 raw = self.fileobj.read(self.blocksize)
659 if not raw:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000660 break
Lars Gustäbel42e00912009-03-22 20:34:29 +0000661 data = self.bz2obj.decompress(raw)
662 self.buf += data
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663 x += len(data)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000664
665 buf = self.buf[:size]
666 self.buf = self.buf[size:]
667 self.pos += len(buf)
668 return buf
669
670 def seek(self, pos):
671 if pos < self.pos:
672 self.init()
673 self.read(pos - self.pos)
674
675 def tell(self):
676 return self.pos
677
678 def write(self, data):
679 self.pos += len(data)
680 raw = self.bz2obj.compress(data)
681 self.fileobj.write(raw)
682
683 def close(self):
684 if self.mode == "w":
685 raw = self.bz2obj.flush()
686 self.fileobj.write(raw)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000687# class _BZ2Proxy
688
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000689#------------------------
690# Extraction file object
691#------------------------
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000692class _FileInFile(object):
693 """A thin wrapper around an existing file object that
694 provides a part of its data as an individual file
695 object.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000696 """
697
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000698 def __init__(self, fileobj, offset, size, sparse=None):
699 self.fileobj = fileobj
700 self.offset = offset
701 self.size = size
702 self.sparse = sparse
703 self.position = 0
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000704
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000705 def seekable(self):
706 if not hasattr(self.fileobj, "seekable"):
707 # XXX gzip.GzipFile and bz2.BZ2File
708 return True
709 return self.fileobj.seekable()
710
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000711 def tell(self):
712 """Return the current file position.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000713 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000714 return self.position
715
716 def seek(self, position):
717 """Seek to a position in the file.
718 """
719 self.position = position
720
721 def read(self, size=None):
722 """Read data from the file.
723 """
724 if size is None:
725 size = self.size - self.position
726 else:
727 size = min(size, self.size - self.position)
728
729 if self.sparse is None:
730 return self.readnormal(size)
731 else:
732 return self.readsparse(size)
733
734 def readnormal(self, size):
735 """Read operation for regular files.
736 """
737 self.fileobj.seek(self.offset + self.position)
738 self.position += size
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000739 return self.fileobj.read(size)
740
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000741 def readsparse(self, size):
742 """Read operation for sparse files.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000743 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000744 data = b""
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000745 while size > 0:
746 buf = self.readsparsesection(size)
747 if not buf:
748 break
749 size -= len(buf)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000750 data += buf
751 return data
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000752
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000753 def readsparsesection(self, size):
754 """Read a single section of a sparse file.
755 """
756 section = self.sparse.find(self.position)
757
758 if section is None:
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000759 return b""
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000760
761 size = min(size, section.offset + section.size - self.position)
762
763 if isinstance(section, _data):
764 realpos = section.realpos + self.position - section.offset
765 self.fileobj.seek(self.offset + realpos)
766 self.position += size
767 return self.fileobj.read(size)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000768 else:
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000769 self.position += size
770 return NUL * size
771#class _FileInFile
772
773
774class ExFileObject(object):
775 """File-like object for reading an archive member.
776 Is returned by TarFile.extractfile().
777 """
778 blocksize = 1024
779
780 def __init__(self, tarfile, tarinfo):
781 self.fileobj = _FileInFile(tarfile.fileobj,
782 tarinfo.offset_data,
783 tarinfo.size,
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +0000784 tarinfo.sparse)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000785 self.name = tarinfo.name
786 self.mode = "r"
787 self.closed = False
788 self.size = tarinfo.size
789
790 self.position = 0
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000791 self.buffer = b""
792
793 def readable(self):
794 return True
795
796 def writable(self):
797 return False
798
799 def seekable(self):
800 return self.fileobj.seekable()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000801
802 def read(self, size=None):
803 """Read at most size bytes from the file. If size is not
804 present or None, read all data until EOF is reached.
805 """
806 if self.closed:
807 raise ValueError("I/O operation on closed file")
808
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000809 buf = b""
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000810 if self.buffer:
811 if size is None:
812 buf = self.buffer
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000813 self.buffer = b""
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000814 else:
815 buf = self.buffer[:size]
816 self.buffer = self.buffer[size:]
817
818 if size is None:
819 buf += self.fileobj.read()
820 else:
821 buf += self.fileobj.read(size - len(buf))
822
823 self.position += len(buf)
824 return buf
825
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000826 # XXX TextIOWrapper uses the read1() method.
827 read1 = read
828
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000829 def readline(self, size=-1):
830 """Read one entire line from the file. If size is present
831 and non-negative, return a string with at most that
832 size, which may be an incomplete line.
833 """
834 if self.closed:
835 raise ValueError("I/O operation on closed file")
836
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000837 pos = self.buffer.find(b"\n") + 1
838 if pos == 0:
839 # no newline found.
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000840 while True:
841 buf = self.fileobj.read(self.blocksize)
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000842 self.buffer += buf
843 if not buf or b"\n" in buf:
844 pos = self.buffer.find(b"\n") + 1
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000845 if pos == 0:
846 # no newline found.
847 pos = len(self.buffer)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000848 break
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000849
850 if size != -1:
851 pos = min(size, pos)
852
853 buf = self.buffer[:pos]
854 self.buffer = self.buffer[pos:]
855 self.position += len(buf)
856 return buf
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000857
858 def readlines(self):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000859 """Return a list with all remaining lines.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000860 """
861 result = []
862 while True:
863 line = self.readline()
864 if not line: break
865 result.append(line)
866 return result
867
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000868 def tell(self):
869 """Return the current file position.
870 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000871 if self.closed:
872 raise ValueError("I/O operation on closed file")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000873
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000874 return self.position
875
876 def seek(self, pos, whence=os.SEEK_SET):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000877 """Seek to a position in the file.
878 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000879 if self.closed:
880 raise ValueError("I/O operation on closed file")
881
882 if whence == os.SEEK_SET:
883 self.position = min(max(pos, 0), self.size)
884 elif whence == os.SEEK_CUR:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000885 if pos < 0:
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000886 self.position = max(self.position + pos, 0)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000887 else:
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000888 self.position = min(self.position + pos, self.size)
889 elif whence == os.SEEK_END:
890 self.position = max(min(self.size + pos, self.size), 0)
891 else:
892 raise ValueError("Invalid argument")
893
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000894 self.buffer = b""
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000895 self.fileobj.seek(self.position)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000896
897 def close(self):
898 """Close the file object.
899 """
900 self.closed = True
Martin v. Löwisdf241532005-03-03 08:17:42 +0000901
902 def __iter__(self):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000903 """Get an iterator over the file's lines.
Martin v. Löwisdf241532005-03-03 08:17:42 +0000904 """
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000905 while True:
906 line = self.readline()
907 if not line:
908 break
909 yield line
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000910#class ExFileObject
911
912#------------------
913# Exported Classes
914#------------------
915class TarInfo(object):
916 """Informational class which holds the details about an
917 archive member given by a tar header block.
918 TarInfo objects are returned by TarFile.getmember(),
919 TarFile.getmembers() and TarFile.gettarinfo() and are
920 usually created internally.
921 """
922
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +0000923 __slots__ = ("name", "mode", "uid", "gid", "size", "mtime",
924 "chksum", "type", "linkname", "uname", "gname",
925 "devmajor", "devminor",
926 "offset", "offset_data", "pax_headers", "sparse",
927 "tarfile", "_sparse_structs", "_link_target")
928
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000929 def __init__(self, name=""):
930 """Construct a TarInfo object. name is the optional name
931 of the member.
932 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000933 self.name = name # member name
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000934 self.mode = 0o644 # file permissions
Thomas Wouters477c8d52006-05-27 19:21:47 +0000935 self.uid = 0 # user id
936 self.gid = 0 # group id
937 self.size = 0 # file size
938 self.mtime = 0 # modification time
939 self.chksum = 0 # header checksum
940 self.type = REGTYPE # member type
941 self.linkname = "" # link name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000942 self.uname = "root" # user name
943 self.gname = "root" # group name
Thomas Wouters477c8d52006-05-27 19:21:47 +0000944 self.devmajor = 0 # device major number
945 self.devminor = 0 # device minor number
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000946
Thomas Wouters477c8d52006-05-27 19:21:47 +0000947 self.offset = 0 # the tar header starts here
948 self.offset_data = 0 # the file's data starts here
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000949
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +0000950 self.sparse = None # sparse member information
Guido van Rossumd8faa362007-04-27 19:54:29 +0000951 self.pax_headers = {} # pax header information
952
953 # In pax headers the "name" and "linkname" field are called
954 # "path" and "linkpath".
955 def _getpath(self):
956 return self.name
957 def _setpath(self, name):
958 self.name = name
959 path = property(_getpath, _setpath)
960
961 def _getlinkpath(self):
962 return self.linkname
963 def _setlinkpath(self, linkname):
964 self.linkname = linkname
965 linkpath = property(_getlinkpath, _setlinkpath)
966
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +0000967 def __repr__(self):
968 return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
969
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000970 def get_info(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000971 """Return the TarInfo's attributes as a dictionary.
972 """
973 info = {
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000974 "name": self.name,
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000975 "mode": self.mode & 0o7777,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976 "uid": self.uid,
977 "gid": self.gid,
978 "size": self.size,
979 "mtime": self.mtime,
980 "chksum": self.chksum,
981 "type": self.type,
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +0000982 "linkname": self.linkname,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000983 "uname": self.uname,
984 "gname": self.gname,
985 "devmajor": self.devmajor,
986 "devminor": self.devminor
987 }
988
989 if info["type"] == DIRTYPE and not info["name"].endswith("/"):
990 info["name"] += "/"
991
992 return info
993
Victor Stinnerde629d42010-05-05 21:43:57 +0000994 def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000995 """Return a tar header as a string of 512 byte blocks.
996 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +0000997 info = self.get_info()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000998
Guido van Rossumd8faa362007-04-27 19:54:29 +0000999 if format == USTAR_FORMAT:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001000 return self.create_ustar_header(info, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001001 elif format == GNU_FORMAT:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001002 return self.create_gnu_header(info, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001003 elif format == PAX_FORMAT:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001004 return self.create_pax_header(info, encoding)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001005 else:
1006 raise ValueError("invalid format")
1007
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001008 def create_ustar_header(self, info, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001009 """Return the object as a ustar header block.
1010 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001011 info["magic"] = POSIX_MAGIC
1012
1013 if len(info["linkname"]) > LENGTH_LINK:
1014 raise ValueError("linkname is too long")
1015
1016 if len(info["name"]) > LENGTH_NAME:
1017 info["prefix"], info["name"] = self._posix_split_name(info["name"])
1018
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001019 return self._create_header(info, USTAR_FORMAT, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001020
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001021 def create_gnu_header(self, info, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001022 """Return the object as a GNU header block sequence.
1023 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001024 info["magic"] = GNU_MAGIC
1025
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001026 buf = b""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001027 if len(info["linkname"]) > LENGTH_LINK:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001028 buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029
1030 if len(info["name"]) > LENGTH_NAME:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001031 buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001032
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001033 return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001034
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001035 def create_pax_header(self, info, encoding):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001036 """Return the object as a ustar header block. If it cannot be
1037 represented this way, prepend a pax extended header sequence
1038 with supplement information.
1039 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001040 info["magic"] = POSIX_MAGIC
1041 pax_headers = self.pax_headers.copy()
1042
1043 # Test string fields for values that exceed the field length or cannot
1044 # be represented in ASCII encoding.
1045 for name, hname, length in (
1046 ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
1047 ("uname", "uname", 32), ("gname", "gname", 32)):
1048
Guido van Rossume7ba4952007-06-06 23:52:48 +00001049 if hname in pax_headers:
1050 # The pax header has priority.
1051 continue
1052
Guido van Rossumd8faa362007-04-27 19:54:29 +00001053 # Try to encode the string as ASCII.
1054 try:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001055 info[name].encode("ascii", "strict")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001056 except UnicodeEncodeError:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001057 pax_headers[hname] = info[name]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058 continue
1059
Guido van Rossume7ba4952007-06-06 23:52:48 +00001060 if len(info[name]) > length:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001061 pax_headers[hname] = info[name]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001062
1063 # Test number fields for values that exceed the field limit or values
1064 # that like to be stored as float.
1065 for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001066 if name in pax_headers:
1067 # The pax header has priority. Avoid overflow.
1068 info[name] = 0
1069 continue
1070
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071 val = info[name]
1072 if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001073 pax_headers[name] = str(val)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001074 info[name] = 0
1075
Guido van Rossume7ba4952007-06-06 23:52:48 +00001076 # Create a pax extended header if necessary.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001077 if pax_headers:
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001078 buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001079 else:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001080 buf = b""
Guido van Rossumd8faa362007-04-27 19:54:29 +00001081
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001082 return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083
1084 @classmethod
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001085 def create_pax_global_header(cls, pax_headers):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001086 """Return the object as a pax global header block sequence.
1087 """
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001088 return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf8")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001089
1090 def _posix_split_name(self, name):
1091 """Split a name longer than 100 chars into a prefix
1092 and a name part.
1093 """
1094 prefix = name[:LENGTH_PREFIX + 1]
1095 while prefix and prefix[-1] != "/":
1096 prefix = prefix[:-1]
1097
1098 name = name[len(prefix):]
1099 prefix = prefix[:-1]
1100
1101 if not prefix or len(name) > LENGTH_NAME:
1102 raise ValueError("name is too long")
1103 return prefix, name
1104
1105 @staticmethod
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001106 def _create_header(info, format, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001107 """Return a header block. info is a dictionary with file
1108 information, format must be one of the *_FORMAT constants.
1109 """
1110 parts = [
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001111 stn(info.get("name", ""), 100, encoding, errors),
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001112 itn(info.get("mode", 0) & 0o7777, 8, format),
Guido van Rossumd8faa362007-04-27 19:54:29 +00001113 itn(info.get("uid", 0), 8, format),
1114 itn(info.get("gid", 0), 8, format),
1115 itn(info.get("size", 0), 12, format),
1116 itn(info.get("mtime", 0), 12, format),
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001117 b" ", # checksum field
Guido van Rossumd8faa362007-04-27 19:54:29 +00001118 info.get("type", REGTYPE),
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001119 stn(info.get("linkname", ""), 100, encoding, errors),
1120 info.get("magic", POSIX_MAGIC),
1121 stn(info.get("uname", "root"), 32, encoding, errors),
1122 stn(info.get("gname", "root"), 32, encoding, errors),
Guido van Rossumd8faa362007-04-27 19:54:29 +00001123 itn(info.get("devmajor", 0), 8, format),
1124 itn(info.get("devminor", 0), 8, format),
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001125 stn(info.get("prefix", ""), 155, encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001126 ]
1127
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001128 buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001129 chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
Lars Gustäbela280ca752007-08-28 07:34:33 +00001130 buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:]
Guido van Rossumd8faa362007-04-27 19:54:29 +00001131 return buf
1132
1133 @staticmethod
1134 def _create_payload(payload):
1135 """Return the string payload filled with zero bytes
1136 up to the next 512 byte border.
1137 """
1138 blocks, remainder = divmod(len(payload), BLOCKSIZE)
1139 if remainder > 0:
1140 payload += (BLOCKSIZE - remainder) * NUL
1141 return payload
1142
1143 @classmethod
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001144 def _create_gnu_long_header(cls, name, type, encoding, errors):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001145 """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
1146 for name.
1147 """
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001148 name = name.encode(encoding, errors) + NUL
Guido van Rossumd8faa362007-04-27 19:54:29 +00001149
1150 info = {}
1151 info["name"] = "././@LongLink"
1152 info["type"] = type
1153 info["size"] = len(name)
1154 info["magic"] = GNU_MAGIC
1155
1156 # create extended header + name blocks.
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001157 return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
Guido van Rossumd8faa362007-04-27 19:54:29 +00001158 cls._create_payload(name)
1159
1160 @classmethod
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001161 def _create_pax_generic_header(cls, pax_headers, type, encoding):
1162 """Return a POSIX.1-2008 extended or global header sequence
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163 that contains a list of keyword, value pairs. The values
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001164 must be strings.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001165 """
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001166 # Check if one of the fields contains surrogate characters and thereby
1167 # forces hdrcharset=BINARY, see _proc_pax() for more information.
1168 binary = False
1169 for keyword, value in pax_headers.items():
1170 try:
1171 value.encode("utf8", "strict")
1172 except UnicodeEncodeError:
1173 binary = True
1174 break
1175
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001176 records = b""
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001177 if binary:
1178 # Put the hdrcharset field at the beginning of the header.
1179 records += b"21 hdrcharset=BINARY\n"
1180
Guido van Rossumd8faa362007-04-27 19:54:29 +00001181 for keyword, value in pax_headers.items():
1182 keyword = keyword.encode("utf8")
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001183 if binary:
1184 # Try to restore the original byte representation of `value'.
1185 # Needless to say, that the encoding must match the string.
1186 value = value.encode(encoding, "surrogateescape")
1187 else:
1188 value = value.encode("utf8")
1189
Guido van Rossumd8faa362007-04-27 19:54:29 +00001190 l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n'
1191 n = p = 0
1192 while True:
1193 n = l + len(str(p))
1194 if n == p:
1195 break
1196 p = n
Lars Gustäbela280ca752007-08-28 07:34:33 +00001197 records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n"
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198
1199 # We use a hardcoded "././@PaxHeader" name like star does
1200 # instead of the one that POSIX recommends.
1201 info = {}
1202 info["name"] = "././@PaxHeader"
1203 info["type"] = type
1204 info["size"] = len(records)
1205 info["magic"] = POSIX_MAGIC
1206
1207 # Create pax header + record blocks.
Lars Gustäbel3741eff2007-08-21 12:17:05 +00001208 return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \
Guido van Rossumd8faa362007-04-27 19:54:29 +00001209 cls._create_payload(records)
1210
Guido van Rossum75b64e62005-01-16 00:16:11 +00001211 @classmethod
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001212 def frombuf(cls, buf, encoding, errors):
1213 """Construct a TarInfo object from a 512 byte bytes object.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001214 """
Lars Gustäbel9520a432009-11-22 18:48:49 +00001215 if len(buf) == 0:
1216 raise EmptyHeaderError("empty header")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001217 if len(buf) != BLOCKSIZE:
Lars Gustäbel9520a432009-11-22 18:48:49 +00001218 raise TruncatedHeaderError("truncated header")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219 if buf.count(NUL) == BLOCKSIZE:
Lars Gustäbel9520a432009-11-22 18:48:49 +00001220 raise EOFHeaderError("end of file header")
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001221
1222 chksum = nti(buf[148:156])
1223 if chksum not in calc_chksums(buf):
Lars Gustäbel9520a432009-11-22 18:48:49 +00001224 raise InvalidHeaderError("bad checksum")
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225
Guido van Rossumd8faa362007-04-27 19:54:29 +00001226 obj = cls()
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001227 obj.name = nts(buf[0:100], encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001228 obj.mode = nti(buf[100:108])
1229 obj.uid = nti(buf[108:116])
1230 obj.gid = nti(buf[116:124])
1231 obj.size = nti(buf[124:136])
1232 obj.mtime = nti(buf[136:148])
1233 obj.chksum = chksum
1234 obj.type = buf[156:157]
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001235 obj.linkname = nts(buf[157:257], encoding, errors)
1236 obj.uname = nts(buf[265:297], encoding, errors)
1237 obj.gname = nts(buf[297:329], encoding, errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001238 obj.devmajor = nti(buf[329:337])
1239 obj.devminor = nti(buf[337:345])
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001240 prefix = nts(buf[345:500], encoding, errors)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001241
Guido van Rossumd8faa362007-04-27 19:54:29 +00001242 # Old V7 tar format represents a directory as a regular
1243 # file with a trailing slash.
1244 if obj.type == AREGTYPE and obj.name.endswith("/"):
1245 obj.type = DIRTYPE
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001246
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001247 # The old GNU sparse format occupies some of the unused
1248 # space in the buffer for up to 4 sparse structures.
1249 # Save the them for later processing in _proc_sparse().
1250 if obj.type == GNUTYPE_SPARSE:
1251 pos = 386
1252 structs = []
1253 for i in range(4):
1254 try:
1255 offset = nti(buf[pos:pos + 12])
1256 numbytes = nti(buf[pos + 12:pos + 24])
1257 except ValueError:
1258 break
1259 structs.append((offset, numbytes))
1260 pos += 24
1261 isextended = bool(buf[482])
1262 origsize = nti(buf[483:495])
1263 obj._sparse_structs = (structs, isextended, origsize)
1264
Guido van Rossumd8faa362007-04-27 19:54:29 +00001265 # Remove redundant slashes from directories.
1266 if obj.isdir():
1267 obj.name = obj.name.rstrip("/")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001268
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 # Reconstruct a ustar longname.
1270 if prefix and obj.type not in GNU_TYPES:
1271 obj.name = prefix + "/" + obj.name
1272 return obj
1273
1274 @classmethod
1275 def fromtarfile(cls, tarfile):
1276 """Return the next TarInfo object from TarFile object
1277 tarfile.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001278 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001279 buf = tarfile.fileobj.read(BLOCKSIZE)
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001280 obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001281 obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
1282 return obj._proc_member(tarfile)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001283
Guido van Rossumd8faa362007-04-27 19:54:29 +00001284 #--------------------------------------------------------------------------
1285 # The following are methods that are called depending on the type of a
1286 # member. The entry point is _proc_member() which can be overridden in a
1287 # subclass to add custom _proc_*() methods. A _proc_*() method MUST
1288 # implement the following
1289 # operations:
1290 # 1. Set self.offset_data to the position where the data blocks begin,
1291 # if there is data that follows.
1292 # 2. Set tarfile.offset to the position where the next member's header will
1293 # begin.
1294 # 3. Return self or another valid TarInfo object.
1295 def _proc_member(self, tarfile):
1296 """Choose the right processing method depending on
1297 the type and call it.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001298 """
Guido van Rossumd8faa362007-04-27 19:54:29 +00001299 if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
1300 return self._proc_gnulong(tarfile)
1301 elif self.type == GNUTYPE_SPARSE:
1302 return self._proc_sparse(tarfile)
1303 elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
1304 return self._proc_pax(tarfile)
1305 else:
1306 return self._proc_builtin(tarfile)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001307
Guido van Rossumd8faa362007-04-27 19:54:29 +00001308 def _proc_builtin(self, tarfile):
1309 """Process a builtin type or an unknown type which
1310 will be treated as a regular file.
1311 """
1312 self.offset_data = tarfile.fileobj.tell()
1313 offset = self.offset_data
1314 if self.isreg() or self.type not in SUPPORTED_TYPES:
1315 # Skip the following data blocks.
1316 offset += self._block(self.size)
1317 tarfile.offset = offset
Thomas Wouters89f507f2006-12-13 04:49:30 +00001318
Guido van Rossume7ba4952007-06-06 23:52:48 +00001319 # Patch the TarInfo object with saved global
Guido van Rossumd8faa362007-04-27 19:54:29 +00001320 # header information.
Guido van Rossume7ba4952007-06-06 23:52:48 +00001321 self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001322
1323 return self
1324
1325 def _proc_gnulong(self, tarfile):
1326 """Process the blocks that hold a GNU longname
1327 or longlink member.
1328 """
1329 buf = tarfile.fileobj.read(self._block(self.size))
1330
1331 # Fetch the next header and process it.
Lars Gustäbel9520a432009-11-22 18:48:49 +00001332 try:
1333 next = self.fromtarfile(tarfile)
1334 except HeaderError:
1335 raise SubsequentHeaderError("missing or bad subsequent header")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001336
1337 # Patch the TarInfo object from the next header with
1338 # the longname information.
1339 next.offset = self.offset
1340 if self.type == GNUTYPE_LONGNAME:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001341 next.name = nts(buf, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001342 elif self.type == GNUTYPE_LONGLINK:
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001343 next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001344
1345 return next
1346
1347 def _proc_sparse(self, tarfile):
1348 """Process a GNU sparse header plus extra headers.
1349 """
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001350 # We already collected some sparse structures in frombuf().
1351 structs, isextended, origsize = self._sparse_structs
1352 del self._sparse_structs
Guido van Rossumd8faa362007-04-27 19:54:29 +00001353
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001354 # Collect sparse structures from extended header blocks.
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001355 while isextended:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001356 buf = tarfile.fileobj.read(BLOCKSIZE)
1357 pos = 0
Guido van Rossum805365e2007-05-07 22:24:25 +00001358 for i in range(21):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001359 try:
1360 offset = nti(buf[pos:pos + 12])
1361 numbytes = nti(buf[pos + 12:pos + 24])
1362 except ValueError:
1363 break
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001364 structs.append((offset, numbytes))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001365 pos += 24
Lars Gustäbelb506dc32007-08-07 18:36:16 +00001366 isextended = bool(buf[504])
Guido van Rossumd8faa362007-04-27 19:54:29 +00001367
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001368 # Transform the sparse structures to something we can use
1369 # in ExFileObject.
1370 self.sparse = _ringbuffer()
1371 lastpos = 0
1372 realpos = 0
1373 for offset, numbytes in structs:
1374 if offset > lastpos:
1375 self.sparse.append(_hole(lastpos, offset - lastpos))
1376 self.sparse.append(_data(offset, numbytes, realpos))
1377 realpos += numbytes
1378 lastpos = offset + numbytes
Guido van Rossumd8faa362007-04-27 19:54:29 +00001379 if lastpos < origsize:
Lars Gustäbelc2ea8c62008-04-14 10:05:48 +00001380 self.sparse.append(_hole(lastpos, origsize - lastpos))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001381
1382 self.offset_data = tarfile.fileobj.tell()
1383 tarfile.offset = self.offset_data + self._block(self.size)
1384 self.size = origsize
1385
1386 return self
1387
1388 def _proc_pax(self, tarfile):
1389 """Process an extended or global header as described in
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001390 POSIX.1-2008.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001391 """
1392 # Read the header information.
1393 buf = tarfile.fileobj.read(self._block(self.size))
1394
1395 # A pax header stores supplemental information for either
1396 # the following file (extended) or all following files
1397 # (global).
1398 if self.type == XGLTYPE:
1399 pax_headers = tarfile.pax_headers
1400 else:
1401 pax_headers = tarfile.pax_headers.copy()
1402
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001403 # Check if the pax header contains a hdrcharset field. This tells us
1404 # the encoding of the path, linkpath, uname and gname fields. Normally,
1405 # these fields are UTF-8 encoded but since POSIX.1-2008 tar
1406 # implementations are allowed to store them as raw binary strings if
1407 # the translation to UTF-8 fails.
1408 match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
1409 if match is not None:
1410 pax_headers["hdrcharset"] = match.group(1).decode("utf8")
1411
1412 # For the time being, we don't care about anything other than "BINARY".
1413 # The only other value that is currently allowed by the standard is
1414 # "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1415 hdrcharset = pax_headers.get("hdrcharset")
1416 if hdrcharset == "BINARY":
1417 encoding = tarfile.encoding
1418 else:
1419 encoding = "utf8"
1420
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421 # Parse pax header information. A record looks like that:
1422 # "%d %s=%s\n" % (length, keyword, value). length is the size
1423 # of the complete record including the length field itself and
Guido van Rossume7ba4952007-06-06 23:52:48 +00001424 # the newline. keyword and value are both UTF-8 encoded strings.
Antoine Pitroufd036452008-08-19 17:56:33 +00001425 regex = re.compile(br"(\d+) ([^=]+)=")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001426 pos = 0
1427 while True:
1428 match = regex.match(buf, pos)
1429 if not match:
1430 break
1431
1432 length, keyword = match.groups()
1433 length = int(length)
1434 value = buf[match.end(2) + 1:match.start(1) + length - 1]
1435
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001436 # Normally, we could just use "utf8" as the encoding and "strict"
1437 # as the error handler, but we better not take the risk. For
1438 # example, GNU tar <= 1.23 is known to store filenames it cannot
1439 # translate to UTF-8 as raw strings (unfortunately without a
1440 # hdrcharset=BINARY header).
1441 # We first try the strict standard encoding, and if that fails we
1442 # fall back on the user's encoding and error handler.
1443 keyword = self._decode_pax_field(keyword, "utf8", "utf8",
1444 tarfile.errors)
1445 if keyword in PAX_NAME_FIELDS:
1446 value = self._decode_pax_field(value, encoding, tarfile.encoding,
1447 tarfile.errors)
1448 else:
1449 value = self._decode_pax_field(value, "utf8", "utf8",
1450 tarfile.errors)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001451
1452 pax_headers[keyword] = value
1453 pos += length
1454
Guido van Rossume7ba4952007-06-06 23:52:48 +00001455 # Fetch the next header.
Lars Gustäbel9520a432009-11-22 18:48:49 +00001456 try:
1457 next = self.fromtarfile(tarfile)
1458 except HeaderError:
1459 raise SubsequentHeaderError("missing or bad subsequent header")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001460
Guido van Rossume7ba4952007-06-06 23:52:48 +00001461 if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
Guido van Rossume7ba4952007-06-06 23:52:48 +00001462 # Patch the TarInfo object with the extended header info.
1463 next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
1464 next.offset = self.offset
1465
1466 if "size" in pax_headers:
1467 # If the extended header replaces the size field,
1468 # we need to recalculate the offset where the next
1469 # header starts.
1470 offset = next.offset_data
1471 if next.isreg() or next.type not in SUPPORTED_TYPES:
1472 offset += next._block(next.size)
1473 tarfile.offset = offset
1474
1475 return next
1476
1477 def _apply_pax_info(self, pax_headers, encoding, errors):
1478 """Replace fields with supplemental information from a previous
1479 pax extended or global header.
1480 """
1481 for keyword, value in pax_headers.items():
1482 if keyword not in PAX_FIELDS:
1483 continue
1484
1485 if keyword == "path":
1486 value = value.rstrip("/")
1487
1488 if keyword in PAX_NUMBER_FIELDS:
1489 try:
1490 value = PAX_NUMBER_FIELDS[keyword](value)
1491 except ValueError:
1492 value = 0
Guido van Rossume7ba4952007-06-06 23:52:48 +00001493
1494 setattr(self, keyword, value)
1495
1496 self.pax_headers = pax_headers.copy()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497
Lars Gustäbel1465cc22010-05-17 18:02:50 +00001498 def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
1499 """Decode a single field from a pax record.
1500 """
1501 try:
1502 return value.decode(encoding, "strict")
1503 except UnicodeDecodeError:
1504 return value.decode(fallback_encoding, fallback_errors)
1505
Guido van Rossumd8faa362007-04-27 19:54:29 +00001506 def _block(self, count):
1507 """Round up a byte count by BLOCKSIZE and return it,
1508 e.g. _block(834) => 1024.
1509 """
1510 blocks, remainder = divmod(count, BLOCKSIZE)
1511 if remainder:
1512 blocks += 1
1513 return blocks * BLOCKSIZE
Thomas Wouters89f507f2006-12-13 04:49:30 +00001514
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001515 def isreg(self):
1516 return self.type in REGULAR_TYPES
1517 def isfile(self):
1518 return self.isreg()
1519 def isdir(self):
1520 return self.type == DIRTYPE
1521 def issym(self):
1522 return self.type == SYMTYPE
1523 def islnk(self):
1524 return self.type == LNKTYPE
1525 def ischr(self):
1526 return self.type == CHRTYPE
1527 def isblk(self):
1528 return self.type == BLKTYPE
1529 def isfifo(self):
1530 return self.type == FIFOTYPE
1531 def issparse(self):
1532 return self.type == GNUTYPE_SPARSE
1533 def isdev(self):
1534 return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
1535# class TarInfo
1536
1537class TarFile(object):
1538 """The TarFile Class provides an interface to tar archives.
1539 """
1540
1541 debug = 0 # May be set from 0 (no msgs) to 3 (all msgs)
1542
1543 dereference = False # If true, add content of linked file to the
1544 # tar file, else the link.
1545
1546 ignore_zeros = False # If true, skips empty or invalid blocks and
1547 # continues processing.
1548
Lars Gustäbel365aff32009-12-13 11:42:29 +00001549 errorlevel = 1 # If 0, fatal errors only appear in debug
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001550 # messages (if debug >= 0). If > 0, errors
1551 # are passed to the caller as exceptions.
1552
Guido van Rossumd8faa362007-04-27 19:54:29 +00001553 format = DEFAULT_FORMAT # The format to use when creating an archive.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001554
Guido van Rossume7ba4952007-06-06 23:52:48 +00001555 encoding = ENCODING # Encoding for 8-bit character strings.
1556
1557 errors = None # Error handler for unicode conversion.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001558
Guido van Rossumd8faa362007-04-27 19:54:29 +00001559 tarinfo = TarInfo # The default TarInfo class to use.
1560
1561 fileobject = ExFileObject # The default ExFileObject class to use.
1562
1563 def __init__(self, name=None, mode="r", fileobj=None, format=None,
1564 tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
Victor Stinnerde629d42010-05-05 21:43:57 +00001565 errors="surrogateescape", pax_headers=None, debug=None, errorlevel=None):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001566 """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
1567 read from an existing archive, 'a' to append data to an existing
1568 file or 'w' to create a new file overwriting an existing one. `mode'
1569 defaults to 'r'.
1570 If `fileobj' is given, it is used for reading or writing data. If it
1571 can be determined, `mode' is overridden by `fileobj's mode.
1572 `fileobj' is not closed, when TarFile is closed.
1573 """
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001574 if len(mode) > 1 or mode not in "raw":
Thomas Wouters477c8d52006-05-27 19:21:47 +00001575 raise ValueError("mode must be 'r', 'a' or 'w'")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001576 self.mode = mode
1577 self._mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001578
1579 if not fileobj:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001580 if self.mode == "a" and not os.path.exists(name):
Thomas Wouterscf297e42007-02-23 15:07:44 +00001581 # Create nonexistent files in append mode.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001582 self.mode = "w"
1583 self._mode = "wb"
Guido van Rossume7ba4952007-06-06 23:52:48 +00001584 fileobj = bltn_open(name, self._mode)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001585 self._extfileobj = False
1586 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001587 if name is None and hasattr(fileobj, "name"):
1588 name = fileobj.name
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001589 if hasattr(fileobj, "mode"):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001590 self._mode = fileobj.mode
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001591 self._extfileobj = True
Thomas Woutersed03b412007-08-28 21:37:11 +00001592 self.name = os.path.abspath(name) if name else None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001593 self.fileobj = fileobj
1594
Guido van Rossumd8faa362007-04-27 19:54:29 +00001595 # Init attributes.
1596 if format is not None:
1597 self.format = format
1598 if tarinfo is not None:
1599 self.tarinfo = tarinfo
1600 if dereference is not None:
1601 self.dereference = dereference
1602 if ignore_zeros is not None:
1603 self.ignore_zeros = ignore_zeros
1604 if encoding is not None:
1605 self.encoding = encoding
Victor Stinnerde629d42010-05-05 21:43:57 +00001606 self.errors = errors
Guido van Rossume7ba4952007-06-06 23:52:48 +00001607
1608 if pax_headers is not None and self.format == PAX_FORMAT:
1609 self.pax_headers = pax_headers
1610 else:
1611 self.pax_headers = {}
1612
Guido van Rossumd8faa362007-04-27 19:54:29 +00001613 if debug is not None:
1614 self.debug = debug
1615 if errorlevel is not None:
1616 self.errorlevel = errorlevel
1617
1618 # Init datastructures.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001619 self.closed = False
1620 self.members = [] # list of members as TarInfo objects
1621 self._loaded = False # flag if all members have been read
Christian Heimesd8654cf2007-12-02 15:22:16 +00001622 self.offset = self.fileobj.tell()
1623 # current position in the archive file
Thomas Wouters477c8d52006-05-27 19:21:47 +00001624 self.inodes = {} # dictionary caching the inodes of
1625 # archive members already added
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001626
Lars Gustäbel7b465392009-11-18 20:29:25 +00001627 try:
1628 if self.mode == "r":
1629 self.firstmember = None
1630 self.firstmember = self.next()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001631
Lars Gustäbel7b465392009-11-18 20:29:25 +00001632 if self.mode == "a":
1633 # Move to the end of the archive,
1634 # before the first empty block.
Lars Gustäbel7b465392009-11-18 20:29:25 +00001635 while True:
Lars Gustäbel9520a432009-11-22 18:48:49 +00001636 self.fileobj.seek(self.offset)
1637 try:
1638 tarinfo = self.tarinfo.fromtarfile(self)
1639 self.members.append(tarinfo)
1640 except EOFHeaderError:
1641 self.fileobj.seek(self.offset)
Lars Gustäbel7b465392009-11-18 20:29:25 +00001642 break
Lars Gustäbel9520a432009-11-22 18:48:49 +00001643 except HeaderError as e:
1644 raise ReadError(str(e))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001645
Lars Gustäbel7b465392009-11-18 20:29:25 +00001646 if self.mode in "aw":
1647 self._loaded = True
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001648
Lars Gustäbel7b465392009-11-18 20:29:25 +00001649 if self.pax_headers:
1650 buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
1651 self.fileobj.write(buf)
1652 self.offset += len(buf)
1653 except:
1654 if not self._extfileobj:
1655 self.fileobj.close()
1656 self.closed = True
1657 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +00001658
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001659 #--------------------------------------------------------------------------
1660 # Below are the classmethods which act as alternate constructors to the
1661 # TarFile class. The open() method is the only one that is needed for
1662 # public use; it is the "super"-constructor and is able to select an
1663 # adequate "sub"-constructor for a particular compression using the mapping
1664 # from OPEN_METH.
1665 #
1666 # This concept allows one to subclass TarFile without losing the comfort of
1667 # the super-constructor. A sub-constructor is registered and made available
1668 # by adding it to the mapping in OPEN_METH.
1669
Guido van Rossum75b64e62005-01-16 00:16:11 +00001670 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001671 def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001672 """Open a tar archive for reading, writing or appending. Return
1673 an appropriate TarFile class.
1674
1675 mode:
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001676 'r' or 'r:*' open for reading with transparent compression
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001677 'r:' open for reading exclusively uncompressed
1678 'r:gz' open for reading with gzip compression
1679 'r:bz2' open for reading with bzip2 compression
Thomas Wouterscf297e42007-02-23 15:07:44 +00001680 'a' or 'a:' open for appending, creating the file if necessary
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001681 'w' or 'w:' open for writing without compression
1682 'w:gz' open for writing with gzip compression
1683 'w:bz2' open for writing with bzip2 compression
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001684
1685 'r|*' open a stream of tar blocks with transparent compression
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001686 'r|' open an uncompressed stream of tar blocks for reading
1687 'r|gz' open a gzip compressed stream of tar blocks
1688 'r|bz2' open a bzip2 compressed stream of tar blocks
1689 'w|' open an uncompressed stream for writing
1690 'w|gz' open a gzip compressed stream for writing
1691 'w|bz2' open a bzip2 compressed stream for writing
1692 """
1693
1694 if not name and not fileobj:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001695 raise ValueError("nothing to open")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001696
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001697 if mode in ("r", "r:*"):
1698 # Find out which *open() is appropriate for opening the file.
1699 for comptype in cls.OPEN_METH:
1700 func = getattr(cls, cls.OPEN_METH[comptype])
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001701 if fileobj is not None:
1702 saved_pos = fileobj.tell()
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001703 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001704 return func(name, "r", fileobj, **kwargs)
1705 except (ReadError, CompressionError) as e:
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001706 if fileobj is not None:
1707 fileobj.seek(saved_pos)
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001708 continue
Thomas Wouters477c8d52006-05-27 19:21:47 +00001709 raise ReadError("file could not be opened successfully")
Martin v. Löwis78be7df2005-03-05 12:47:42 +00001710
1711 elif ":" in mode:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001712 filemode, comptype = mode.split(":", 1)
1713 filemode = filemode or "r"
1714 comptype = comptype or "tar"
1715
1716 # Select the *open() function according to
1717 # given compression.
1718 if comptype in cls.OPEN_METH:
1719 func = getattr(cls, cls.OPEN_METH[comptype])
1720 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001721 raise CompressionError("unknown compression type %r" % comptype)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001722 return func(name, filemode, fileobj, **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001723
1724 elif "|" in mode:
1725 filemode, comptype = mode.split("|", 1)
1726 filemode = filemode or "r"
1727 comptype = comptype or "tar"
1728
1729 if filemode not in "rw":
Thomas Wouters477c8d52006-05-27 19:21:47 +00001730 raise ValueError("mode must be 'r' or 'w'")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001731
1732 t = cls(name, filemode,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001733 _Stream(name, filemode, comptype, fileobj, bufsize),
1734 **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001735 t._extfileobj = False
1736 return t
1737
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001738 elif mode in "aw":
Guido van Rossumd8faa362007-04-27 19:54:29 +00001739 return cls.taropen(name, mode, fileobj, **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001740
Thomas Wouters477c8d52006-05-27 19:21:47 +00001741 raise ValueError("undiscernible mode")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001742
Guido van Rossum75b64e62005-01-16 00:16:11 +00001743 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001744 def taropen(cls, name, mode="r", fileobj=None, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001745 """Open uncompressed tar archive name for reading or writing.
1746 """
1747 if len(mode) > 1 or mode not in "raw":
Thomas Wouters477c8d52006-05-27 19:21:47 +00001748 raise ValueError("mode must be 'r', 'a' or 'w'")
Guido van Rossumd8faa362007-04-27 19:54:29 +00001749 return cls(name, mode, fileobj, **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001750
Guido van Rossum75b64e62005-01-16 00:16:11 +00001751 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001752 def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001753 """Open gzip compressed tar archive name for reading or writing.
1754 Appending is not allowed.
1755 """
1756 if len(mode) > 1 or mode not in "rw":
Thomas Wouters477c8d52006-05-27 19:21:47 +00001757 raise ValueError("mode must be 'r' or 'w'")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001758
1759 try:
1760 import gzip
Neal Norwitz4ec68242003-04-11 03:05:56 +00001761 gzip.GzipFile
1762 except (ImportError, AttributeError):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001763 raise CompressionError("gzip module is not available")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001764
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001765 if fileobj is None:
Guido van Rossume7ba4952007-06-06 23:52:48 +00001766 fileobj = bltn_open(name, mode + "b")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001767 extfileobj = False
1768 else:
1769 extfileobj = True
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001770
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001771 try:
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001772 t = cls.taropen(name, mode,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001773 gzip.GzipFile(name, mode, compresslevel, fileobj),
1774 **kwargs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001775 except IOError:
Antoine Pitrou95f55602010-09-23 18:36:46 +00001776 if not extfileobj:
1777 fileobj.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778 raise ReadError("not a gzip file")
Antoine Pitrou95f55602010-09-23 18:36:46 +00001779 t._extfileobj = extfileobj
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001780 return t
1781
Guido van Rossum75b64e62005-01-16 00:16:11 +00001782 @classmethod
Guido van Rossumd8faa362007-04-27 19:54:29 +00001783 def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001784 """Open bzip2 compressed tar archive name for reading or writing.
1785 Appending is not allowed.
1786 """
1787 if len(mode) > 1 or mode not in "rw":
Thomas Wouters477c8d52006-05-27 19:21:47 +00001788 raise ValueError("mode must be 'r' or 'w'.")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001789
1790 try:
1791 import bz2
1792 except ImportError:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001793 raise CompressionError("bz2 module is not available")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001794
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001795 if fileobj is not None:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001796 fileobj = _BZ2Proxy(fileobj, mode)
1797 else:
1798 fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001799
1800 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001801 t = cls.taropen(name, mode, fileobj, **kwargs)
Lars Gustäbel9520a432009-11-22 18:48:49 +00001802 except (IOError, EOFError):
Antoine Pitrou95f55602010-09-23 18:36:46 +00001803 fileobj.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001804 raise ReadError("not a bzip2 file")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001805 t._extfileobj = False
1806 return t
1807
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001808 # All *open() methods are registered here.
1809 OPEN_METH = {
1810 "tar": "taropen", # uncompressed tar
1811 "gz": "gzopen", # gzip compressed tar
1812 "bz2": "bz2open" # bzip2 compressed tar
1813 }
1814
1815 #--------------------------------------------------------------------------
1816 # The public methods which TarFile provides:
1817
1818 def close(self):
1819 """Close the TarFile. In write-mode, two finishing zero blocks are
1820 appended to the archive.
1821 """
1822 if self.closed:
1823 return
1824
Guido van Rossumd8faa362007-04-27 19:54:29 +00001825 if self.mode in "aw":
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001826 self.fileobj.write(NUL * (BLOCKSIZE * 2))
1827 self.offset += (BLOCKSIZE * 2)
1828 # fill up the end with zero-blocks
1829 # (like option -b20 for tar does)
1830 blocks, remainder = divmod(self.offset, RECORDSIZE)
1831 if remainder > 0:
1832 self.fileobj.write(NUL * (RECORDSIZE - remainder))
1833
1834 if not self._extfileobj:
1835 self.fileobj.close()
1836 self.closed = True
1837
1838 def getmember(self, name):
1839 """Return a TarInfo object for member `name'. If `name' can not be
1840 found in the archive, KeyError is raised. If a member occurs more
Mark Dickinson934896d2009-02-21 20:59:32 +00001841 than once in the archive, its last occurrence is assumed to be the
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001842 most up-to-date version.
1843 """
Martin v. Löwisf3c56112004-09-18 09:08:52 +00001844 tarinfo = self._getmember(name)
1845 if tarinfo is None:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001846 raise KeyError("filename %r not found" % name)
Martin v. Löwisf3c56112004-09-18 09:08:52 +00001847 return tarinfo
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001848
1849 def getmembers(self):
1850 """Return the members of the archive as a list of TarInfo objects. The
1851 list has the same order as the members in the archive.
1852 """
1853 self._check()
1854 if not self._loaded: # if we want to obtain a list of
1855 self._load() # all members, we first have to
1856 # scan the whole archive.
1857 return self.members
1858
1859 def getnames(self):
1860 """Return the members of the archive as a list of their names. It has
1861 the same order as the list returned by getmembers().
1862 """
Martin v. Löwisf3c56112004-09-18 09:08:52 +00001863 return [tarinfo.name for tarinfo in self.getmembers()]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001864
1865 def gettarinfo(self, name=None, arcname=None, fileobj=None):
1866 """Create a TarInfo object for either the file `name' or the file
1867 object `fileobj' (using os.fstat on its file descriptor). You can
1868 modify some of the TarInfo's attributes before you add it using
1869 addfile(). If given, `arcname' specifies an alternative name for the
1870 file in the archive.
1871 """
1872 self._check("aw")
1873
1874 # When fileobj is given, replace name by
1875 # fileobj's real name.
1876 if fileobj is not None:
1877 name = fileobj.name
1878
1879 # Building the name of the member in the archive.
1880 # Backward slashes are converted to forward slashes,
1881 # Absolute paths are turned to relative paths.
1882 if arcname is None:
1883 arcname = name
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001884 drv, arcname = os.path.splitdrive(arcname)
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00001885 arcname = arcname.replace(os.sep, "/")
1886 arcname = arcname.lstrip("/")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001887
1888 # Now, fill the TarInfo object with
1889 # information specific for the file.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001890 tarinfo = self.tarinfo()
1891 tarinfo.tarfile = self
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001892
1893 # Use os.stat or os.lstat, depending on platform
1894 # and if symlinks shall be resolved.
1895 if fileobj is None:
1896 if hasattr(os, "lstat") and not self.dereference:
1897 statres = os.lstat(name)
1898 else:
1899 statres = os.stat(name)
1900 else:
1901 statres = os.fstat(fileobj.fileno())
1902 linkname = ""
1903
1904 stmd = statres.st_mode
1905 if stat.S_ISREG(stmd):
1906 inode = (statres.st_ino, statres.st_dev)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001907 if not self.dereference and statres.st_nlink > 1 and \
1908 inode in self.inodes and arcname != self.inodes[inode]:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001909 # Is it a hardlink to an already
1910 # archived file?
1911 type = LNKTYPE
1912 linkname = self.inodes[inode]
1913 else:
1914 # The inode is added only if its valid.
1915 # For win32 it is always 0.
1916 type = REGTYPE
1917 if inode[0]:
1918 self.inodes[inode] = arcname
1919 elif stat.S_ISDIR(stmd):
1920 type = DIRTYPE
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001921 elif stat.S_ISFIFO(stmd):
1922 type = FIFOTYPE
1923 elif stat.S_ISLNK(stmd):
1924 type = SYMTYPE
1925 linkname = os.readlink(name)
1926 elif stat.S_ISCHR(stmd):
1927 type = CHRTYPE
1928 elif stat.S_ISBLK(stmd):
1929 type = BLKTYPE
1930 else:
1931 return None
1932
1933 # Fill the TarInfo object with all
1934 # information we can get.
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001935 tarinfo.name = arcname
1936 tarinfo.mode = stmd
1937 tarinfo.uid = statres.st_uid
1938 tarinfo.gid = statres.st_gid
Lars Gustäbel2470ff12010-06-03 10:11:52 +00001939 if type == REGTYPE:
Martin v. Löwis61d77e02004-08-20 06:35:46 +00001940 tarinfo.size = statres.st_size
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001941 else:
Guido van Rossume2a383d2007-01-15 16:59:06 +00001942 tarinfo.size = 0
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001943 tarinfo.mtime = statres.st_mtime
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00001944 tarinfo.type = type
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001945 tarinfo.linkname = linkname
1946 if pwd:
1947 try:
1948 tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
1949 except KeyError:
1950 pass
1951 if grp:
1952 try:
1953 tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
1954 except KeyError:
1955 pass
1956
1957 if type in (CHRTYPE, BLKTYPE):
1958 if hasattr(os, "major") and hasattr(os, "minor"):
1959 tarinfo.devmajor = os.major(statres.st_rdev)
1960 tarinfo.devminor = os.minor(statres.st_rdev)
1961 return tarinfo
1962
1963 def list(self, verbose=True):
1964 """Print a table of contents to sys.stdout. If `verbose' is False, only
1965 the names of the members are printed. If it is True, an `ls -l'-like
1966 output is produced.
1967 """
1968 self._check()
1969
1970 for tarinfo in self:
1971 if verbose:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001972 print(filemode(tarinfo.mode), end=' ')
1973 print("%s/%s" % (tarinfo.uname or tarinfo.uid,
1974 tarinfo.gname or tarinfo.gid), end=' ')
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001975 if tarinfo.ischr() or tarinfo.isblk():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001976 print("%10s" % ("%d,%d" \
1977 % (tarinfo.devmajor, tarinfo.devminor)), end=' ')
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001978 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001979 print("%10d" % tarinfo.size, end=' ')
1980 print("%d-%02d-%02d %02d:%02d:%02d" \
1981 % time.localtime(tarinfo.mtime)[:6], end=' ')
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001982
Guido van Rossumd8faa362007-04-27 19:54:29 +00001983 print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001984
1985 if verbose:
1986 if tarinfo.issym():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001987 print("->", tarinfo.linkname, end=' ')
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001988 if tarinfo.islnk():
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001989 print("link to", tarinfo.linkname, end=' ')
1990 print()
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001991
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001992 def add(self, name, arcname=None, recursive=True, exclude=None, filter=None):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00001993 """Add the file `name' to the archive. `name' may be any type of file
1994 (directory, fifo, symbolic link, etc.). If given, `arcname'
1995 specifies an alternative name for the file in the archive.
1996 Directories are added recursively by default. This can be avoided by
Guido van Rossum486364b2007-06-30 05:01:58 +00001997 setting `recursive' to False. `exclude' is a function that should
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00001998 return True for each filename to be excluded. `filter' is a function
1999 that expects a TarInfo object argument and returns the changed
2000 TarInfo object, if it returns None the TarInfo object will be
2001 excluded from the archive.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002002 """
2003 self._check("aw")
2004
2005 if arcname is None:
2006 arcname = name
2007
Guido van Rossum486364b2007-06-30 05:01:58 +00002008 # Exclude pathnames.
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00002009 if exclude is not None:
2010 import warnings
2011 warnings.warn("use the filter argument instead",
2012 DeprecationWarning, 2)
2013 if exclude(name):
2014 self._dbg(2, "tarfile: Excluded %r" % name)
2015 return
Guido van Rossum486364b2007-06-30 05:01:58 +00002016
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002017 # Skip if somebody tries to archive the archive...
Thomas Wouters902d6eb2007-01-09 23:18:33 +00002018 if self.name is not None and os.path.abspath(name) == self.name:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002019 self._dbg(2, "tarfile: Skipped %r" % name)
2020 return
2021
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002022 self._dbg(1, name)
2023
2024 # Create a TarInfo object from the file.
2025 tarinfo = self.gettarinfo(name, arcname)
2026
2027 if tarinfo is None:
2028 self._dbg(1, "tarfile: Unsupported type %r" % name)
2029 return
2030
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00002031 # Change or exclude the TarInfo object.
2032 if filter is not None:
2033 tarinfo = filter(tarinfo)
2034 if tarinfo is None:
2035 self._dbg(2, "tarfile: Excluded %r" % name)
2036 return
2037
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002038 # Append the tar header and data to the archive.
2039 if tarinfo.isreg():
Guido van Rossume7ba4952007-06-06 23:52:48 +00002040 f = bltn_open(name, "rb")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002041 self.addfile(tarinfo, f)
2042 f.close()
2043
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00002044 elif tarinfo.isdir():
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002045 self.addfile(tarinfo)
2046 if recursive:
2047 for f in os.listdir(name):
Lars Gustäbel049d2aa2009-09-12 10:44:00 +00002048 self.add(os.path.join(name, f), os.path.join(arcname, f),
2049 recursive, exclude, filter)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002050
Martin v. Löwis5dbdc592005-08-27 10:07:56 +00002051 else:
2052 self.addfile(tarinfo)
2053
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002054 def addfile(self, tarinfo, fileobj=None):
2055 """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
2056 given, tarinfo.size bytes are read from it and added to the archive.
2057 You can create TarInfo objects using gettarinfo().
2058 On Windows platforms, `fileobj' should always be opened with mode
2059 'rb' to avoid irritation about the file size.
2060 """
2061 self._check("aw")
2062
Thomas Wouters89f507f2006-12-13 04:49:30 +00002063 tarinfo = copy.copy(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002064
Guido van Rossume7ba4952007-06-06 23:52:48 +00002065 buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
Thomas Wouters89f507f2006-12-13 04:49:30 +00002066 self.fileobj.write(buf)
2067 self.offset += len(buf)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002068
2069 # If there's data to follow, append it.
2070 if fileobj is not None:
2071 copyfileobj(fileobj, self.fileobj, tarinfo.size)
2072 blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
2073 if remainder > 0:
2074 self.fileobj.write(NUL * (BLOCKSIZE - remainder))
2075 blocks += 1
2076 self.offset += blocks * BLOCKSIZE
2077
Martin v. Löwisf3c56112004-09-18 09:08:52 +00002078 self.members.append(tarinfo)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002079
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002080 def extractall(self, path=".", members=None):
2081 """Extract all members from the archive to the current working
2082 directory and set owner, modification time and permissions on
2083 directories afterwards. `path' specifies a different directory
2084 to extract to. `members' is optional and must be a subset of the
2085 list returned by getmembers().
2086 """
2087 directories = []
2088
2089 if members is None:
2090 members = self
2091
2092 for tarinfo in members:
2093 if tarinfo.isdir():
Christian Heimes2202f872008-02-06 14:31:34 +00002094 # Extract directories with a safe mode.
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002095 directories.append(tarinfo)
Christian Heimes2202f872008-02-06 14:31:34 +00002096 tarinfo = copy.copy(tarinfo)
2097 tarinfo.mode = 0o700
2098 self.extract(tarinfo, path)
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002099
2100 # Reverse sort directories.
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00002101 directories.sort(key=lambda a: a.name)
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002102 directories.reverse()
2103
2104 # Set correct owner, mtime and filemode on directories.
2105 for tarinfo in directories:
Christian Heimesfaf2f632008-01-06 16:59:19 +00002106 dirpath = os.path.join(path, tarinfo.name)
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002107 try:
Christian Heimesfaf2f632008-01-06 16:59:19 +00002108 self.chown(tarinfo, dirpath)
2109 self.utime(tarinfo, dirpath)
2110 self.chmod(tarinfo, dirpath)
Guido van Rossumb940e112007-01-10 16:19:56 +00002111 except ExtractError as e:
Martin v. Löwis00a73e72005-03-04 19:40:34 +00002112 if self.errorlevel > 1:
2113 raise
2114 else:
2115 self._dbg(1, "tarfile: %s" % e)
2116
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002117 def extract(self, member, path=""):
2118 """Extract a member from the archive to the current working directory,
2119 using its full name. Its file information is extracted as accurately
2120 as possible. `member' may be a filename or a TarInfo object. You can
2121 specify a different directory using `path'.
2122 """
2123 self._check("r")
2124
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002125 if isinstance(member, str):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002126 tarinfo = self.getmember(member)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002127 else:
2128 tarinfo = member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002129
Neal Norwitza4f651a2004-07-20 22:07:44 +00002130 # Prepare the link target for makelink().
2131 if tarinfo.islnk():
2132 tarinfo._link_target = os.path.join(path, tarinfo.linkname)
2133
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002134 try:
2135 self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
Guido van Rossumb940e112007-01-10 16:19:56 +00002136 except EnvironmentError as e:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002137 if self.errorlevel > 0:
2138 raise
2139 else:
2140 if e.filename is None:
2141 self._dbg(1, "tarfile: %s" % e.strerror)
2142 else:
2143 self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
Guido van Rossumb940e112007-01-10 16:19:56 +00002144 except ExtractError as e:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002145 if self.errorlevel > 1:
2146 raise
2147 else:
2148 self._dbg(1, "tarfile: %s" % e)
2149
2150 def extractfile(self, member):
2151 """Extract a member from the archive as a file object. `member' may be
2152 a filename or a TarInfo object. If `member' is a regular file, a
2153 file-like object is returned. If `member' is a link, a file-like
2154 object is constructed from the link's target. If `member' is none of
2155 the above, None is returned.
2156 The file-like object is read-only and provides the following
2157 methods: read(), readline(), readlines(), seek() and tell()
2158 """
2159 self._check("r")
2160
Guido van Rossum3172c5d2007-10-16 18:12:55 +00002161 if isinstance(member, str):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002162 tarinfo = self.getmember(member)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002163 else:
2164 tarinfo = member
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002165
2166 if tarinfo.isreg():
2167 return self.fileobject(self, tarinfo)
2168
2169 elif tarinfo.type not in SUPPORTED_TYPES:
2170 # If a member's type is unknown, it is treated as a
2171 # regular file.
2172 return self.fileobject(self, tarinfo)
2173
2174 elif tarinfo.islnk() or tarinfo.issym():
2175 if isinstance(self.fileobj, _Stream):
2176 # A small but ugly workaround for the case that someone tries
2177 # to extract a (sym)link as a file-object from a non-seekable
2178 # stream of tar blocks.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002179 raise StreamError("cannot extract (sym)link as file object")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002180 else:
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00002181 # A (sym)link's file object is its target's file object.
Lars Gustäbel1b512722010-06-03 12:45:16 +00002182 return self.extractfile(self._find_link_target(tarinfo))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002183 else:
2184 # If there's no data associated with the member (directory, chrdev,
2185 # blkdev, etc.), return None instead of a file object.
2186 return None
2187
2188 def _extract_member(self, tarinfo, targetpath):
2189 """Extract the TarInfo object tarinfo to a physical
2190 file called targetpath.
2191 """
2192 # Fetch the TarInfo object for the given name
2193 # and build the destination pathname, replacing
2194 # forward slashes to platform specific separators.
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00002195 targetpath = targetpath.rstrip("/")
2196 targetpath = targetpath.replace("/", os.sep)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002197
2198 # Create all upper directories.
2199 upperdirs = os.path.dirname(targetpath)
2200 if upperdirs and not os.path.exists(upperdirs):
Christian Heimes2202f872008-02-06 14:31:34 +00002201 # Create directories that are not part of the archive with
2202 # default permissions.
Thomas Woutersb2137042007-02-01 18:02:27 +00002203 os.makedirs(upperdirs)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002204
2205 if tarinfo.islnk() or tarinfo.issym():
2206 self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
2207 else:
2208 self._dbg(1, tarinfo.name)
2209
2210 if tarinfo.isreg():
2211 self.makefile(tarinfo, targetpath)
2212 elif tarinfo.isdir():
2213 self.makedir(tarinfo, targetpath)
2214 elif tarinfo.isfifo():
2215 self.makefifo(tarinfo, targetpath)
2216 elif tarinfo.ischr() or tarinfo.isblk():
2217 self.makedev(tarinfo, targetpath)
2218 elif tarinfo.islnk() or tarinfo.issym():
2219 self.makelink(tarinfo, targetpath)
2220 elif tarinfo.type not in SUPPORTED_TYPES:
2221 self.makeunknown(tarinfo, targetpath)
2222 else:
2223 self.makefile(tarinfo, targetpath)
2224
2225 self.chown(tarinfo, targetpath)
2226 if not tarinfo.issym():
2227 self.chmod(tarinfo, targetpath)
2228 self.utime(tarinfo, targetpath)
2229
2230 #--------------------------------------------------------------------------
2231 # Below are the different file methods. They are called via
2232 # _extract_member() when extract() is called. They can be replaced in a
2233 # subclass to implement other functionality.
2234
2235 def makedir(self, tarinfo, targetpath):
2236 """Make a directory called targetpath.
2237 """
2238 try:
Christian Heimes2202f872008-02-06 14:31:34 +00002239 # Use a safe mode for the directory, the real mode is set
2240 # later in _extract_member().
2241 os.mkdir(targetpath, 0o700)
Guido van Rossumb940e112007-01-10 16:19:56 +00002242 except EnvironmentError as e:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002243 if e.errno != errno.EEXIST:
2244 raise
2245
2246 def makefile(self, tarinfo, targetpath):
2247 """Make a file called targetpath.
2248 """
2249 source = self.extractfile(tarinfo)
Guido van Rossume7ba4952007-06-06 23:52:48 +00002250 target = bltn_open(targetpath, "wb")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002251 copyfileobj(source, target)
2252 source.close()
2253 target.close()
2254
2255 def makeunknown(self, tarinfo, targetpath):
2256 """Make a file from a TarInfo object with an unknown type
2257 at targetpath.
2258 """
2259 self.makefile(tarinfo, targetpath)
2260 self._dbg(1, "tarfile: Unknown file type %r, " \
2261 "extracted as regular file." % tarinfo.type)
2262
2263 def makefifo(self, tarinfo, targetpath):
2264 """Make a fifo called targetpath.
2265 """
2266 if hasattr(os, "mkfifo"):
2267 os.mkfifo(targetpath)
2268 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002269 raise ExtractError("fifo not supported by system")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002270
2271 def makedev(self, tarinfo, targetpath):
2272 """Make a character or block device called targetpath.
2273 """
2274 if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002275 raise ExtractError("special devices not supported by system")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002276
2277 mode = tarinfo.mode
2278 if tarinfo.isblk():
2279 mode |= stat.S_IFBLK
2280 else:
2281 mode |= stat.S_IFCHR
2282
2283 os.mknod(targetpath, mode,
2284 os.makedev(tarinfo.devmajor, tarinfo.devminor))
2285
2286 def makelink(self, tarinfo, targetpath):
2287 """Make a (symbolic) link called targetpath. If it cannot be created
2288 (platform limitation), we try to make a copy of the referenced file
2289 instead of a link.
2290 """
Brian Curtind40e6f72010-07-08 21:39:08 +00002291 try:
Lars Gustäbel1b512722010-06-03 12:45:16 +00002292 # For systems that support symbolic and hard links.
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002293 if tarinfo.issym():
Lars Gustäbelbfdfdda2009-08-28 19:59:59 +00002294 os.symlink(tarinfo.linkname, targetpath)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002295 else:
Neal Norwitza4f651a2004-07-20 22:07:44 +00002296 # See extract().
Lars Gustäbel1b512722010-06-03 12:45:16 +00002297 if os.path.exists(tarinfo._link_target):
2298 os.link(tarinfo._link_target, targetpath)
2299 else:
Brian Curtind40e6f72010-07-08 21:39:08 +00002300 self._extract_mem
Brian Curtin16633fa2010-07-09 13:54:27 +00002301 except symlink_exception:
Brian Curtind40e6f72010-07-08 21:39:08 +00002302 if tarinfo.issym():
Brian Curtin16633fa2010-07-09 13:54:27 +00002303 linkpath = os.path.join(os.path.dirname(tarinfo.name),
2304 tarinfo.linkname)
Brian Curtind40e6f72010-07-08 21:39:08 +00002305 else:
2306 linkpath = tarinfo.linkname
Lars Gustäbel1b512722010-06-03 12:45:16 +00002307 else:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002308 try:
Brian Curtin16633fa2010-07-09 13:54:27 +00002309 self._extract_member(self._find_link_target(tarinfo),
2310 targetpath)
Lars Gustäbel1b512722010-06-03 12:45:16 +00002311 except KeyError:
2312 raise ExtractError("unable to resolve link inside archive")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002313
2314 def chown(self, tarinfo, targetpath):
2315 """Set owner of targetpath according to tarinfo.
2316 """
2317 if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
2318 # We have to be root to do so.
2319 try:
2320 g = grp.getgrnam(tarinfo.gname)[2]
2321 except KeyError:
2322 try:
2323 g = grp.getgrgid(tarinfo.gid)[2]
2324 except KeyError:
2325 g = os.getgid()
2326 try:
2327 u = pwd.getpwnam(tarinfo.uname)[2]
2328 except KeyError:
2329 try:
2330 u = pwd.getpwuid(tarinfo.uid)[2]
2331 except KeyError:
2332 u = os.getuid()
2333 try:
2334 if tarinfo.issym() and hasattr(os, "lchown"):
2335 os.lchown(targetpath, u, g)
2336 else:
Andrew MacIntyre7970d202003-02-19 12:51:34 +00002337 if sys.platform != "os2emx":
2338 os.chown(targetpath, u, g)
Guido van Rossumb940e112007-01-10 16:19:56 +00002339 except EnvironmentError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002340 raise ExtractError("could not change owner")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002341
2342 def chmod(self, tarinfo, targetpath):
2343 """Set file permissions of targetpath according to tarinfo.
2344 """
Jack Jansen834eff62003-03-07 12:47:06 +00002345 if hasattr(os, 'chmod'):
2346 try:
2347 os.chmod(targetpath, tarinfo.mode)
Guido van Rossumb940e112007-01-10 16:19:56 +00002348 except EnvironmentError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002349 raise ExtractError("could not change mode")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002350
2351 def utime(self, tarinfo, targetpath):
2352 """Set modification time of targetpath according to tarinfo.
2353 """
Jack Jansen834eff62003-03-07 12:47:06 +00002354 if not hasattr(os, 'utime'):
Tim Petersf9347782003-03-07 15:36:41 +00002355 return
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002356 try:
2357 os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
Guido van Rossumb940e112007-01-10 16:19:56 +00002358 except EnvironmentError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002359 raise ExtractError("could not change modification time")
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002360
2361 #--------------------------------------------------------------------------
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002362 def next(self):
2363 """Return the next member of the archive as a TarInfo object, when
2364 TarFile is opened for reading. Return None if there is no more
2365 available.
2366 """
2367 self._check("ra")
2368 if self.firstmember is not None:
2369 m = self.firstmember
2370 self.firstmember = None
2371 return m
2372
2373 # Read the next block.
Andrew M. Kuchling864bba12004-07-10 22:02:11 +00002374 self.fileobj.seek(self.offset)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002375 tarinfo = None
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002376 while True:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002377 try:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002378 tarinfo = self.tarinfo.fromtarfile(self)
Lars Gustäbel9520a432009-11-22 18:48:49 +00002379 except EOFHeaderError as e:
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002380 if self.ignore_zeros:
Thomas Wouters902d6eb2007-01-09 23:18:33 +00002381 self._dbg(2, "0x%X: %s" % (self.offset, e))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002382 self.offset += BLOCKSIZE
2383 continue
Lars Gustäbel9520a432009-11-22 18:48:49 +00002384 except InvalidHeaderError as e:
2385 if self.ignore_zeros:
2386 self._dbg(2, "0x%X: %s" % (self.offset, e))
2387 self.offset += BLOCKSIZE
2388 continue
2389 elif self.offset == 0:
2390 raise ReadError(str(e))
2391 except EmptyHeaderError:
2392 if self.offset == 0:
2393 raise ReadError("empty file")
2394 except TruncatedHeaderError as e:
2395 if self.offset == 0:
2396 raise ReadError(str(e))
2397 except SubsequentHeaderError as e:
2398 raise ReadError(str(e))
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002399 break
2400
Lars Gustäbel9520a432009-11-22 18:48:49 +00002401 if tarinfo is not None:
2402 self.members.append(tarinfo)
2403 else:
2404 self._loaded = True
2405
Thomas Wouters477c8d52006-05-27 19:21:47 +00002406 return tarinfo
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002407
2408 #--------------------------------------------------------------------------
2409 # Little helper methods:
2410
Lars Gustäbel1b512722010-06-03 12:45:16 +00002411 def _getmember(self, name, tarinfo=None, normalize=False):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002412 """Find an archive member by name from bottom to top.
2413 If tarinfo is given, it is used as the starting point.
2414 """
Martin v. Löwisf3c56112004-09-18 09:08:52 +00002415 # Ensure that all members have been loaded.
2416 members = self.getmembers()
2417
Lars Gustäbel1b512722010-06-03 12:45:16 +00002418 # Limit the member search list up to tarinfo.
2419 if tarinfo is not None:
2420 members = members[:members.index(tarinfo)]
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002421
Lars Gustäbel1b512722010-06-03 12:45:16 +00002422 if normalize:
2423 name = os.path.normpath(name)
2424
2425 for member in reversed(members):
2426 if normalize:
2427 member_name = os.path.normpath(member.name)
2428 else:
2429 member_name = member.name
2430
2431 if name == member_name:
2432 return member
Andrew M. Kuchling864bba12004-07-10 22:02:11 +00002433
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002434 def _load(self):
2435 """Read through the entire archive file and look for readable
2436 members.
2437 """
2438 while True:
2439 tarinfo = self.next()
2440 if tarinfo is None:
2441 break
2442 self._loaded = True
2443
2444 def _check(self, mode=None):
2445 """Check if TarFile is still open, and if the operation's mode
2446 corresponds to TarFile's mode.
2447 """
2448 if self.closed:
Thomas Wouters477c8d52006-05-27 19:21:47 +00002449 raise IOError("%s is closed" % self.__class__.__name__)
Guido van Rossumd8faa362007-04-27 19:54:29 +00002450 if mode is not None and self.mode not in mode:
2451 raise IOError("bad operation for mode %r" % self.mode)
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002452
Lars Gustäbel1b512722010-06-03 12:45:16 +00002453 def _find_link_target(self, tarinfo):
2454 """Find the target member of a symlink or hardlink member in the
2455 archive.
2456 """
2457 if tarinfo.issym():
2458 # Always search the entire archive.
2459 linkname = os.path.dirname(tarinfo.name) + "/" + tarinfo.linkname
2460 limit = None
2461 else:
2462 # Search the archive before the link, because a hard link is
2463 # just a reference to an already archived file.
2464 linkname = tarinfo.linkname
2465 limit = tarinfo
2466
2467 member = self._getmember(linkname, tarinfo=limit, normalize=True)
2468 if member is None:
2469 raise KeyError("linkname %r not found" % linkname)
2470 return member
2471
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002472 def __iter__(self):
2473 """Provide an iterator object.
2474 """
2475 if self._loaded:
2476 return iter(self.members)
2477 else:
2478 return TarIter(self)
2479
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002480 def _dbg(self, level, msg):
2481 """Write debugging output to sys.stderr.
2482 """
2483 if level <= self.debug:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002484 print(msg, file=sys.stderr)
Lars Gustäbel01385812010-03-03 12:08:54 +00002485
2486 def __enter__(self):
2487 self._check()
2488 return self
2489
2490 def __exit__(self, type, value, traceback):
2491 if type is None:
2492 self.close()
2493 else:
2494 # An exception occurred. We must not call close() because
2495 # it would try to write end-of-archive blocks and padding.
2496 if not self._extfileobj:
2497 self.fileobj.close()
2498 self.closed = True
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002499# class TarFile
2500
2501class TarIter:
2502 """Iterator Class.
2503
2504 for tarinfo in TarFile(...):
2505 suite...
2506 """
2507
2508 def __init__(self, tarfile):
2509 """Construct a TarIter object.
2510 """
2511 self.tarfile = tarfile
Martin v. Löwis637431b2005-03-03 23:12:42 +00002512 self.index = 0
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002513 def __iter__(self):
2514 """Return iterator object.
2515 """
2516 return self
Georg Brandla18af4e2007-04-21 15:47:16 +00002517 def __next__(self):
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002518 """Return the next item using TarFile's next() method.
2519 When all members have been read, set TarFile as _loaded.
2520 """
Martin v. Löwis637431b2005-03-03 23:12:42 +00002521 # Fix for SF #1100429: Under rare circumstances it can
2522 # happen that getmembers() is called during iteration,
2523 # which will cause TarIter to stop prematurely.
2524 if not self.tarfile._loaded:
2525 tarinfo = self.tarfile.next()
2526 if not tarinfo:
2527 self.tarfile._loaded = True
2528 raise StopIteration
2529 else:
2530 try:
2531 tarinfo = self.tarfile.members[self.index]
2532 except IndexError:
2533 raise StopIteration
2534 self.index += 1
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002535 return tarinfo
2536
2537# Helper classes for sparse file support
2538class _section:
2539 """Base class for _data and _hole.
2540 """
2541 def __init__(self, offset, size):
2542 self.offset = offset
2543 self.size = size
2544 def __contains__(self, offset):
2545 return self.offset <= offset < self.offset + self.size
2546
2547class _data(_section):
2548 """Represent a data section in a sparse file.
2549 """
2550 def __init__(self, offset, size, realpos):
2551 _section.__init__(self, offset, size)
2552 self.realpos = realpos
2553
2554class _hole(_section):
2555 """Represent a hole section in a sparse file.
2556 """
2557 pass
2558
2559class _ringbuffer(list):
2560 """Ringbuffer class which increases performance
2561 over a regular list.
2562 """
2563 def __init__(self):
2564 self.idx = 0
2565 def find(self, offset):
2566 idx = self.idx
2567 while True:
2568 item = self[idx]
2569 if offset in item:
2570 break
2571 idx += 1
2572 if idx == len(self):
2573 idx = 0
2574 if idx == self.idx:
2575 # End of File
2576 return None
2577 self.idx = idx
2578 return item
2579
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002580#--------------------
2581# exported functions
2582#--------------------
2583def is_tarfile(name):
2584 """Return True if name points to a tar archive that we
2585 are able to handle, else return False.
2586 """
2587 try:
2588 t = open(name)
2589 t.close()
2590 return True
2591 except TarError:
2592 return False
2593
Guido van Rossume7ba4952007-06-06 23:52:48 +00002594bltn_open = open
Neal Norwitzb9ef4ae2003-01-05 23:19:43 +00002595open = TarFile.open