tarfile.py 103 KB

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