Debian Codegraph @

src/python/backports/zstd/tarfile.py

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