Debian Codegraph @

src/python/backports/zstd/tarfile.py

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