tarfile.py 92 KB

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