tarfile.py 104 KB

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