Debian Codegraph @

lib-python/3/tarfile.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #-------------------------------------------------------------------
3 # tarfile.py
4 #-------------------------------------------------------------------
5 # Copyright (C) 2002 Lars Gustaebel <[email protected]>
6 # All rights reserved.
7 #
8 # Permission is hereby granted, free of charge, to any person
9 # obtaining a copy of this software and associated documentation
10 # files (the "Software"), to deal in the Software without
11 # restriction, including without limitation the rights to use,
12 # copy, modify, merge, publish, distribute, sublicense, and/or sell
13 # copies of the Software, and to permit persons to whom the
14 # Software is furnished to do so, subject to the following
15 # conditions:
16 #
17 # The above copyright notice and this permission notice shall be
18 # included in all copies or substantial portions of the Software.
19 #
20 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
22 # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
24 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
25 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27 # OTHER DEALINGS IN THE SOFTWARE.
28 #
29 """Read from and write to tar format archives.
30 """
31
32 version = "0.9.0"
33 __author__ = "Lars Gust\u00e4bel ([email protected])"
34 __credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
35
36 #---------
37 # Imports
38 #---------
39 from builtins import open as bltn_open
40 import sys
41 import os
42 import io
43 import shutil
44 import stat
45 import time
46 import struct
47 import copy
48 import re
49 import warnings
50
51 try:
52 import pwd
53 except ImportError:
54 pwd = None
55 try:
56 import grp
57 except ImportError:
58 grp = None
59
60 # os.symlink on Windows prior to 6.0 raises NotImplementedError
61 symlink_exception = (AttributeError, NotImplementedError)
62 try:
63 # OSError (winerror=1314) will be raised if the caller does not hold the
64 # SeCreateSymbolicLinkPrivilege privilege
65 symlink_exception += (OSError,)
66 except NameError:
67 pass
68
69 # from tarfile import *
70 __all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError", "ReadError",
71 "CompressionError", "StreamError", "ExtractError", "HeaderError",
72 "ENCODING", "USTAR_FORMAT", "GNU_FORMAT", "PAX_FORMAT",
73 "DEFAULT_FORMAT", "open"]
74
75
76 #---------------------------------------------------------
77 # tar constants
78 #---------------------------------------------------------
79 NUL = b"\0" # the null character
80 BLOCKSIZE = 512 # length of processing blocks
81 RECORDSIZE = BLOCKSIZE * 20 # length of records
82 GNU_MAGIC = b"ustar \0" # magic gnu tar string
83 POSIX_MAGIC = b"ustar\x0000" # magic posix tar string
84
85 LENGTH_NAME = 100 # maximum length of a filename
86 LENGTH_LINK = 100 # maximum length of a linkname
87 LENGTH_PREFIX = 155 # maximum length of the prefix field
88
89 REGTYPE = b"0" # regular file
90 AREGTYPE = b"\0" # regular file
91 LNKTYPE = b"1" # link (inside tarfile)
92 SYMTYPE = b"2" # symbolic link
93 CHRTYPE = b"3" # character special device
94 BLKTYPE = b"4" # block special device
95 DIRTYPE = b"5" # directory
96 FIFOTYPE = b"6" # fifo special device
97 CONTTYPE = b"7" # contiguous file
98
99 GNUTYPE_LONGNAME = b"L" # GNU tar longname
100 GNUTYPE_LONGLINK = b"K" # GNU tar longlink
101 GNUTYPE_SPARSE = b"S" # GNU tar sparse file
102
103 XHDTYPE = b"x" # POSIX.1-2001 extended header
104 XGLTYPE = b"g" # POSIX.1-2001 global header
105 SOLARIS_XHDTYPE = b"X" # Solaris extended header
106
107 USTAR_FORMAT = 0 # POSIX.1-1988 (ustar) format
108 GNU_FORMAT = 1 # GNU tar format
109 PAX_FORMAT = 2 # POSIX.1-2001 (pax) format
110 DEFAULT_FORMAT = PAX_FORMAT
111
112 #---------------------------------------------------------
113 # tarfile constants
114 #---------------------------------------------------------
115 # File types that tarfile supports:
116 SUPPORTED_TYPES = (REGTYPE, AREGTYPE, LNKTYPE,
117 SYMTYPE, DIRTYPE, FIFOTYPE,
118 CONTTYPE, CHRTYPE, BLKTYPE,
119 GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
120 GNUTYPE_SPARSE)
121
122 # File types that will be treated as a regular file.
123 REGULAR_TYPES = (REGTYPE, AREGTYPE,
124 CONTTYPE, GNUTYPE_SPARSE)
125
126 # File types that are part of the GNU tar format.
127 GNU_TYPES = (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK,
128 GNUTYPE_SPARSE)
129
130 # Fields from a pax header that override a TarInfo attribute.
131 PAX_FIELDS = ("path", "linkpath", "size", "mtime",
132 "uid", "gid", "uname", "gname")
133
134 # Fields from a pax header that are affected by hdrcharset.
135 PAX_NAME_FIELDS = {"path", "linkpath", "uname", "gname"}
136
137 # Fields in a pax header that are numbers, all other fields
138 # are treated as strings.
139 PAX_NUMBER_FIELDS = {
140 "atime": float,
141 "ctime": float,
142 "mtime": float,
143 "uid": int,
144 "gid": int,
145 "size": int
146 }
147
148 #---------------------------------------------------------
149 # initialization
150 #---------------------------------------------------------
151 if os.name == "nt":
152 ENCODING = "utf-8"
153 else:
154 ENCODING = sys.getfilesystemencoding()
155
156 #---------------------------------------------------------
157 # Some useful functions
158 #---------------------------------------------------------
159
160 def stn(s, length, encoding, errors):
161 """Convert a string to a null-terminated bytes object.
162 """
163 if s is None:
164 raise ValueError("metadata cannot contain None")
165 s = s.encode(encoding, errors)
166 return s[:length] + (length - len(s)) * NUL
167
168 def nts(s, encoding, errors):
169 """Convert a null-terminated bytes object to a string.
170 """
171 p = s.find(b"\0")
172 if p != -1:
173 s = s[:p]
174 return s.decode(encoding, errors)
175
176 def nti(s):
177 """Convert a number field to a python number.
178 """
179 # There are two possible encodings for a number field, see
180 # itn() below.
181 if s[0] in (0o200, 0o377):
182 n = 0
183 for i in range(len(s) - 1):
184 n <<= 8
185 n += s[i + 1]
186 if s[0] == 0o377:
187 n = -(256 ** (len(s) - 1) - n)
188 else:
189 try:
190 s = nts(s, "ascii", "strict")
191 n = int(s.strip() or "0", 8)
192 except ValueError:
193 raise InvalidHeaderError("invalid header")
194 return n
195
196 def itn(n, digits=8, format=DEFAULT_FORMAT):
197 """Convert a python number to a number field.
198 """
199 # POSIX 1003.1-1988 requires numbers to be encoded as a string of
200 # octal digits followed by a null-byte, this allows values up to
201 # (8**(digits-1))-1. GNU tar allows storing numbers greater than
202 # that if necessary. A leading 0o200 or 0o377 byte indicate this
203 # particular encoding, the following digits-1 bytes are a big-endian
204 # base-256 representation. This allows values up to (256**(digits-1))-1.
205 # A 0o200 byte indicates a positive number, a 0o377 byte a negative
206 # number.
207 original_n = n
208 n = int(n)
209 if 0 <= n < 8 ** (digits - 1):
210 s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL
211 elif format == GNU_FORMAT and -256 ** (digits - 1) <= n < 256 ** (digits - 1):
212 if n >= 0:
213 s = bytearray([0o200])
214 else:
215 s = bytearray([0o377])
216 n = 256 ** digits + n
217
218 for i in range(digits - 1):
219 s.insert(1, n & 0o377)
220 n >>= 8
221 else:
222 raise ValueError("overflow in number field")
223
224 return s
225
226 def calc_chksums(buf):
227 """Calculate the checksum for a member's header by summing up all
228 characters except for the chksum field which is treated as if
229 it was filled with spaces. According to the GNU tar sources,
230 some tars (Sun and NeXT) calculate chksum with signed char,
231 which will be different if there are chars in the buffer with
232 the high bit set. So we calculate two checksums, unsigned and
233 signed.
234 """
235 unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf))
236 signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf))
237 return unsigned_chksum, signed_chksum
238
239 def copyfileobj(src, dst, length=None, exception=OSError, bufsize=None):
240 """Copy length bytes from fileobj src to fileobj dst.
241 If length is None, copy the entire content.
242 """
243 bufsize = bufsize or 16 * 1024
244 if length == 0:
245 return
246 if length is None:
247 shutil.copyfileobj(src, dst, bufsize)
248 return
249
250 blocks, remainder = divmod(length, bufsize)
251 for b in range(blocks):
252 buf = src.read(bufsize)
253 if len(buf) < bufsize:
254 raise exception("unexpected end of data")
255 dst.write(buf)
256
257 if remainder != 0:
258 buf = src.read(remainder)
259 if len(buf) < remainder:
260 raise exception("unexpected end of data")
261 dst.write(buf)
262 return
263
264 def _safe_print(s):
265 encoding = getattr(sys.stdout, 'encoding', None)
266 if encoding is not None:
267 s = s.encode(encoding, 'backslashreplace').decode(encoding)
268 print(s, end=' ')
269
270
271 class TarError(Exception):
272 """Base exception."""
273 pass
274 class ExtractError(TarError):
275 """General exception for extract errors."""
276 pass
277 class ReadError(TarError):
278 """Exception for unreadable tar archives."""
279 pass
280 class CompressionError(TarError):
281 """Exception for unavailable compression methods."""
282 pass
283 class StreamError(TarError):
284 """Exception for unsupported operations on stream-like TarFiles."""
285 pass
286 class HeaderError(TarError):
287 """Base exception for header errors."""
288 pass
289 class EmptyHeaderError(HeaderError):
290 """Exception for empty headers."""
291 pass
292 class TruncatedHeaderError(HeaderError):
293 """Exception for truncated headers."""
294 pass
295 class EOFHeaderError(HeaderError):
296 """Exception for end of file headers."""
297 pass
298 class InvalidHeaderError(HeaderError):
299 """Exception for invalid headers."""
300 pass
301 class SubsequentHeaderError(HeaderError):
302 """Exception for missing and invalid extended headers."""
303 pass
304
305 #---------------------------
306 # internal stream interface
307 #---------------------------
308 class _LowLevelFile:
309 """Low-level file object. Supports reading and writing.
310 It is used instead of a regular file object for streaming
311 access.
312 """
313
314 def __init__(self, name, mode):
315 mode = {
316 "r": os.O_RDONLY,
317 "w": os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
318 }[mode]
319 if hasattr(os, "O_BINARY"):
320 mode |= os.O_BINARY
321 self.fd = os.open(name, mode, 0o666)
322
323 def close(self):
324 os.close(self.fd)
325
326 def read(self, size):
327 return os.read(self.fd, size)
328
329 def write(self, s):
330 os.write(self.fd, s)
331
332 class _Stream:
333 """Class that serves as an adapter between TarFile and
334 a stream-like object. The stream-like object only
335 needs to have a read() or write() method that works with bytes,
336 and the method is accessed blockwise.
337 Use of gzip or bzip2 compression is possible.
338 A stream-like object could be for example: sys.stdin.buffer,
339 sys.stdout.buffer, a socket, a tape device etc.
340
341 _Stream is intended to be used only internally.
342 """
343
344 def __init__(self, name, mode, comptype, fileobj, bufsize):
345 """Construct a _Stream object.
346 """
347 self._extfileobj = True
348 if fileobj is None:
349 fileobj = _LowLevelFile(name, mode)
350 self._extfileobj = False
351
352 if comptype == '*':
353 # Enable transparent compression detection for the
354 # stream interface
355 fileobj = _StreamProxy(fileobj)
356 comptype = fileobj.getcomptype()
357
358 self.name = name or ""
359 self.mode = mode
360 self.comptype = comptype
361 self.fileobj = fileobj
362 self.bufsize = bufsize
363 self.buf = b""
364 self.pos = 0
365 self.closed = False
366
367 try:
368 if comptype == "gz":
369 try:
370 import zlib
371 except ImportError:
372 raise CompressionError("zlib module is not available") from None
373 self.zlib = zlib
374 self.crc = zlib.crc32(b"")
375 if mode == "r":
376 self.exception = zlib.error
377 self._init_read_gz()
378 else:
379 self._init_write_gz()
380
381 elif comptype == "bz2":
382 try:
383 import bz2
384 except ImportError:
385 raise CompressionError("bz2 module is not available") from None
386 if mode == "r":
387 self.dbuf = b""
388 self.cmp = bz2.BZ2Decompressor()
389 self.exception = OSError
390 else:
391 self.cmp = bz2.BZ2Compressor()
392
393 elif comptype == "xz":
394 try:
395 import lzma
396 except ImportError:
397 raise CompressionError("lzma module is not available") from None
398 if mode == "r":
399 self.dbuf = b""
400 self.cmp = lzma.LZMADecompressor()
401 self.exception = lzma.LZMAError
402 else:
403 self.cmp = lzma.LZMACompressor()
404
405 elif comptype != "tar":
406 raise CompressionError("unknown compression type %r" % comptype)
407
408 except:
409 if not self._extfileobj:
410 self.fileobj.close()
411 self.closed = True
412 raise
413
414 def __del__(self):
415 if hasattr(self, "closed") and not self.closed:
416 self.close()
417
418 def _init_write_gz(self):
419 """Initialize for writing with gzip compression.
420 """
421 self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED,
422 -self.zlib.MAX_WBITS,
423 self.zlib.DEF_MEM_LEVEL,
424 0)
425 timestamp = struct.pack("<L", int(time.time()))
426 self.__write(b"\037\213\010\010" + timestamp + b"\002\377")
427 if self.name.endswith(".gz"):
428 self.name = self.name[:-3]
429 # Honor "directory components removed" from RFC1952
430 self.name = os.path.basename(self.name)
431 # RFC1952 says we must use ISO-8859-1 for the FNAME field.
432 self.__write(self.name.encode("iso-8859-1", "replace") + NUL)
433
434 def write(self, s):
435 """Write string s to the stream.
436 """
437 if self.comptype == "gz":
438 self.crc = self.zlib.crc32(s, self.crc)
439 self.pos += len(s)
440 if self.comptype != "tar":
441 s = self.cmp.compress(s)
442 self.__write(s)
443
444 def __write(self, s):
445 """Write string s to the stream if a whole new block
446 is ready to be written.
447 """
448 self.buf += s
449 while len(self.buf) > self.bufsize:
450 self.fileobj.write(self.buf[:self.bufsize])
451 self.buf = self.buf[self.bufsize:]
452
453 def close(self):
454 """Close the _Stream object. No operation should be
455 done on it afterwards.
456 """
457 if self.closed:
458 return
459
460 self.closed = True
461 try:
462 if self.mode == "w" and self.comptype != "tar":
463 self.buf += self.cmp.flush()
464
465 if self.mode == "w" and self.buf:
466 self.fileobj.write(self.buf)
467 self.buf = b""
468 if self.comptype == "gz":
469 self.fileobj.write(struct.pack("<L", self.crc))
470 self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF))
471 finally:
472 if not self._extfileobj:
473 self.fileobj.close()
474
475 def _init_read_gz(self):
476 """Initialize for reading a gzip compressed fileobj.
477 """
478 self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS)
479 self.dbuf = b""
480
481 # taken from gzip.GzipFile with some alterations
482 if self.__read(2) != b"\037\213":
483 raise ReadError("not a gzip file")
484 if self.__read(1) != b"\010":
485 raise CompressionError("unsupported compression method")
486
487 flag = ord(self.__read(1))
488 self.__read(6)
489
490 if flag & 4:
491 xlen = ord(self.__read(1)) + 256 * ord(self.__read(1))
492 self.read(xlen)
493 if flag & 8:
494 while True:
495 s = self.__read(1)
496 if not s or s == NUL:
497 break
498 if flag & 16:
499 while True:
500 s = self.__read(1)
501 if not s or s == NUL:
502 break
503 if flag & 2:
504 self.__read(2)
505
506 def tell(self):
507 """Return the stream's file pointer position.
508 """
509 return self.pos
510
511 def seek(self, pos=0):
512 """Set the stream's file pointer to pos. Negative seeking
513 is forbidden.
514 """
515 if pos - self.pos >= 0:
516 blocks, remainder = divmod(pos - self.pos, self.bufsize)
517 for i in range(blocks):
518 self.read(self.bufsize)
519 self.read(remainder)
520 else:
521 raise StreamError("seeking backwards is not allowed")
522 return self.pos
523
524 def read(self, size):
525 """Return the next size number of bytes from the stream."""
526 assert size is not None
527 buf = self._read(size)
528 self.pos += len(buf)
529 return buf
530
531 def _read(self, size):
532 """Return size bytes from the stream.
533 """
534 if self.comptype == "tar":
535 return self.__read(size)
536
537 c = len(self.dbuf)
538 t = [self.dbuf]
539 while c < size:
540 # Skip underlying buffer to avoid unaligned double buffering.
541 if self.buf:
542 buf = self.buf
543 self.buf = b""
544 else:
545 buf = self.fileobj.read(self.bufsize)
546 if not buf:
547 break
548 try:
549 buf = self.cmp.decompress(buf)
550 except self.exception as e:
551 raise ReadError("invalid compressed data") from e
552 t.append(buf)
553 c += len(buf)
554 t = b"".join(t)
555 self.dbuf = t[size:]
556 return t[:size]
557
558 def __read(self, size):
559 """Return size bytes from stream. If internal buffer is empty,
560 read another block from the stream.
561 """
562 c = len(self.buf)
563 t = [self.buf]
564 while c < size:
565 buf = self.fileobj.read(self.bufsize)
566 if not buf:
567 break
568 t.append(buf)
569 c += len(buf)
570 t = b"".join(t)
571 self.buf = t[size:]
572 return t[:size]
573 # class _Stream
574
575 class _StreamProxy(object):
576 """Small proxy class that enables transparent compression
577 detection for the Stream interface (mode 'r|*').
578 """
579
580 def __init__(self, fileobj):
581 self.fileobj = fileobj
582 self.buf = self.fileobj.read(BLOCKSIZE)
583
584 def read(self, size):
585 self.read = self.fileobj.read
586 return self.buf
587
588 def getcomptype(self):
589 if self.buf.startswith(b"\x1f\x8b\x08"):
590 return "gz"
591 elif self.buf[0:3] == b"BZh" and self.buf[4:10] == b"1AY&SY":
592 return "bz2"
593 elif self.buf.startswith((b"\x5d\x00\x00\x80", b"\xfd7zXZ")):
594 return "xz"
595 else:
596 return "tar"
597
598 def close(self):
599 self.fileobj.close()
600 # class StreamProxy
601
602 #------------------------
603 # Extraction file object
604 #------------------------
605 class _FileInFile(object):
606 """A thin wrapper around an existing file object that
607 provides a part of its data as an individual file
608 object.
609 """
610
611 def __init__(self, fileobj, offset, size, blockinfo=None):
612 self.fileobj = fileobj
613 self.offset = offset
614 self.size = size
615 self.position = 0
616 self.name = getattr(fileobj, "name", None)
617 self.closed = False
618
619 if blockinfo is None:
620 blockinfo = [(0, size)]
621
622 # Construct a map with data and zero blocks.
623 self.map_index = 0
624 self.map = []
625 lastpos = 0
626 realpos = self.offset
627 for offset, size in blockinfo:
628 if offset > lastpos:
629 self.map.append((False, lastpos, offset, None))
630 self.map.append((True, offset, offset + size, realpos))
631 realpos += size
632 lastpos = offset + size
633 if lastpos < self.size:
634 self.map.append((False, lastpos, self.size, None))
635
636 def flush(self):
637 pass
638
639 def readable(self):
640 return True
641
642 def writable(self):
643 return False
644
645 def seekable(self):
646 return self.fileobj.seekable()
647
648 def tell(self):
649 """Return the current file position.
650 """
651 return self.position
652
653 def seek(self, position, whence=io.SEEK_SET):
654 """Seek to a position in the file.
655 """
656 if whence == io.SEEK_SET:
657 self.position = min(max(position, 0), self.size)
658 elif whence == io.SEEK_CUR:
659 if position < 0:
660 self.position = max(self.position + position, 0)
661 else:
662 self.position = min(self.position + position, self.size)
663 elif whence == io.SEEK_END:
664 self.position = max(min(self.size + position, self.size), 0)
665 else:
666 raise ValueError("Invalid argument")
667 return self.position
668
669 def read(self, size=None):
670 """Read data from the file.
671 """
672 if size is None:
673 size = self.size - self.position
674 else:
675 size = min(size, self.size - self.position)
676
677 buf = b""
678 while size > 0:
679 while True:
680 data, start, stop, offset = self.map[self.map_index]
681 if start <= self.position < stop:
682 break
683 else:
684 self.map_index += 1
685 if self.map_index == len(self.map):
686 self.map_index = 0
687 length = min(size, stop - self.position)
688 if data:
689 self.fileobj.seek(offset + (self.position - start))
690 b = self.fileobj.read(length)
691 if len(b) != length:
692 raise ReadError("unexpected end of data")
693 buf += b
694 else:
695 buf += NUL * length
696 size -= length
697 self.position += length
698 return buf
699
700 def readinto(self, b):
701 buf = self.read(len(b))
702 b[:len(buf)] = buf
703 return len(buf)
704
705 def close(self):
706 self.closed = True
707 #class _FileInFile
708
709 class ExFileObject(io.BufferedReader):
710
711 def __init__(self, tarfile, tarinfo):
712 fileobj = _FileInFile(tarfile.fileobj, tarinfo.offset_data,
713 tarinfo.size, tarinfo.sparse)
714 super().__init__(fileobj)
715 #class ExFileObject
716
717
718 #-----------------------------
719 # extraction filters (PEP 706)
720 #-----------------------------
721
722 class FilterError(TarError):
723 pass
724
725 class AbsolutePathError(FilterError):
726 def __init__(self, tarinfo):
727 self.tarinfo = tarinfo
728 super().__init__(f'member {tarinfo.name!r} has an absolute path')
729
730 class OutsideDestinationError(FilterError):
731 def __init__(self, tarinfo, path):
732 self.tarinfo = tarinfo
733 self._path = path
734 super().__init__(f'{tarinfo.name!r} would be extracted to {path!r}, '
735 + 'which is outside the destination')
736
737 class SpecialFileError(FilterError):
738 def __init__(self, tarinfo):
739 self.tarinfo = tarinfo
740 super().__init__(f'{tarinfo.name!r} is a special file')
741
742 class AbsoluteLinkError(FilterError):
743 def __init__(self, tarinfo):
744 self.tarinfo = tarinfo
745 super().__init__(f'{tarinfo.name!r} is a link to an absolute path')
746
747 class LinkOutsideDestinationError(FilterError):
748 def __init__(self, tarinfo, path):
749 self.tarinfo = tarinfo
750 self._path = path
751 super().__init__(f'{tarinfo.name!r} would link to {path!r}, '
752 + 'which is outside the destination')
753
754 class LinkFallbackError(FilterError):
755 def __init__(self, tarinfo, path):
756 self.tarinfo = tarinfo
757 self._path = path
758 super().__init__(f'link {tarinfo.name!r} would be extracted as a '
759 + f'copy of {path!r}, which was rejected')
760
761 # Errors caused by filters -- both "fatal" and "non-fatal" -- that
762 # we consider to be issues with the argument, rather than a bug in the
763 # filter function
764 _FILTER_ERRORS = (FilterError, OSError, ExtractError)
765
766 def _get_filtered_attrs(member, dest_path, for_data=True):
767 new_attrs = {}
768 name = member.name
769 dest_path = os.path.realpath(dest_path, strict=os.path.ALLOW_MISSING)
770 # Strip leading / (tar's directory separator) from filenames.
771 # Include os.sep (target OS directory separator) as well.
772 if name.startswith(('/', os.sep)):
773 name = new_attrs['name'] = member.path.lstrip('/' + os.sep)
774 if os.path.isabs(name):
775 # Path is absolute even after stripping.
776 # For example, 'C:/foo' on Windows.
777 raise AbsolutePathError(member)
778 # Ensure we stay in the destination
779 target_path = os.path.realpath(os.path.join(dest_path, name),
780 strict=os.path.ALLOW_MISSING)
781 if os.path.commonpath([target_path, dest_path]) != dest_path:
782 raise OutsideDestinationError(member, target_path)
783 # Limit permissions (no high bits, and go-w)
784 mode = member.mode
785 if mode is not None:
786 # Strip high bits & group/other write bits
787 mode = mode & 0o755
788 if for_data:
789 # For data, handle permissions & file types
790 if member.isreg() or member.islnk():
791 if not mode & 0o100:
792 # Clear executable bits if not executable by user
793 mode &= ~0o111
794 # Ensure owner can read & write
795 mode |= 0o600
796 elif member.isdir() or member.issym():
797 # Ignore mode for directories & symlinks
798 mode = None
799 else:
800 # Reject special files
801 raise SpecialFileError(member)
802 if mode != member.mode:
803 new_attrs['mode'] = mode
804 if for_data:
805 # Ignore ownership for 'data'
806 if member.uid is not None:
807 new_attrs['uid'] = None
808 if member.gid is not None:
809 new_attrs['gid'] = None
810 if member.uname is not None:
811 new_attrs['uname'] = None
812 if member.gname is not None:
813 new_attrs['gname'] = None
814 # Check link destination for 'data'
815 if member.islnk() or member.issym():
816 if os.path.isabs(member.linkname):
817 raise AbsoluteLinkError(member)
818 normalized = os.path.normpath(member.linkname)
819 if normalized != member.linkname:
820 new_attrs['linkname'] = normalized
821 if member.issym():
822 target_path = os.path.join(dest_path,
823 os.path.dirname(name),
824 member.linkname)
825 else:
826 target_path = os.path.join(dest_path,
827 member.linkname)
828 target_path = os.path.realpath(target_path,
829 strict=os.path.ALLOW_MISSING)
830 if os.path.commonpath([target_path, dest_path]) != dest_path:
831 raise LinkOutsideDestinationError(member, target_path)
832 return new_attrs
833
834 def fully_trusted_filter(member, dest_path):
835 return member
836
837 def tar_filter(member, dest_path):
838 new_attrs = _get_filtered_attrs(member, dest_path, False)
839 if new_attrs:
840 return member.replace(**new_attrs, deep=False)
841 return member
842
843 def data_filter(member, dest_path):
844 new_attrs = _get_filtered_attrs(member, dest_path, True)
845 if new_attrs:
846 return member.replace(**new_attrs, deep=False)
847 return member
848
849 _NAMED_FILTERS = {
850 "fully_trusted": fully_trusted_filter,
851 "tar": tar_filter,
852 "data": data_filter,
853 }
854
855 #------------------
856 # Exported Classes
857 #------------------
858
859 # Sentinel for replace() defaults, meaning "don't change the attribute"
860 _KEEP = object()
861
862 # Header length is digits followed by a space.
863 _header_length_prefix_re = re.compile(br"([0-9]{1,20}) ")
864
865 class TarInfo(object):
866 """Informational class which holds the details about an
867 archive member given by a tar header block.
868 TarInfo objects are returned by TarFile.getmember(),
869 TarFile.getmembers() and TarFile.gettarinfo() and are
870 usually created internally.
871 """
872
873 __slots__ = dict(
874 name = 'Name of the archive member.',
875 mode = 'Permission bits.',
876 uid = 'User ID of the user who originally stored this member.',
877 gid = 'Group ID of the user who originally stored this member.',
878 size = 'Size in bytes.',
879 mtime = 'Time of last modification.',
880 chksum = 'Header checksum.',
881 type = ('File type. type is usually one of these constants: '
882 'REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, '
883 'CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.'),
884 linkname = ('Name of the target file name, which is only present '
885 'in TarInfo objects of type LNKTYPE and SYMTYPE.'),
886 uname = 'User name.',
887 gname = 'Group name.',
888 devmajor = 'Device major number.',
889 devminor = 'Device minor number.',
890 offset = 'The tar header starts here.',
891 offset_data = "The file's data starts here.",
892 pax_headers = ('A dictionary containing key-value pairs of an '
893 'associated pax extended header.'),
894 sparse = 'Sparse member information.',
895 tarfile = None,
896 _sparse_structs = None,
897 _link_target = None,
898 )
899
900 def __init__(self, name=""):
901 """Construct a TarInfo object. name is the optional name
902 of the member.
903 """
904 self.name = name # member name
905 self.mode = 0o644 # file permissions
906 self.uid = 0 # user id
907 self.gid = 0 # group id
908 self.size = 0 # file size
909 self.mtime = 0 # modification time
910 self.chksum = 0 # header checksum
911 self.type = REGTYPE # member type
912 self.linkname = "" # link name
913 self.uname = "" # user name
914 self.gname = "" # group name
915 self.devmajor = 0 # device major number
916 self.devminor = 0 # device minor number
917
918 self.offset = 0 # the tar header starts here
919 self.offset_data = 0 # the file's data starts here
920
921 self.sparse = None # sparse member information
922 self.pax_headers = {} # pax header information
923
924 @property
925 def path(self):
926 'In pax headers, "name" is called "path".'
927 return self.name
928
929 @path.setter
930 def path(self, name):
931 self.name = name
932
933 @property
934 def linkpath(self):
935 'In pax headers, "linkname" is called "linkpath".'
936 return self.linkname
937
938 @linkpath.setter
939 def linkpath(self, linkname):
940 self.linkname = linkname
941
942 def __repr__(self):
943 return "<%s %r at %#x>" % (self.__class__.__name__,self.name,id(self))
944
945 def replace(self, *,
946 name=_KEEP, mtime=_KEEP, mode=_KEEP, linkname=_KEEP,
947 uid=_KEEP, gid=_KEEP, uname=_KEEP, gname=_KEEP,
948 deep=True, _KEEP=_KEEP):
949 """Return a deep copy of self with the given attributes replaced.
950 """
951 if deep:
952 result = copy.deepcopy(self)
953 else:
954 result = copy.copy(self)
955 if name is not _KEEP:
956 result.name = name
957 if mtime is not _KEEP:
958 result.mtime = mtime
959 if mode is not _KEEP:
960 result.mode = mode
961 if linkname is not _KEEP:
962 result.linkname = linkname
963 if uid is not _KEEP:
964 result.uid = uid
965 if gid is not _KEEP:
966 result.gid = gid
967 if uname is not _KEEP:
968 result.uname = uname
969 if gname is not _KEEP:
970 result.gname = gname
971 return result
972
973 def get_info(self):
974 """Return the TarInfo's attributes as a dictionary.
975 """
976 if self.mode is None:
977 mode = None
978 else:
979 mode = self.mode & 0o7777
980 info = {
981 "name": self.name,
982 "mode": mode,
983 "uid": self.uid,
984 "gid": self.gid,
985 "size": self.size,
986 "mtime": self.mtime,
987 "chksum": self.chksum,
988 "type": self.type,
989 "linkname": self.linkname,
990 "uname": self.uname,
991 "gname": self.gname,
992 "devmajor": self.devmajor,
993 "devminor": self.devminor
994 }
995
996 if info["type"] == DIRTYPE and not info["name"].endswith("/"):
997 info["name"] += "/"
998
999 return info
1000
1001 def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="surrogateescape"):
1002 """Return a tar header as a string of 512 byte blocks.
1003 """
1004 info = self.get_info()
1005 for name, value in info.items():
1006 if value is None:
1007 raise ValueError("%s may not be None" % name)
1008
1009 if format == USTAR_FORMAT:
1010 return self.create_ustar_header(info, encoding, errors)
1011 elif format == GNU_FORMAT:
1012 return self.create_gnu_header(info, encoding, errors)
1013 elif format == PAX_FORMAT:
1014 return self.create_pax_header(info, encoding)
1015 else:
1016 raise ValueError("invalid format")
1017
1018 def create_ustar_header(self, info, encoding, errors):
1019 """Return the object as a ustar header block.
1020 """
1021 info["magic"] = POSIX_MAGIC
1022
1023 if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
1024 raise ValueError("linkname is too long")
1025
1026 if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
1027 info["prefix"], info["name"] = self._posix_split_name(info["name"], encoding, errors)
1028
1029 return self._create_header(info, USTAR_FORMAT, encoding, errors)
1030
1031 def create_gnu_header(self, info, encoding, errors):
1032 """Return the object as a GNU header block sequence.
1033 """
1034 info["magic"] = GNU_MAGIC
1035
1036 buf = b""
1037 if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK:
1038 buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors)
1039
1040 if len(info["name"].encode(encoding, errors)) > LENGTH_NAME:
1041 buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors)
1042
1043 return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
1044
1045 def create_pax_header(self, info, encoding):
1046 """Return the object as a ustar header block. If it cannot be
1047 represented this way, prepend a pax extended header sequence
1048 with supplement information.
1049 """
1050 info["magic"] = POSIX_MAGIC
1051 pax_headers = self.pax_headers.copy()
1052
1053 # Test string fields for values that exceed the field length or cannot
1054 # be represented in ASCII encoding.
1055 for name, hname, length in (
1056 ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
1057 ("uname", "uname", 32), ("gname", "gname", 32)):
1058
1059 if hname in pax_headers:
1060 # The pax header has priority.
1061 continue
1062
1063 # Try to encode the string as ASCII.
1064 try:
1065 info[name].encode("ascii", "strict")
1066 except UnicodeEncodeError:
1067 pax_headers[hname] = info[name]
1068 continue
1069
1070 if len(info[name]) > length:
1071 pax_headers[hname] = info[name]
1072
1073 # Test number fields for values that exceed the field limit or values
1074 # that like to be stored as float.
1075 for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
1076 needs_pax = False
1077
1078 val = info[name]
1079 val_is_float = isinstance(val, float)
1080 val_int = round(val) if val_is_float else val
1081 if not 0 <= val_int < 8 ** (digits - 1):
1082 # Avoid overflow.
1083 info[name] = 0
1084 needs_pax = True
1085 elif val_is_float:
1086 # Put rounded value in ustar header, and full
1087 # precision value in pax header.
1088 info[name] = val_int
1089 needs_pax = True
1090
1091 # The existing pax header has priority.
1092 if needs_pax and name not in pax_headers:
1093 pax_headers[name] = str(val)
1094
1095 # Create a pax extended header if necessary.
1096 if pax_headers:
1097 buf = self._create_pax_generic_header(pax_headers, XHDTYPE, encoding)
1098 else:
1099 buf = b""
1100
1101 return buf + self._create_header(info, USTAR_FORMAT, "ascii", "replace")
1102
1103 @classmethod
1104 def create_pax_global_header(cls, pax_headers):
1105 """Return the object as a pax global header block sequence.
1106 """
1107 return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8")
1108
1109 def _posix_split_name(self, name, encoding, errors):
1110 """Split a name longer than 100 chars into a prefix
1111 and a name part.
1112 """
1113 components = name.split("/")
1114 for i in range(1, len(components)):
1115 prefix = "/".join(components[:i])
1116 name = "/".join(components[i:])
1117 if len(prefix.encode(encoding, errors)) <= LENGTH_PREFIX and \
1118 len(name.encode(encoding, errors)) <= LENGTH_NAME:
1119 break
1120 else:
1121 raise ValueError("name is too long")
1122
1123 return prefix, name
1124
1125 @staticmethod
1126 def _create_header(info, format, encoding, errors):
1127 """Return a header block. info is a dictionary with file
1128 information, format must be one of the *_FORMAT constants.
1129 """
1130 has_device_fields = info.get("type") in (CHRTYPE, BLKTYPE)
1131 if has_device_fields:
1132 devmajor = itn(info.get("devmajor", 0), 8, format)
1133 devminor = itn(info.get("devminor", 0), 8, format)
1134 else:
1135 devmajor = stn("", 8, encoding, errors)
1136 devminor = stn("", 8, encoding, errors)
1137
1138 # None values in metadata should cause ValueError.
1139 # itn()/stn() do this for all fields except type.
1140 filetype = info.get("type", REGTYPE)
1141 if filetype is None:
1142 raise ValueError("TarInfo.type must not be None")
1143
1144 parts = [
1145 stn(info.get("name", ""), 100, encoding, errors),
1146 itn(info.get("mode", 0) & 0o7777, 8, format),
1147 itn(info.get("uid", 0), 8, format),
1148 itn(info.get("gid", 0), 8, format),
1149 itn(info.get("size", 0), 12, format),
1150 itn(info.get("mtime", 0), 12, format),
1151 b" ", # checksum field
1152 filetype,
1153 stn(info.get("linkname", ""), 100, encoding, errors),
1154 info.get("magic", POSIX_MAGIC),
1155 stn(info.get("uname", ""), 32, encoding, errors),
1156 stn(info.get("gname", ""), 32, encoding, errors),
1157 devmajor,
1158 devminor,
1159 stn(info.get("prefix", ""), 155, encoding, errors)
1160 ]
1161
1162 buf = struct.pack("%ds" % BLOCKSIZE, b"".join(parts))
1163 chksum = calc_chksums(buf[-BLOCKSIZE:])[0]
1164 buf = buf[:-364] + bytes("%06o\0" % chksum, "ascii") + buf[-357:]
1165 return buf
1166
1167 @staticmethod
1168 def _create_payload(payload):
1169 """Return the string payload filled with zero bytes
1170 up to the next 512 byte border.
1171 """
1172 blocks, remainder = divmod(len(payload), BLOCKSIZE)
1173 if remainder > 0:
1174 payload += (BLOCKSIZE - remainder) * NUL
1175 return payload
1176
1177 @classmethod
1178 def _create_gnu_long_header(cls, name, type, encoding, errors):
1179 """Return a GNUTYPE_LONGNAME or GNUTYPE_LONGLINK sequence
1180 for name.
1181 """
1182 name = name.encode(encoding, errors) + NUL
1183
1184 info = {}
1185 info["name"] = "././@LongLink"
1186 info["type"] = type
1187 info["size"] = len(name)
1188 info["magic"] = GNU_MAGIC
1189
1190 # create extended header + name blocks.
1191 return cls._create_header(info, USTAR_FORMAT, encoding, errors) + \
1192 cls._create_payload(name)
1193
1194 @classmethod
1195 def _create_pax_generic_header(cls, pax_headers, type, encoding):
1196 """Return a POSIX.1-2008 extended or global header sequence
1197 that contains a list of keyword, value pairs. The values
1198 must be strings.
1199 """
1200 # Check if one of the fields contains surrogate characters and thereby
1201 # forces hdrcharset=BINARY, see _proc_pax() for more information.
1202 binary = False
1203 for keyword, value in pax_headers.items():
1204 try:
1205 value.encode("utf-8", "strict")
1206 except UnicodeEncodeError:
1207 binary = True
1208 break
1209
1210 records = b""
1211 if binary:
1212 # Put the hdrcharset field at the beginning of the header.
1213 records += b"21 hdrcharset=BINARY\n"
1214
1215 for keyword, value in pax_headers.items():
1216 keyword = keyword.encode("utf-8")
1217 if binary:
1218 # Try to restore the original byte representation of `value'.
1219 # Needless to say, that the encoding must match the string.
1220 value = value.encode(encoding, "surrogateescape")
1221 else:
1222 value = value.encode("utf-8")
1223
1224 l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n'
1225 n = p = 0
1226 while True:
1227 n = l + len(str(p))
1228 if n == p:
1229 break
1230 p = n
1231 records += bytes(str(p), "ascii") + b" " + keyword + b"=" + value + b"\n"
1232
1233 # We use a hardcoded "././@PaxHeader" name like star does
1234 # instead of the one that POSIX recommends.
1235 info = {}
1236 info["name"] = "././@PaxHeader"
1237 info["type"] = type
1238 info["size"] = len(records)
1239 info["magic"] = POSIX_MAGIC
1240
1241 # Create pax header + record blocks.
1242 return cls._create_header(info, USTAR_FORMAT, "ascii", "replace") + \
1243 cls._create_payload(records)
1244
1245 @classmethod
1246 def frombuf(cls, buf, encoding, errors):
1247 """Construct a TarInfo object from a 512 byte bytes object.
1248 """
1249 if len(buf) == 0:
1250 raise EmptyHeaderError("empty header")
1251 if len(buf) != BLOCKSIZE:
1252 raise TruncatedHeaderError("truncated header")
1253 if buf.count(NUL) == BLOCKSIZE:
1254 raise EOFHeaderError("end of file header")
1255
1256 chksum = nti(buf[148:156])
1257 if chksum not in calc_chksums(buf):
1258 raise InvalidHeaderError("bad checksum")
1259
1260 obj = cls()
1261 obj.name = nts(buf[0:100], encoding, errors)
1262 obj.mode = nti(buf[100:108])
1263 obj.uid = nti(buf[108:116])
1264 obj.gid = nti(buf[116:124])
1265 obj.size = nti(buf[124:136])
1266 obj.mtime = nti(buf[136:148])
1267 obj.chksum = chksum
1268 obj.type = buf[156:157]
1269 obj.linkname = nts(buf[157:257], encoding, errors)
1270 obj.uname = nts(buf[265:297], encoding, errors)
1271 obj.gname = nts(buf[297:329], encoding, errors)
1272 obj.devmajor = nti(buf[329:337])
1273 obj.devminor = nti(buf[337:345])
1274 prefix = nts(buf[345:500], encoding, errors)
1275
1276 # Old V7 tar format represents a directory as a regular
1277 # file with a trailing slash.
1278 if obj.type == AREGTYPE and obj.name.endswith("/"):
1279 obj.type = DIRTYPE
1280
1281 # The old GNU sparse format occupies some of the unused
1282 # space in the buffer for up to 4 sparse structures.
1283 # Save them for later processing in _proc_sparse().
1284 if obj.type == GNUTYPE_SPARSE:
1285 pos = 386
1286 structs = []
1287 for i in range(4):
1288 try:
1289 offset = nti(buf[pos:pos + 12])
1290 numbytes = nti(buf[pos + 12:pos + 24])
1291 except ValueError:
1292 break
1293 structs.append((offset, numbytes))
1294 pos += 24
1295 isextended = bool(buf[482])
1296 origsize = nti(buf[483:495])
1297 obj._sparse_structs = (structs, isextended, origsize)
1298
1299 # Remove redundant slashes from directories.
1300 if obj.isdir():
1301 obj.name = obj.name.rstrip("/")
1302
1303 # Reconstruct a ustar longname.
1304 if prefix and obj.type not in GNU_TYPES:
1305 obj.name = prefix + "/" + obj.name
1306 return obj
1307
1308 @classmethod
1309 def fromtarfile(cls, tarfile):
1310 """Return the next TarInfo object from TarFile object
1311 tarfile.
1312 """
1313 buf = tarfile.fileobj.read(BLOCKSIZE)
1314 obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors)
1315 obj.offset = tarfile.fileobj.tell() - BLOCKSIZE
1316 return obj._proc_member(tarfile)
1317
1318 #--------------------------------------------------------------------------
1319 # The following are methods that are called depending on the type of a
1320 # member. The entry point is _proc_member() which can be overridden in a
1321 # subclass to add custom _proc_*() methods. A _proc_*() method MUST
1322 # implement the following
1323 # operations:
1324 # 1. Set self.offset_data to the position where the data blocks begin,
1325 # if there is data that follows.
1326 # 2. Set tarfile.offset to the position where the next member's header will
1327 # begin.
1328 # 3. Return self or another valid TarInfo object.
1329 def _proc_member(self, tarfile):
1330 """Choose the right processing method depending on
1331 the type and call it.
1332 """
1333 if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
1334 return self._proc_gnulong(tarfile)
1335 elif self.type == GNUTYPE_SPARSE:
1336 return self._proc_sparse(tarfile)
1337 elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
1338 return self._proc_pax(tarfile)
1339 else:
1340 return self._proc_builtin(tarfile)
1341
1342 def _proc_builtin(self, tarfile):
1343 """Process a builtin type or an unknown type which
1344 will be treated as a regular file.
1345 """
1346 self.offset_data = tarfile.fileobj.tell()
1347 offset = self.offset_data
1348 if self.isreg() or self.type not in SUPPORTED_TYPES:
1349 # Skip the following data blocks.
1350 offset += self._block(self.size)
1351 tarfile.offset = offset
1352
1353 # Patch the TarInfo object with saved global
1354 # header information.
1355 self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors)
1356
1357 # Remove redundant slashes from directories. This is to be consistent
1358 # with frombuf().
1359 if self.isdir():
1360 self.name = self.name.rstrip("/")
1361
1362 return self
1363
1364 def _proc_gnulong(self, tarfile):
1365 """Process the blocks that hold a GNU longname
1366 or longlink member.
1367 """
1368 buf = tarfile.fileobj.read(self._block(self.size))
1369
1370 # Fetch the next header and process it.
1371 try:
1372 next = self.fromtarfile(tarfile)
1373 except HeaderError as e:
1374 raise SubsequentHeaderError(str(e)) from None
1375
1376 # Patch the TarInfo object from the next header with
1377 # the longname information.
1378 next.offset = self.offset
1379 if self.type == GNUTYPE_LONGNAME:
1380 next.name = nts(buf, tarfile.encoding, tarfile.errors)
1381 elif self.type == GNUTYPE_LONGLINK:
1382 next.linkname = nts(buf, tarfile.encoding, tarfile.errors)
1383
1384 # Remove redundant slashes from directories. This is to be consistent
1385 # with frombuf().
1386 if next.isdir():
1387 next.name = next.name.removesuffix("/")
1388
1389 return next
1390
1391 def _proc_sparse(self, tarfile):
1392 """Process a GNU sparse header plus extra headers.
1393 """
1394 # We already collected some sparse structures in frombuf().
1395 structs, isextended, origsize = self._sparse_structs
1396 del self._sparse_structs
1397
1398 # Collect sparse structures from extended header blocks.
1399 while isextended:
1400 buf = tarfile.fileobj.read(BLOCKSIZE)
1401 pos = 0
1402 for i in range(21):
1403 try:
1404 offset = nti(buf[pos:pos + 12])
1405 numbytes = nti(buf[pos + 12:pos + 24])
1406 except ValueError:
1407 break
1408 if offset and numbytes:
1409 structs.append((offset, numbytes))
1410 pos += 24
1411 isextended = bool(buf[504])
1412 self.sparse = structs
1413
1414 self.offset_data = tarfile.fileobj.tell()
1415 tarfile.offset = self.offset_data + self._block(self.size)
1416 self.size = origsize
1417 return self
1418
1419 def _proc_pax(self, tarfile):
1420 """Process an extended or global header as described in
1421 POSIX.1-2008.
1422 """
1423 # Read the header information.
1424 buf = tarfile.fileobj.read(self._block(self.size))
1425
1426 # A pax header stores supplemental information for either
1427 # the following file (extended) or all following files
1428 # (global).
1429 if self.type == XGLTYPE:
1430 pax_headers = tarfile.pax_headers
1431 else:
1432 pax_headers = tarfile.pax_headers.copy()
1433
1434 # Parse pax header information. A record looks like that:
1435 # "%d %s=%s\n" % (length, keyword, value). length is the size
1436 # of the complete record including the length field itself and
1437 # the newline.
1438 pos = 0
1439 encoding = None
1440 raw_headers = []
1441 while len(buf) > pos and buf[pos] != 0x00:
1442 if not (match := _header_length_prefix_re.match(buf, pos)):
1443 raise InvalidHeaderError("invalid header")
1444 try:
1445 length = int(match.group(1))
1446 except ValueError:
1447 raise InvalidHeaderError("invalid header")
1448 # Headers must be at least 5 bytes, shortest being '5 x=\n'.
1449 # Value is allowed to be empty.
1450 if length < 5:
1451 raise InvalidHeaderError("invalid header")
1452 if pos + length > len(buf):
1453 raise InvalidHeaderError("invalid header")
1454
1455 header_value_end_offset = match.start(1) + length - 1 # Last byte of the header
1456 keyword_and_value = buf[match.end(1) + 1:header_value_end_offset]
1457 raw_keyword, equals, raw_value = keyword_and_value.partition(b"=")
1458
1459 # Check the framing of the header. The last character must be '\n' (0x0A)
1460 if not raw_keyword or equals != b"=" or buf[header_value_end_offset] != 0x0A:
1461 raise InvalidHeaderError("invalid header")
1462 raw_headers.append((length, raw_keyword, raw_value))
1463
1464 # Check if the pax header contains a hdrcharset field. This tells us
1465 # the encoding of the path, linkpath, uname and gname fields. Normally,
1466 # these fields are UTF-8 encoded but since POSIX.1-2008 tar
1467 # implementations are allowed to store them as raw binary strings if
1468 # the translation to UTF-8 fails. For the time being, we don't care about
1469 # anything other than "BINARY". The only other value that is currently
1470 # allowed by the standard is "ISO-IR 10646 2000 UTF-8" in other words UTF-8.
1471 # Note that we only follow the initial 'hdrcharset' setting to preserve
1472 # the initial behavior of the 'tarfile' module.
1473 if raw_keyword == b"hdrcharset" and encoding is None:
1474 if raw_value == b"BINARY":
1475 encoding = tarfile.encoding
1476 else: # This branch ensures only the first 'hdrcharset' header is used.
1477 encoding = "utf-8"
1478
1479 pos += length
1480
1481 # If no explicit hdrcharset is set, we use UTF-8 as a default.
1482 if encoding is None:
1483 encoding = "utf-8"
1484
1485 # After parsing the raw headers we can decode them to text.
1486 for length, raw_keyword, raw_value in raw_headers:
1487 # Normally, we could just use "utf-8" as the encoding and "strict"
1488 # as the error handler, but we better not take the risk. For
1489 # example, GNU tar <= 1.23 is known to store filenames it cannot
1490 # translate to UTF-8 as raw strings (unfortunately without a
1491 # hdrcharset=BINARY header).
1492 # We first try the strict standard encoding, and if that fails we
1493 # fall back on the user's encoding and error handler.
1494 keyword = self._decode_pax_field(raw_keyword, "utf-8", "utf-8",
1495 tarfile.errors)
1496 if keyword in PAX_NAME_FIELDS:
1497 value = self._decode_pax_field(raw_value, encoding, tarfile.encoding,
1498 tarfile.errors)
1499 else:
1500 value = self._decode_pax_field(raw_value, "utf-8", "utf-8",
1501 tarfile.errors)
1502
1503 pax_headers[keyword] = value
1504
1505 # Fetch the next header.
1506 try:
1507 next = self.fromtarfile(tarfile)
1508 except HeaderError as e:
1509 raise SubsequentHeaderError(str(e)) from None
1510
1511 # Process GNU sparse information.
1512 if "GNU.sparse.map" in pax_headers:
1513 # GNU extended sparse format version 0.1.
1514 self._proc_gnusparse_01(next, pax_headers)
1515
1516 elif "GNU.sparse.size" in pax_headers:
1517 # GNU extended sparse format version 0.0.
1518 self._proc_gnusparse_00(next, raw_headers)
1519
1520 elif pax_headers.get("GNU.sparse.major") == "1" and pax_headers.get("GNU.sparse.minor") == "0":
1521 # GNU extended sparse format version 1.0.
1522 self._proc_gnusparse_10(next, pax_headers, tarfile)
1523
1524 if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
1525 # Patch the TarInfo object with the extended header info.
1526 next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
1527 next.offset = self.offset
1528
1529 if "size" in pax_headers:
1530 # If the extended header replaces the size field,
1531 # we need to recalculate the offset where the next
1532 # header starts.
1533 offset = next.offset_data
1534 if next.isreg() or next.type not in SUPPORTED_TYPES:
1535 offset += next._block(next.size)
1536 tarfile.offset = offset
1537
1538 return next
1539
1540 def _proc_gnusparse_00(self, next, raw_headers):
1541 """Process a GNU tar extended sparse header, version 0.0.
1542 """
1543 offsets = []
1544 numbytes = []
1545 for _, keyword, value in raw_headers:
1546 if keyword == b"GNU.sparse.offset":
1547 try:
1548 offsets.append(int(value.decode()))
1549 except ValueError:
1550 raise InvalidHeaderError("invalid header")
1551
1552 elif keyword == b"GNU.sparse.numbytes":
1553 try:
1554 numbytes.append(int(value.decode()))
1555 except ValueError:
1556 raise InvalidHeaderError("invalid header")
1557
1558 next.sparse = list(zip(offsets, numbytes))
1559
1560 def _proc_gnusparse_01(self, next, pax_headers):
1561 """Process a GNU tar extended sparse header, version 0.1.
1562 """
1563 sparse = [int(x) for x in pax_headers["GNU.sparse.map"].split(",")]
1564 next.sparse = list(zip(sparse[::2], sparse[1::2]))
1565
1566 def _proc_gnusparse_10(self, next, pax_headers, tarfile):
1567 """Process a GNU tar extended sparse header, version 1.0.
1568 """
1569 fields = None
1570 sparse = []
1571 buf = tarfile.fileobj.read(BLOCKSIZE)
1572 fields, buf = buf.split(b"\n", 1)
1573 fields = int(fields)
1574 while len(sparse) < fields * 2:
1575 if b"\n" not in buf:
1576 buf += tarfile.fileobj.read(BLOCKSIZE)
1577 number, buf = buf.split(b"\n", 1)
1578 sparse.append(int(number))
1579 next.offset_data = tarfile.fileobj.tell()
1580 next.sparse = list(zip(sparse[::2], sparse[1::2]))
1581
1582 def _apply_pax_info(self, pax_headers, encoding, errors):
1583 """Replace fields with supplemental information from a previous
1584 pax extended or global header.
1585 """
1586 for keyword, value in pax_headers.items():
1587 if keyword == "GNU.sparse.name":
1588 setattr(self, "path", value)
1589 elif keyword == "GNU.sparse.size":
1590 setattr(self, "size", int(value))
1591 elif keyword == "GNU.sparse.realsize":
1592 setattr(self, "size", int(value))
1593 elif keyword in PAX_FIELDS:
1594 if keyword in PAX_NUMBER_FIELDS:
1595 try:
1596 value = PAX_NUMBER_FIELDS[keyword](value)
1597 except ValueError:
1598 value = 0
1599 if keyword == "path":
1600 value = value.rstrip("/")
1601 setattr(self, keyword, value)
1602
1603 self.pax_headers = pax_headers.copy()
1604
1605 def _decode_pax_field(self, value, encoding, fallback_encoding, fallback_errors):
1606 """Decode a single field from a pax record.
1607 """
1608 try:
1609 return value.decode(encoding, "strict")
1610 except UnicodeDecodeError:
1611 return value.decode(fallback_encoding, fallback_errors)
1612
1613 def _block(self, count):
1614 """Round up a byte count by BLOCKSIZE and return it,
1615 e.g. _block(834) => 1024.
1616 """
1617 # Only non-negative offsets are allowed
1618 if count < 0:
1619 raise InvalidHeaderError("invalid offset")
1620 blocks, remainder = divmod(count, BLOCKSIZE)
1621 if remainder:
1622 blocks += 1
1623 return blocks * BLOCKSIZE
1624
1625 def isreg(self):
1626 'Return True if the Tarinfo object is a regular file.'
1627 return self.type in REGULAR_TYPES
1628
1629 def isfile(self):
1630 'Return True if the Tarinfo object is a regular file.'
1631 return self.isreg()
1632
1633 def isdir(self):
1634 'Return True if it is a directory.'
1635 return self.type == DIRTYPE
1636
1637 def issym(self):
1638 'Return True if it is a symbolic link.'
1639 return self.type == SYMTYPE
1640
1641 def islnk(self):
1642 'Return True if it is a hard link.'
1643 return self.type == LNKTYPE
1644
1645 def ischr(self):
1646 'Return True if it is a character device.'
1647 return self.type == CHRTYPE
1648
1649 def isblk(self):
1650 'Return True if it is a block device.'
1651 return self.type == BLKTYPE
1652
1653 def isfifo(self):
1654 'Return True if it is a FIFO.'
1655 return self.type == FIFOTYPE
1656
1657 def issparse(self):
1658 return self.sparse is not None
1659
1660 def isdev(self):
1661 'Return True if it is one of character device, block device or FIFO.'
1662 return self.type in (CHRTYPE, BLKTYPE, FIFOTYPE)
1663 # class TarInfo
1664
1665 class TarFile(object):
1666 """The TarFile Class provides an interface to tar archives.
1667 """
1668
1669 debug = 0 # May be set from 0 (no msgs) to 3 (all msgs)
1670
1671 dereference = False # If true, add content of linked file to the
1672 # tar file, else the link.
1673
1674 ignore_zeros = False # If true, skips empty or invalid blocks and
1675 # continues processing.
1676
1677 errorlevel = 1 # If 0, fatal errors only appear in debug
1678 # messages (if debug >= 0). If > 0, errors
1679 # are passed to the caller as exceptions.
1680
1681 format = DEFAULT_FORMAT # The format to use when creating an archive.
1682
1683 encoding = ENCODING # Encoding for 8-bit character strings.
1684
1685 errors = None # Error handler for unicode conversion.
1686
1687 tarinfo = TarInfo # The default TarInfo class to use.
1688
1689 fileobject = ExFileObject # The file-object for extractfile().
1690
1691 extraction_filter = None # The default filter for extraction.
1692
1693 def __init__(self, name=None, mode="r", fileobj=None, format=None,
1694 tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
1695 errors="surrogateescape", pax_headers=None, debug=None,
1696 errorlevel=None, copybufsize=None):
1697 """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to
1698 read from an existing archive, 'a' to append data to an existing
1699 file or 'w' to create a new file overwriting an existing one. `mode'
1700 defaults to 'r'.
1701 If `fileobj' is given, it is used for reading or writing data. If it
1702 can be determined, `mode' is overridden by `fileobj's mode.
1703 `fileobj' is not closed, when TarFile is closed.
1704 """
1705 modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
1706 if mode not in modes:
1707 raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
1708 self.mode = mode
1709 self._mode = modes[mode]
1710
1711 if not fileobj:
1712 if self.mode == "a" and not os.path.exists(name):
1713 # Create nonexistent files in append mode.
1714 self.mode = "w"
1715 self._mode = "wb"
1716 fileobj = bltn_open(name, self._mode)
1717 self._extfileobj = False
1718 else:
1719 if (name is None and hasattr(fileobj, "name") and
1720 isinstance(fileobj.name, (str, bytes))):
1721 name = fileobj.name
1722 if hasattr(fileobj, "mode"):
1723 self._mode = fileobj.mode
1724 self._extfileobj = True
1725 self.name = os.path.abspath(name) if name else None
1726 self.fileobj = fileobj
1727
1728 # Init attributes.
1729 if format is not None:
1730 self.format = format
1731 if tarinfo is not None:
1732 self.tarinfo = tarinfo
1733 if dereference is not None:
1734 self.dereference = dereference
1735 if ignore_zeros is not None:
1736 self.ignore_zeros = ignore_zeros
1737 if encoding is not None:
1738 self.encoding = encoding
1739 self.errors = errors
1740
1741 if pax_headers is not None and self.format == PAX_FORMAT:
1742 self.pax_headers = pax_headers
1743 else:
1744 self.pax_headers = {}
1745
1746 if debug is not None:
1747 self.debug = debug
1748 if errorlevel is not None:
1749 self.errorlevel = errorlevel
1750
1751 # Init datastructures.
1752 self.copybufsize = copybufsize
1753 self.closed = False
1754 self.members = [] # list of members as TarInfo objects
1755 self._loaded = False # flag if all members have been read
1756 self.offset = self.fileobj.tell()
1757 # current position in the archive file
1758 self.inodes = {} # dictionary caching the inodes of
1759 # archive members already added
1760
1761 try:
1762 if self.mode == "r":
1763 self.firstmember = None
1764 self.firstmember = self.next()
1765
1766 if self.mode == "a":
1767 # Move to the end of the archive,
1768 # before the first empty block.
1769 while True:
1770 self.fileobj.seek(self.offset)
1771 try:
1772 tarinfo = self.tarinfo.fromtarfile(self)
1773 self.members.append(tarinfo)
1774 except EOFHeaderError:
1775 self.fileobj.seek(self.offset)
1776 break
1777 except HeaderError as e:
1778 raise ReadError(str(e)) from None
1779
1780 if self.mode in ("a", "w", "x"):
1781 self._loaded = True
1782
1783 if self.pax_headers:
1784 buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
1785 self.fileobj.write(buf)
1786 self.offset += len(buf)
1787 except:
1788 if not self._extfileobj:
1789 self.fileobj.close()
1790 self.closed = True
1791 raise
1792
1793 #--------------------------------------------------------------------------
1794 # Below are the classmethods which act as alternate constructors to the
1795 # TarFile class. The open() method is the only one that is needed for
1796 # public use; it is the "super"-constructor and is able to select an
1797 # adequate "sub"-constructor for a particular compression using the mapping
1798 # from OPEN_METH.
1799 #
1800 # This concept allows one to subclass TarFile without losing the comfort of
1801 # the super-constructor. A sub-constructor is registered and made available
1802 # by adding it to the mapping in OPEN_METH.
1803
1804 @classmethod
1805 def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
1806 """Open a tar archive for reading, writing or appending. Return
1807 an appropriate TarFile class.
1808
1809 mode:
1810 'r' or 'r:*' open for reading with transparent compression
1811 'r:' open for reading exclusively uncompressed
1812 'r:gz' open for reading with gzip compression
1813 'r:bz2' open for reading with bzip2 compression
1814 'r:xz' open for reading with lzma compression
1815 'a' or 'a:' open for appending, creating the file if necessary
1816 'w' or 'w:' open for writing without compression
1817 'w:gz' open for writing with gzip compression
1818 'w:bz2' open for writing with bzip2 compression
1819 'w:xz' open for writing with lzma compression
1820
1821 'x' or 'x:' create a tarfile exclusively without compression, raise
1822 an exception if the file is already created
1823 'x:gz' create a gzip compressed tarfile, raise an exception
1824 if the file is already created
1825 'x:bz2' create a bzip2 compressed tarfile, raise an exception
1826 if the file is already created
1827 'x:xz' create an lzma compressed tarfile, raise an exception
1828 if the file is already created
1829
1830 'r|*' open a stream of tar blocks with transparent compression
1831 'r|' open an uncompressed stream of tar blocks for reading
1832 'r|gz' open a gzip compressed stream of tar blocks
1833 'r|bz2' open a bzip2 compressed stream of tar blocks
1834 'r|xz' open an lzma compressed stream of tar blocks
1835 'w|' open an uncompressed stream for writing
1836 'w|gz' open a gzip compressed stream for writing
1837 'w|bz2' open a bzip2 compressed stream for writing
1838 'w|xz' open an lzma compressed stream for writing
1839 """
1840
1841 if not name and not fileobj:
1842 raise ValueError("nothing to open")
1843
1844 if mode in ("r", "r:*"):
1845 # Find out which *open() is appropriate for opening the file.
1846 def not_compressed(comptype):
1847 return cls.OPEN_METH[comptype] == 'taropen'
1848 error_msgs = []
1849 for comptype in sorted(cls.OPEN_METH, key=not_compressed):
1850 func = getattr(cls, cls.OPEN_METH[comptype])
1851 if fileobj is not None:
1852 saved_pos = fileobj.tell()
1853 try:
1854 return func(name, "r", fileobj, **kwargs)
1855 except (ReadError, CompressionError) as e:
1856 error_msgs.append(f'- method {comptype}: {e!r}')
1857 if fileobj is not None:
1858 fileobj.seek(saved_pos)
1859 continue
1860 error_msgs_summary = '\n'.join(error_msgs)
1861 raise ReadError(f"file could not be opened successfully:\n{error_msgs_summary}")
1862
1863 elif ":" in mode:
1864 filemode, comptype = mode.split(":", 1)
1865 filemode = filemode or "r"
1866 comptype = comptype or "tar"
1867
1868 # Select the *open() function according to
1869 # given compression.
1870 if comptype in cls.OPEN_METH:
1871 func = getattr(cls, cls.OPEN_METH[comptype])
1872 else:
1873 raise CompressionError("unknown compression type %r" % comptype)
1874 return func(name, filemode, fileobj, **kwargs)
1875
1876 elif "|" in mode:
1877 filemode, comptype = mode.split("|", 1)
1878 filemode = filemode or "r"
1879 comptype = comptype or "tar"
1880
1881 if filemode not in ("r", "w"):
1882 raise ValueError("mode must be 'r' or 'w'")
1883
1884 stream = _Stream(name, filemode, comptype, fileobj, bufsize)
1885 try:
1886 t = cls(name, filemode, stream, **kwargs)
1887 except:
1888 stream.close()
1889 raise
1890 t._extfileobj = False
1891 return t
1892
1893 elif mode in ("a", "w", "x"):
1894 return cls.taropen(name, mode, fileobj, **kwargs)
1895
1896 raise ValueError("undiscernible mode")
1897
1898 @classmethod
1899 def taropen(cls, name, mode="r", fileobj=None, **kwargs):
1900 """Open uncompressed tar archive name for reading or writing.
1901 """
1902 if mode not in ("r", "a", "w", "x"):
1903 raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
1904 return cls(name, mode, fileobj, **kwargs)
1905
1906 @classmethod
1907 def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
1908 """Open gzip compressed tar archive name for reading or writing.
1909 Appending is not allowed.
1910 """
1911 if mode not in ("r", "w", "x"):
1912 raise ValueError("mode must be 'r', 'w' or 'x'")
1913
1914 try:
1915 from gzip import GzipFile
1916 except ImportError:
1917 raise CompressionError("gzip module is not available") from None
1918
1919 try:
1920 fileobj = GzipFile(name, mode + "b", compresslevel, fileobj)
1921 except OSError as e:
1922 if fileobj is not None and mode == 'r':
1923 raise ReadError("not a gzip file") from e
1924 raise
1925
1926 try:
1927 t = cls.taropen(name, mode, fileobj, **kwargs)
1928 except OSError as e:
1929 fileobj.close()
1930 if mode == 'r':
1931 raise ReadError("not a gzip file") from e
1932 raise
1933 except:
1934 fileobj.close()
1935 raise
1936 t._extfileobj = False
1937 return t
1938
1939 @classmethod
1940 def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
1941 """Open bzip2 compressed tar archive name for reading or writing.
1942 Appending is not allowed.
1943 """
1944 if mode not in ("r", "w", "x"):
1945 raise ValueError("mode must be 'r', 'w' or 'x'")
1946
1947 try:
1948 from bz2 import BZ2File
1949 except ImportError:
1950 raise CompressionError("bz2 module is not available") from None
1951
1952 fileobj = BZ2File(fileobj or name, mode, compresslevel=compresslevel)
1953
1954 try:
1955 t = cls.taropen(name, mode, fileobj, **kwargs)
1956 except (OSError, EOFError) as e:
1957 fileobj.close()
1958 if mode == 'r':
1959 raise ReadError("not a bzip2 file") from e
1960 raise
1961 except:
1962 fileobj.close()
1963 raise
1964 t._extfileobj = False
1965 return t
1966
1967 @classmethod
1968 def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
1969 """Open lzma compressed tar archive name for reading or writing.
1970 Appending is not allowed.
1971 """
1972 if mode not in ("r", "w", "x"):
1973 raise ValueError("mode must be 'r', 'w' or 'x'")
1974
1975 try:
1976 from lzma import LZMAFile, LZMAError
1977 except ImportError:
1978 raise CompressionError("lzma module is not available") from None
1979
1980 fileobj = LZMAFile(fileobj or name, mode, preset=preset)
1981
1982 try:
1983 t = cls.taropen(name, mode, fileobj, **kwargs)
1984 except (LZMAError, EOFError) as e:
1985 fileobj.close()
1986 if mode == 'r':
1987 raise ReadError("not an lzma file") from e
1988 raise
1989 except:
1990 fileobj.close()
1991 raise
1992 t._extfileobj = False
1993 return t
1994
1995 # All *open() methods are registered here.
1996 OPEN_METH = {
1997 "tar": "taropen", # uncompressed tar
1998 "gz": "gzopen", # gzip compressed tar
1999 "bz2": "bz2open", # bzip2 compressed tar
2000 "xz": "xzopen" # lzma compressed tar
2001 }
2002
2003 #--------------------------------------------------------------------------
2004 # The public methods which TarFile provides:
2005
2006 def close(self):
2007 """Close the TarFile. In write-mode, two finishing zero blocks are
2008 appended to the archive.
2009 """
2010 if self.closed:
2011 return
2012
2013 self.closed = True
2014 try:
2015 if self.mode in ("a", "w", "x"):
2016 self.fileobj.write(NUL * (BLOCKSIZE * 2))
2017 self.offset += (BLOCKSIZE * 2)
2018 # fill up the end with zero-blocks
2019 # (like option -b20 for tar does)
2020 blocks, remainder = divmod(self.offset, RECORDSIZE)
2021 if remainder > 0:
2022 self.fileobj.write(NUL * (RECORDSIZE - remainder))
2023 finally:
2024 if not self._extfileobj:
2025 self.fileobj.close()
2026
2027 def getmember(self, name):
2028 """Return a TarInfo object for member `name'. If `name' can not be
2029 found in the archive, KeyError is raised. If a member occurs more
2030 than once in the archive, its last occurrence is assumed to be the
2031 most up-to-date version.
2032 """
2033 tarinfo = self._getmember(name.rstrip('/'))
2034 if tarinfo is None:
2035 raise KeyError("filename %r not found" % name)
2036 return tarinfo
2037
2038 def getmembers(self):
2039 """Return the members of the archive as a list of TarInfo objects. The
2040 list has the same order as the members in the archive.
2041 """
2042 self._check()
2043 if not self._loaded: # if we want to obtain a list of
2044 self._load() # all members, we first have to
2045 # scan the whole archive.
2046 return self.members
2047
2048 def getnames(self):
2049 """Return the members of the archive as a list of their names. It has
2050 the same order as the list returned by getmembers().
2051 """
2052 return [tarinfo.name for tarinfo in self.getmembers()]
2053
2054 def gettarinfo(self, name=None, arcname=None, fileobj=None):
2055 """Create a TarInfo object from the result of os.stat or equivalent
2056 on an existing file. The file is either named by `name', or
2057 specified as a file object `fileobj' with a file descriptor. If
2058 given, `arcname' specifies an alternative name for the file in the
2059 archive, otherwise, the name is taken from the 'name' attribute of
2060 'fileobj', or the 'name' argument. The name should be a text
2061 string.
2062 """
2063 self._check("awx")
2064
2065 # When fileobj is given, replace name by
2066 # fileobj's real name.
2067 if fileobj is not None:
2068 name = fileobj.name
2069
2070 # Building the name of the member in the archive.
2071 # Backward slashes are converted to forward slashes,
2072 # Absolute paths are turned to relative paths.
2073 if arcname is None:
2074 arcname = name
2075 drv, arcname = os.path.splitdrive(arcname)
2076 arcname = arcname.replace(os.sep, "/")
2077 arcname = arcname.lstrip("/")
2078
2079 # Now, fill the TarInfo object with
2080 # information specific for the file.
2081 tarinfo = self.tarinfo()
2082 tarinfo.tarfile = self # Not needed
2083
2084 # Use os.stat or os.lstat, depending on if symlinks shall be resolved.
2085 if fileobj is None:
2086 if not self.dereference:
2087 statres = os.lstat(name)
2088 else:
2089 statres = os.stat(name)
2090 else:
2091 statres = os.fstat(fileobj.fileno())
2092 linkname = ""
2093
2094 stmd = statres.st_mode
2095 if stat.S_ISREG(stmd):
2096 inode = (statres.st_ino, statres.st_dev)
2097 if not self.dereference and statres.st_nlink > 1 and \
2098 inode in self.inodes and arcname != self.inodes[inode]:
2099 # Is it a hardlink to an already
2100 # archived file?
2101 type = LNKTYPE
2102 linkname = self.inodes[inode]
2103 else:
2104 # The inode is added only if its valid.
2105 # For win32 it is always 0.
2106 type = REGTYPE
2107 if inode[0]:
2108 self.inodes[inode] = arcname
2109 elif stat.S_ISDIR(stmd):
2110 type = DIRTYPE
2111 elif stat.S_ISFIFO(stmd):
2112 type = FIFOTYPE
2113 elif stat.S_ISLNK(stmd):
2114 type = SYMTYPE
2115 linkname = os.readlink(name)
2116 elif stat.S_ISCHR(stmd):
2117 type = CHRTYPE
2118 elif stat.S_ISBLK(stmd):
2119 type = BLKTYPE
2120 else:
2121 return None
2122
2123 # Fill the TarInfo object with all
2124 # information we can get.
2125 tarinfo.name = arcname
2126 tarinfo.mode = stmd
2127 tarinfo.uid = statres.st_uid
2128 tarinfo.gid = statres.st_gid
2129 if type == REGTYPE:
2130 tarinfo.size = statres.st_size
2131 else:
2132 tarinfo.size = 0
2133 tarinfo.mtime = statres.st_mtime
2134 tarinfo.type = type
2135 tarinfo.linkname = linkname
2136 if pwd:
2137 try:
2138 tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
2139 except KeyError:
2140 pass
2141 if grp:
2142 try:
2143 tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
2144 except KeyError:
2145 pass
2146
2147 if type in (CHRTYPE, BLKTYPE):
2148 if hasattr(os, "major") and hasattr(os, "minor"):
2149 tarinfo.devmajor = os.major(statres.st_rdev)
2150 tarinfo.devminor = os.minor(statres.st_rdev)
2151 return tarinfo
2152
2153 def list(self, verbose=True, *, members=None):
2154 """Print a table of contents to sys.stdout. If `verbose' is False, only
2155 the names of the members are printed. If it is True, an `ls -l'-like
2156 output is produced. `members' is optional and must be a subset of the
2157 list returned by getmembers().
2158 """
2159 self._check()
2160
2161 if members is None:
2162 members = self
2163 for tarinfo in members:
2164 if verbose:
2165 if tarinfo.mode is None:
2166 _safe_print("??????????")
2167 else:
2168 _safe_print(stat.filemode(tarinfo.mode))
2169 _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid,
2170 tarinfo.gname or tarinfo.gid))
2171 if tarinfo.ischr() or tarinfo.isblk():
2172 _safe_print("%10s" %
2173 ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor)))
2174 else:
2175 _safe_print("%10d" % tarinfo.size)
2176 if tarinfo.mtime is None:
2177 _safe_print("????-??-?? ??:??:??")
2178 else:
2179 _safe_print("%d-%02d-%02d %02d:%02d:%02d" \
2180 % time.localtime(tarinfo.mtime)[:6])
2181
2182 _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else ""))
2183
2184 if verbose:
2185 if tarinfo.issym():
2186 _safe_print("-> " + tarinfo.linkname)
2187 if tarinfo.islnk():
2188 _safe_print("link to " + tarinfo.linkname)
2189 print()
2190
2191 def add(self, name, arcname=None, recursive=True, *, filter=None):
2192 """Add the file `name' to the archive. `name' may be any type of file
2193 (directory, fifo, symbolic link, etc.). If given, `arcname'
2194 specifies an alternative name for the file in the archive.
2195 Directories are added recursively by default. This can be avoided by
2196 setting `recursive' to False. `filter' is a function
2197 that expects a TarInfo object argument and returns the changed
2198 TarInfo object, if it returns None the TarInfo object will be
2199 excluded from the archive.
2200 """
2201 self._check("awx")
2202
2203 if arcname is None:
2204 arcname = name
2205
2206 # Skip if somebody tries to archive the archive...
2207 if self.name is not None and os.path.abspath(name) == self.name:
2208 self._dbg(2, "tarfile: Skipped %r" % name)
2209 return
2210
2211 self._dbg(1, name)
2212
2213 # Create a TarInfo object from the file.
2214 tarinfo = self.gettarinfo(name, arcname)
2215
2216 if tarinfo is None:
2217 self._dbg(1, "tarfile: Unsupported type %r" % name)
2218 return
2219
2220 # Change or exclude the TarInfo object.
2221 if filter is not None:
2222 tarinfo = filter(tarinfo)
2223 if tarinfo is None:
2224 self._dbg(2, "tarfile: Excluded %r" % name)
2225 return
2226
2227 # Append the tar header and data to the archive.
2228 if tarinfo.isreg():
2229 with bltn_open(name, "rb") as f:
2230 self.addfile(tarinfo, f)
2231
2232 elif tarinfo.isdir():
2233 self.addfile(tarinfo)
2234 if recursive:
2235 for f in sorted(os.listdir(name)):
2236 self.add(os.path.join(name, f), os.path.join(arcname, f),
2237 recursive, filter=filter)
2238
2239 else:
2240 self.addfile(tarinfo)
2241
2242 def addfile(self, tarinfo, fileobj=None):
2243 """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
2244 given, it should be a binary file, and tarinfo.size bytes are read
2245 from it and added to the archive. You can create TarInfo objects
2246 directly, or by using gettarinfo().
2247 """
2248 self._check("awx")
2249
2250 tarinfo = copy.copy(tarinfo)
2251
2252 buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
2253 self.fileobj.write(buf)
2254 self.offset += len(buf)
2255 bufsize=self.copybufsize
2256 # If there's data to follow, append it.
2257 if fileobj is not None:
2258 copyfileobj(fileobj, self.fileobj, tarinfo.size, bufsize=bufsize)
2259 blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
2260 if remainder > 0:
2261 self.fileobj.write(NUL * (BLOCKSIZE - remainder))
2262 blocks += 1
2263 self.offset += blocks * BLOCKSIZE
2264
2265 self.members.append(tarinfo)
2266
2267 def _get_filter_function(self, filter):
2268 if filter is None:
2269 filter = self.extraction_filter
2270 if filter is None:
2271 return fully_trusted_filter
2272 if isinstance(filter, str):
2273 raise TypeError(
2274 'String names are not supported for '
2275 + 'TarFile.extraction_filter. Use a function such as '
2276 + 'tarfile.data_filter directly.')
2277 return filter
2278 if callable(filter):
2279 return filter
2280 try:
2281 return _NAMED_FILTERS[filter]
2282 except KeyError:
2283 raise ValueError(f"filter {filter!r} not found") from None
2284
2285 def extractall(self, path=".", members=None, *, numeric_owner=False,
2286 filter=None):
2287 """Extract all members from the archive to the current working
2288 directory and set owner, modification time and permissions on
2289 directories afterwards. `path' specifies a different directory
2290 to extract to. `members' is optional and must be a subset of the
2291 list returned by getmembers(). If `numeric_owner` is True, only
2292 the numbers for user/group names are used and not the names.
2293
2294 The `filter` function will be called on each member just
2295 before extraction.
2296 It can return a changed TarInfo or None to skip the member.
2297 String names of common filters are accepted.
2298 """
2299 directories = []
2300
2301 filter_function = self._get_filter_function(filter)
2302 if members is None:
2303 members = self
2304
2305 for member in members:
2306 tarinfo, unfiltered = self._get_extract_tarinfo(
2307 member, filter_function, path)
2308 if tarinfo is None:
2309 continue
2310 if tarinfo.isdir():
2311 # For directories, delay setting attributes until later,
2312 # since permissions can interfere with extraction and
2313 # extracting contents can reset mtime.
2314 directories.append(unfiltered)
2315 self._extract_one(tarinfo, path, set_attrs=not tarinfo.isdir(),
2316 numeric_owner=numeric_owner,
2317 filter_function=filter_function)
2318
2319 # Reverse sort directories.
2320 directories.sort(key=lambda a: a.name, reverse=True)
2321
2322
2323 # Set correct owner, mtime and filemode on directories.
2324 for unfiltered in directories:
2325 try:
2326 # Need to re-apply any filter, to take the *current* filesystem
2327 # state into account.
2328 try:
2329 tarinfo = filter_function(unfiltered, path)
2330 except _FILTER_ERRORS as exc:
2331 self._log_no_directory_fixup(unfiltered, repr(exc))
2332 continue
2333 if tarinfo is None:
2334 self._log_no_directory_fixup(unfiltered,
2335 'excluded by filter')
2336 continue
2337 dirpath = os.path.join(path, tarinfo.name)
2338 try:
2339 lstat = os.lstat(dirpath)
2340 except FileNotFoundError:
2341 self._log_no_directory_fixup(tarinfo, 'missing')
2342 continue
2343 if not stat.S_ISDIR(lstat.st_mode):
2344 # This is no longer a directory; presumably a later
2345 # member overwrote the entry.
2346 self._log_no_directory_fixup(tarinfo, 'not a directory')
2347 continue
2348 self.chown(tarinfo, dirpath, numeric_owner=numeric_owner)
2349 self.utime(tarinfo, dirpath)
2350 self.chmod(tarinfo, dirpath)
2351 except ExtractError as e:
2352 self._handle_nonfatal_error(e)
2353
2354 def _log_no_directory_fixup(self, member, reason):
2355 self._dbg(2, "tarfile: Not fixing up directory %r (%s)" %
2356 (member.name, reason))
2357
2358 def extract(self, member, path="", set_attrs=True, *, numeric_owner=False,
2359 filter=None):
2360 """Extract a member from the archive to the current working directory,
2361 using its full name. Its file information is extracted as accurately
2362 as possible. `member' may be a filename or a TarInfo object. You can
2363 specify a different directory using `path'. File attributes (owner,
2364 mtime, mode) are set unless `set_attrs' is False. If `numeric_owner`
2365 is True, only the numbers for user/group names are used and not
2366 the names.
2367
2368 The `filter` function will be called before extraction.
2369 It can return a changed TarInfo or None to skip the member.
2370 String names of common filters are accepted.
2371 """
2372 filter_function = self._get_filter_function(filter)
2373 tarinfo, unfiltered = self._get_extract_tarinfo(
2374 member, filter_function, path)
2375 if tarinfo is not None:
2376 self._extract_one(tarinfo, path, set_attrs, numeric_owner)
2377
2378 def _get_extract_tarinfo(self, member, filter_function, path):
2379 """Get (filtered, unfiltered) TarInfos from *member*
2380
2381 *member* might be a string.
2382
2383 Return (None, None) if not found.
2384 """
2385
2386 if isinstance(member, str):
2387 unfiltered = self.getmember(member)
2388 else:
2389 unfiltered = member
2390
2391 filtered = None
2392 try:
2393 filtered = filter_function(unfiltered, path)
2394 except (OSError, FilterError) as e:
2395 self._handle_fatal_error(e)
2396 except ExtractError as e:
2397 self._handle_nonfatal_error(e)
2398 if filtered is None:
2399 self._dbg(2, "tarfile: Excluded %r" % unfiltered.name)
2400 return None, None
2401
2402 # Prepare the link target for makelink().
2403 if filtered.islnk():
2404 filtered = copy.copy(filtered)
2405 filtered._link_target = os.path.join(path, filtered.linkname)
2406 return filtered, unfiltered
2407
2408 def _extract_one(self, tarinfo, path, set_attrs, numeric_owner,
2409 filter_function=None):
2410 """Extract from filtered tarinfo to disk.
2411
2412 filter_function is only used when extracting a *different*
2413 member (e.g. as fallback to creating a symlink)
2414 """
2415 self._check("r")
2416
2417 try:
2418 self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
2419 set_attrs=set_attrs,
2420 numeric_owner=numeric_owner,
2421 filter_function=filter_function,
2422 extraction_root=path)
2423 except OSError as e:
2424 self._handle_fatal_error(e)
2425 except ExtractError as e:
2426 self._handle_nonfatal_error(e)
2427
2428 def _handle_nonfatal_error(self, e):
2429 """Handle non-fatal error (ExtractError) according to errorlevel"""
2430 if self.errorlevel > 1:
2431 raise
2432 else:
2433 self._dbg(1, "tarfile: %s" % e)
2434
2435 def _handle_fatal_error(self, e):
2436 """Handle "fatal" error according to self.errorlevel"""
2437 if self.errorlevel > 0:
2438 raise
2439 elif isinstance(e, OSError):
2440 if e.filename is None:
2441 self._dbg(1, "tarfile: %s" % e.strerror)
2442 else:
2443 self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
2444 else:
2445 self._dbg(1, "tarfile: %s %s" % (type(e).__name__, e))
2446
2447 def extractfile(self, member):
2448 """Extract a member from the archive as a file object. `member' may be
2449 a filename or a TarInfo object. If `member' is a regular file or
2450 a link, an io.BufferedReader object is returned. For all other
2451 existing members, None is returned. If `member' does not appear
2452 in the archive, KeyError is raised.
2453 """
2454 self._check("r")
2455
2456 if isinstance(member, str):
2457 tarinfo = self.getmember(member)
2458 else:
2459 tarinfo = member
2460
2461 if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
2462 # Members with unknown types are treated as regular files.
2463 return self.fileobject(self, tarinfo)
2464
2465 elif tarinfo.islnk() or tarinfo.issym():
2466 if isinstance(self.fileobj, _Stream):
2467 # A small but ugly workaround for the case that someone tries
2468 # to extract a (sym)link as a file-object from a non-seekable
2469 # stream of tar blocks.
2470 raise StreamError("cannot extract (sym)link as file object")
2471 else:
2472 # A (sym)link's file object is its target's file object.
2473 return self.extractfile(self._find_link_target(tarinfo))
2474 else:
2475 # If there's no data associated with the member (directory, chrdev,
2476 # blkdev, etc.), return None instead of a file object.
2477 return None
2478
2479 def _extract_member(self, tarinfo, targetpath, set_attrs=True,
2480 numeric_owner=False, *, filter_function=None,
2481 extraction_root=None):
2482 """Extract the filtered TarInfo object tarinfo to a physical
2483 file called targetpath.
2484
2485 filter_function is only used when extracting a *different*
2486 member (e.g. as fallback to creating a symlink)
2487 """
2488 # Fetch the TarInfo object for the given name
2489 # and build the destination pathname, replacing
2490 # forward slashes to platform specific separators.
2491 targetpath = targetpath.rstrip("/")
2492 targetpath = targetpath.replace("/", os.sep)
2493
2494 # Create all upper directories.
2495 upperdirs = os.path.dirname(targetpath)
2496 if upperdirs and not os.path.exists(upperdirs):
2497 # Create directories that are not part of the archive with
2498 # default permissions.
2499 os.makedirs(upperdirs)
2500
2501 if tarinfo.islnk() or tarinfo.issym():
2502 self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
2503 else:
2504 self._dbg(1, tarinfo.name)
2505
2506 if tarinfo.isreg():
2507 self.makefile(tarinfo, targetpath)
2508 elif tarinfo.isdir():
2509 self.makedir(tarinfo, targetpath)
2510 elif tarinfo.isfifo():
2511 self.makefifo(tarinfo, targetpath)
2512 elif tarinfo.ischr() or tarinfo.isblk():
2513 self.makedev(tarinfo, targetpath)
2514 elif tarinfo.islnk() or tarinfo.issym():
2515 self.makelink_with_filter(
2516 tarinfo, targetpath,
2517 filter_function=filter_function,
2518 extraction_root=extraction_root)
2519 elif tarinfo.type not in SUPPORTED_TYPES:
2520 self.makeunknown(tarinfo, targetpath)
2521 else:
2522 self.makefile(tarinfo, targetpath)
2523
2524 if set_attrs:
2525 self.chown(tarinfo, targetpath, numeric_owner)
2526 if not tarinfo.issym():
2527 self.chmod(tarinfo, targetpath)
2528 self.utime(tarinfo, targetpath)
2529
2530 #--------------------------------------------------------------------------
2531 # Below are the different file methods. They are called via
2532 # _extract_member() when extract() is called. They can be replaced in a
2533 # subclass to implement other functionality.
2534
2535 def makedir(self, tarinfo, targetpath):
2536 """Make a directory called targetpath.
2537 """
2538 try:
2539 if tarinfo.mode is None:
2540 # Use the system's default mode
2541 os.mkdir(targetpath)
2542 else:
2543 # Use a safe mode for the directory, the real mode is set
2544 # later in _extract_member().
2545 os.mkdir(targetpath, 0o700)
2546 except FileExistsError:
2547 if not os.path.isdir(targetpath):
2548 raise
2549
2550 def makefile(self, tarinfo, targetpath):
2551 """Make a file called targetpath.
2552 """
2553 source = self.fileobj
2554 source.seek(tarinfo.offset_data)
2555 bufsize = self.copybufsize
2556 with bltn_open(targetpath, "wb") as target:
2557 if tarinfo.sparse is not None:
2558 for offset, size in tarinfo.sparse:
2559 target.seek(offset)
2560 copyfileobj(source, target, size, ReadError, bufsize)
2561 target.seek(tarinfo.size)
2562 target.truncate()
2563 else:
2564 copyfileobj(source, target, tarinfo.size, ReadError, bufsize)
2565
2566 def makeunknown(self, tarinfo, targetpath):
2567 """Make a file from a TarInfo object with an unknown type
2568 at targetpath.
2569 """
2570 self.makefile(tarinfo, targetpath)
2571 self._dbg(1, "tarfile: Unknown file type %r, " \
2572 "extracted as regular file." % tarinfo.type)
2573
2574 def makefifo(self, tarinfo, targetpath):
2575 """Make a fifo called targetpath.
2576 """
2577 if hasattr(os, "mkfifo"):
2578 os.mkfifo(targetpath)
2579 else:
2580 raise ExtractError("fifo not supported by system")
2581
2582 def makedev(self, tarinfo, targetpath):
2583 """Make a character or block device called targetpath.
2584 """
2585 if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
2586 raise ExtractError("special devices not supported by system")
2587
2588 mode = tarinfo.mode
2589 if mode is None:
2590 # Use mknod's default
2591 mode = 0o600
2592 if tarinfo.isblk():
2593 mode |= stat.S_IFBLK
2594 else:
2595 mode |= stat.S_IFCHR
2596
2597 os.mknod(targetpath, mode,
2598 os.makedev(tarinfo.devmajor, tarinfo.devminor))
2599
2600 def makelink(self, tarinfo, targetpath):
2601 return self.makelink_with_filter(tarinfo, targetpath, None, None)
2602
2603 def makelink_with_filter(self, tarinfo, targetpath,
2604 filter_function, extraction_root):
2605 """Make a (symbolic) link called targetpath. If it cannot be created
2606 (platform limitation), we try to make a copy of the referenced file
2607 instead of a link.
2608
2609 filter_function is only used when extracting a *different*
2610 member (e.g. as fallback to creating a link).
2611 """
2612 keyerror_to_extracterror = False
2613 try:
2614 # For systems that support symbolic and hard links.
2615 if tarinfo.issym():
2616 if os.path.lexists(targetpath):
2617 # Avoid FileExistsError on following os.symlink.
2618 os.unlink(targetpath)
2619 os.symlink(tarinfo.linkname, targetpath)
2620 return
2621 else:
2622 if os.path.exists(tarinfo._link_target):
2623 os.link(tarinfo._link_target, targetpath)
2624 return
2625 except symlink_exception:
2626 keyerror_to_extracterror = True
2627
2628 try:
2629 unfiltered = self._find_link_target(tarinfo)
2630 except KeyError:
2631 if keyerror_to_extracterror:
2632 raise ExtractError(
2633 "unable to resolve link inside archive") from None
2634 else:
2635 raise
2636
2637 if filter_function is None:
2638 filtered = unfiltered
2639 else:
2640 if extraction_root is None:
2641 raise ExtractError(
2642 "makelink_with_filter: if filter_function is not None, "
2643 + "extraction_root must also not be None")
2644 try:
2645 filtered = filter_function(unfiltered, extraction_root)
2646 except _FILTER_ERRORS as cause:
2647 raise LinkFallbackError(tarinfo, unfiltered.name) from cause
2648 if filtered is not None:
2649 self._extract_member(filtered, targetpath,
2650 filter_function=filter_function,
2651 extraction_root=extraction_root)
2652
2653 def chown(self, tarinfo, targetpath, numeric_owner):
2654 """Set owner of targetpath according to tarinfo. If numeric_owner
2655 is True, use .gid/.uid instead of .gname/.uname. If numeric_owner
2656 is False, fall back to .gid/.uid when the search based on name
2657 fails.
2658 """
2659 if hasattr(os, "geteuid") and os.geteuid() == 0:
2660 # We have to be root to do so.
2661 g = tarinfo.gid
2662 u = tarinfo.uid
2663 if not numeric_owner:
2664 try:
2665 if grp and tarinfo.gname:
2666 g = grp.getgrnam(tarinfo.gname)[2]
2667 except KeyError:
2668 pass
2669 try:
2670 if pwd and tarinfo.uname:
2671 u = pwd.getpwnam(tarinfo.uname)[2]
2672 except KeyError:
2673 pass
2674 if g is None:
2675 g = -1
2676 if u is None:
2677 u = -1
2678 try:
2679 if tarinfo.issym() and hasattr(os, "lchown"):
2680 os.lchown(targetpath, u, g)
2681 else:
2682 os.chown(targetpath, u, g)
2683 except OSError as e:
2684 raise ExtractError("could not change owner") from e
2685
2686 def chmod(self, tarinfo, targetpath):
2687 """Set file permissions of targetpath according to tarinfo.
2688 """
2689 if tarinfo.mode is None:
2690 return
2691 try:
2692 os.chmod(targetpath, tarinfo.mode)
2693 except OSError as e:
2694 raise ExtractError("could not change mode") from e
2695
2696 def utime(self, tarinfo, targetpath):
2697 """Set modification time of targetpath according to tarinfo.
2698 """
2699 mtime = tarinfo.mtime
2700 if mtime is None:
2701 return
2702 if not hasattr(os, 'utime'):
2703 return
2704 try:
2705 os.utime(targetpath, (mtime, mtime))
2706 except OSError as e:
2707 raise ExtractError("could not change modification time") from e
2708
2709 #--------------------------------------------------------------------------
2710 def next(self):
2711 """Return the next member of the archive as a TarInfo object, when
2712 TarFile is opened for reading. Return None if there is no more
2713 available.
2714 """
2715 self._check("ra")
2716 if self.firstmember is not None:
2717 m = self.firstmember
2718 self.firstmember = None
2719 return m
2720
2721 # Advance the file pointer.
2722 if self.offset != self.fileobj.tell():
2723 if self.offset == 0:
2724 return None
2725 self.fileobj.seek(self.offset - 1)
2726 if not self.fileobj.read(1):
2727 raise ReadError("unexpected end of data")
2728
2729 # Read the next block.
2730 tarinfo = None
2731 while True:
2732 try:
2733 tarinfo = self.tarinfo.fromtarfile(self)
2734 except EOFHeaderError as e:
2735 if self.ignore_zeros:
2736 self._dbg(2, "0x%X: %s" % (self.offset, e))
2737 self.offset += BLOCKSIZE
2738 continue
2739 except InvalidHeaderError as e:
2740 if self.ignore_zeros:
2741 self._dbg(2, "0x%X: %s" % (self.offset, e))
2742 self.offset += BLOCKSIZE
2743 continue
2744 elif self.offset == 0:
2745 raise ReadError(str(e)) from None
2746 except EmptyHeaderError:
2747 if self.offset == 0:
2748 raise ReadError("empty file") from None
2749 except TruncatedHeaderError as e:
2750 if self.offset == 0:
2751 raise ReadError(str(e)) from None
2752 except SubsequentHeaderError as e:
2753 raise ReadError(str(e)) from None
2754 except Exception as e:
2755 try:
2756 import zlib
2757 if isinstance(e, zlib.error):
2758 raise ReadError(f'zlib error: {e}') from None
2759 else:
2760 raise e
2761 except ImportError:
2762 raise e
2763 break
2764
2765 if tarinfo is not None:
2766 self.members.append(tarinfo)
2767 else:
2768 self._loaded = True
2769
2770 return tarinfo
2771
2772 #--------------------------------------------------------------------------
2773 # Little helper methods:
2774
2775 def _getmember(self, name, tarinfo=None, normalize=False):
2776 """Find an archive member by name from bottom to top.
2777 If tarinfo is given, it is used as the starting point.
2778 """
2779 # Ensure that all members have been loaded.
2780 members = self.getmembers()
2781
2782 # Limit the member search list up to tarinfo.
2783 skipping = False
2784 if tarinfo is not None:
2785 try:
2786 index = members.index(tarinfo)
2787 except ValueError:
2788 # The given starting point might be a (modified) copy.
2789 # We'll later skip members until we find an equivalent.
2790 skipping = True
2791 else:
2792 # Happy fast path
2793 members = members[:index]
2794
2795 if normalize:
2796 name = os.path.normpath(name)
2797
2798 for member in reversed(members):
2799 if skipping:
2800 if tarinfo.offset == member.offset:
2801 skipping = False
2802 continue
2803 if normalize:
2804 member_name = os.path.normpath(member.name)
2805 else:
2806 member_name = member.name
2807
2808 if name == member_name:
2809 return member
2810
2811 if skipping:
2812 # Starting point was not found
2813 raise ValueError(tarinfo)
2814
2815 def _load(self):
2816 """Read through the entire archive file and look for readable
2817 members.
2818 """
2819 while True:
2820 tarinfo = self.next()
2821 if tarinfo is None:
2822 break
2823 self._loaded = True
2824
2825 def _check(self, mode=None):
2826 """Check if TarFile is still open, and if the operation's mode
2827 corresponds to TarFile's mode.
2828 """
2829 if self.closed:
2830 raise OSError("%s is closed" % self.__class__.__name__)
2831 if mode is not None and self.mode not in mode:
2832 raise OSError("bad operation for mode %r" % self.mode)
2833
2834 def _find_link_target(self, tarinfo):
2835 """Find the target member of a symlink or hardlink member in the
2836 archive.
2837 """
2838 if tarinfo.issym():
2839 # Always search the entire archive.
2840 linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname)))
2841 limit = None
2842 else:
2843 # Search the archive before the link, because a hard link is
2844 # just a reference to an already archived file.
2845 linkname = tarinfo.linkname
2846 limit = tarinfo
2847
2848 member = self._getmember(linkname, tarinfo=limit, normalize=True)
2849 if member is None:
2850 raise KeyError("linkname %r not found" % linkname)
2851 return member
2852
2853 def __iter__(self):
2854 """Provide an iterator object.
2855 """
2856 if self._loaded:
2857 yield from self.members
2858 return
2859
2860 # Yield items using TarFile's next() method.
2861 # When all members have been read, set TarFile as _loaded.
2862 index = 0
2863 # Fix for SF #1100429: Under rare circumstances it can
2864 # happen that getmembers() is called during iteration,
2865 # which will have already exhausted the next() method.
2866 if self.firstmember is not None:
2867 tarinfo = self.next()
2868 index += 1
2869 yield tarinfo
2870
2871 while True:
2872 if index < len(self.members):
2873 tarinfo = self.members[index]
2874 elif not self._loaded:
2875 tarinfo = self.next()
2876 if not tarinfo:
2877 self._loaded = True
2878 return
2879 else:
2880 return
2881 index += 1
2882 yield tarinfo
2883
2884 def _dbg(self, level, msg):
2885 """Write debugging output to sys.stderr.
2886 """
2887 if level <= self.debug:
2888 print(msg, file=sys.stderr)
2889
2890 def __enter__(self):
2891 self._check()
2892 return self
2893
2894 def __exit__(self, type, value, traceback):
2895 if type is None:
2896 self.close()
2897 else:
2898 # An exception occurred. We must not call close() because
2899 # it would try to write end-of-archive blocks and padding.
2900 if not self._extfileobj:
2901 self.fileobj.close()
2902 self.closed = True
2903
2904 #--------------------
2905 # exported functions
2906 #--------------------
2907
2908 def is_tarfile(name):
2909 """Return True if name points to a tar archive that we
2910 are able to handle, else return False.
2911
2912 'name' should be a string, file, or file-like object.
2913 """
2914 try:
2915 if hasattr(name, "read"):
2916 pos = name.tell()
2917 t = open(fileobj=name)
2918 name.seek(pos)
2919 else:
2920 t = open(name)
2921 t.close()
2922 return True
2923 except TarError:
2924 return False
2925
2926 open = TarFile.open
2927
2928
2929 def main():
2930 import argparse
2931
2932 description = 'A simple command-line interface for tarfile module.'
2933 parser = argparse.ArgumentParser(description=description)
2934 parser.add_argument('-v', '--verbose', action='store_true', default=False,
2935 help='Verbose output')
2936 parser.add_argument('--filter', metavar='<filtername>',
2937 choices=_NAMED_FILTERS,
2938 help='Filter for extraction')
2939
2940 group = parser.add_mutually_exclusive_group(required=True)
2941 group.add_argument('-l', '--list', metavar='<tarfile>',
2942 help='Show listing of a tarfile')
2943 group.add_argument('-e', '--extract', nargs='+',
2944 metavar=('<tarfile>', '<output_dir>'),
2945 help='Extract tarfile into target dir')
2946 group.add_argument('-c', '--create', nargs='+',
2947 metavar=('<name>', '<file>'),
2948 help='Create tarfile from sources')
2949 group.add_argument('-t', '--test', metavar='<tarfile>',
2950 help='Test if a tarfile is valid')
2951
2952 args = parser.parse_args()
2953
2954 if args.filter and args.extract is None:
2955 parser.exit(1, '--filter is only valid for extraction\n')
2956
2957 if args.test is not None:
2958 src = args.test
2959 if is_tarfile(src):
2960 with open(src, 'r') as tar:
2961 tar.getmembers()
2962 print(tar.getmembers(), file=sys.stderr)
2963 if args.verbose:
2964 print('{!r} is a tar archive.'.format(src))
2965 else:
2966 parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
2967
2968 elif args.list is not None:
2969 src = args.list
2970 if is_tarfile(src):
2971 with TarFile.open(src, 'r:*') as tf:
2972 tf.list(verbose=args.verbose)
2973 else:
2974 parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
2975
2976 elif args.extract is not None:
2977 if len(args.extract) == 1:
2978 src = args.extract[0]
2979 curdir = os.curdir
2980 elif len(args.extract) == 2:
2981 src, curdir = args.extract
2982 else:
2983 parser.exit(1, parser.format_help())
2984
2985 if is_tarfile(src):
2986 with TarFile.open(src, 'r:*') as tf:
2987 tf.extractall(path=curdir, filter=args.filter)
2988 if args.verbose:
2989 if curdir == '.':
2990 msg = '{!r} file is extracted.'.format(src)
2991 else:
2992 msg = ('{!r} file is extracted '
2993 'into {!r} directory.').format(src, curdir)
2994 print(msg)
2995 else:
2996 parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
2997
2998 elif args.create is not None:
2999 tar_name = args.create.pop(0)
3000 _, ext = os.path.splitext(tar_name)
3001 compressions = {
3002 # gz
3003 '.gz': 'gz',
3004 '.tgz': 'gz',
3005 # xz
3006 '.xz': 'xz',
3007 '.txz': 'xz',
3008 # bz2
3009 '.bz2': 'bz2',
3010 '.tbz': 'bz2',
3011 '.tbz2': 'bz2',
3012 '.tb2': 'bz2',
3013 }
3014 tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w'
3015 tar_files = args.create
3016
3017 with TarFile.open(tar_name, tar_mode) as tf:
3018 for file_name in tar_files:
3019 tf.add(file_name)
3020
3021 if args.verbose:
3022 print('{!r} file created.'.format(tar_name))
3023
3024 if __name__ == '__main__':
3025 main()