tarfile.py 88 KB

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