test_tarfile.py 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924
  1. import sys
  2. import os
  3. import io
  4. from hashlib import sha256
  5. from contextlib import contextmanager
  6. from random import Random
  7. import pathlib
  8. import unittest
  9. import unittest.mock
  10. import tarfile
  11. from test import support
  12. from test.support import os_helper
  13. from test.support import script_helper
  14. # Check for our compression modules.
  15. try:
  16. import gzip
  17. except ImportError:
  18. gzip = None
  19. try:
  20. import zlib
  21. except ImportError:
  22. zlib = None
  23. try:
  24. import bz2
  25. except ImportError:
  26. bz2 = None
  27. try:
  28. import lzma
  29. except ImportError:
  30. lzma = None
  31. def sha256sum(data):
  32. return sha256(data).hexdigest()
  33. TEMPDIR = os.path.abspath(os_helper.TESTFN) + "-tardir"
  34. tarextdir = TEMPDIR + '-extract-test'
  35. tarname = support.findfile("testtar.tar")
  36. gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
  37. bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
  38. xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
  39. tmpname = os.path.join(TEMPDIR, "tmp.tar")
  40. dotlessname = os.path.join(TEMPDIR, "testtar")
  41. sha256_regtype = (
  42. "e09e4bc8b3c9d9177e77256353b36c159f5f040531bbd4b024a8f9b9196c71ce"
  43. )
  44. sha256_sparse = (
  45. "4f05a776071146756345ceee937b33fc5644f5a96b9780d1c7d6a32cdf164d7b"
  46. )
  47. class TarTest:
  48. tarname = tarname
  49. suffix = ''
  50. open = io.FileIO
  51. taropen = tarfile.TarFile.taropen
  52. @property
  53. def mode(self):
  54. return self.prefix + self.suffix
  55. @support.requires_gzip()
  56. class GzipTest:
  57. tarname = gzipname
  58. suffix = 'gz'
  59. open = gzip.GzipFile if gzip else None
  60. taropen = tarfile.TarFile.gzopen
  61. @support.requires_bz2()
  62. class Bz2Test:
  63. tarname = bz2name
  64. suffix = 'bz2'
  65. open = bz2.BZ2File if bz2 else None
  66. taropen = tarfile.TarFile.bz2open
  67. @support.requires_lzma()
  68. class LzmaTest:
  69. tarname = xzname
  70. suffix = 'xz'
  71. open = lzma.LZMAFile if lzma else None
  72. taropen = tarfile.TarFile.xzopen
  73. class ReadTest(TarTest):
  74. prefix = "r:"
  75. def setUp(self):
  76. self.tar = tarfile.open(self.tarname, mode=self.mode,
  77. encoding="iso8859-1")
  78. def tearDown(self):
  79. self.tar.close()
  80. class UstarReadTest(ReadTest, unittest.TestCase):
  81. def test_fileobj_regular_file(self):
  82. tarinfo = self.tar.getmember("ustar/regtype")
  83. with self.tar.extractfile(tarinfo) as fobj:
  84. data = fobj.read()
  85. self.assertEqual(len(data), tarinfo.size,
  86. "regular file extraction failed")
  87. self.assertEqual(sha256sum(data), sha256_regtype,
  88. "regular file extraction failed")
  89. def test_fileobj_readlines(self):
  90. self.tar.extract("ustar/regtype", TEMPDIR)
  91. tarinfo = self.tar.getmember("ustar/regtype")
  92. with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
  93. lines1 = fobj1.readlines()
  94. with self.tar.extractfile(tarinfo) as fobj:
  95. fobj2 = io.TextIOWrapper(fobj)
  96. lines2 = fobj2.readlines()
  97. self.assertEqual(lines1, lines2,
  98. "fileobj.readlines() failed")
  99. self.assertEqual(len(lines2), 114,
  100. "fileobj.readlines() failed")
  101. self.assertEqual(lines2[83],
  102. "I will gladly admit that Python is not the fastest "
  103. "running scripting language.\n",
  104. "fileobj.readlines() failed")
  105. def test_fileobj_iter(self):
  106. self.tar.extract("ustar/regtype", TEMPDIR)
  107. tarinfo = self.tar.getmember("ustar/regtype")
  108. with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
  109. lines1 = fobj1.readlines()
  110. with self.tar.extractfile(tarinfo) as fobj2:
  111. lines2 = list(io.TextIOWrapper(fobj2))
  112. self.assertEqual(lines1, lines2,
  113. "fileobj.__iter__() failed")
  114. def test_fileobj_seek(self):
  115. self.tar.extract("ustar/regtype", TEMPDIR)
  116. with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
  117. data = fobj.read()
  118. tarinfo = self.tar.getmember("ustar/regtype")
  119. with self.tar.extractfile(tarinfo) as fobj:
  120. text = fobj.read()
  121. fobj.seek(0)
  122. self.assertEqual(0, fobj.tell(),
  123. "seek() to file's start failed")
  124. fobj.seek(2048, 0)
  125. self.assertEqual(2048, fobj.tell(),
  126. "seek() to absolute position failed")
  127. fobj.seek(-1024, 1)
  128. self.assertEqual(1024, fobj.tell(),
  129. "seek() to negative relative position failed")
  130. fobj.seek(1024, 1)
  131. self.assertEqual(2048, fobj.tell(),
  132. "seek() to positive relative position failed")
  133. s = fobj.read(10)
  134. self.assertEqual(s, data[2048:2058],
  135. "read() after seek failed")
  136. fobj.seek(0, 2)
  137. self.assertEqual(tarinfo.size, fobj.tell(),
  138. "seek() to file's end failed")
  139. self.assertEqual(fobj.read(), b"",
  140. "read() at file's end did not return empty string")
  141. fobj.seek(-tarinfo.size, 2)
  142. self.assertEqual(0, fobj.tell(),
  143. "relative seek() to file's end failed")
  144. fobj.seek(512)
  145. s1 = fobj.readlines()
  146. fobj.seek(512)
  147. s2 = fobj.readlines()
  148. self.assertEqual(s1, s2,
  149. "readlines() after seek failed")
  150. fobj.seek(0)
  151. self.assertEqual(len(fobj.readline()), fobj.tell(),
  152. "tell() after readline() failed")
  153. fobj.seek(512)
  154. self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
  155. "tell() after seek() and readline() failed")
  156. fobj.seek(0)
  157. line = fobj.readline()
  158. self.assertEqual(fobj.read(), data[len(line):],
  159. "read() after readline() failed")
  160. def test_fileobj_text(self):
  161. with self.tar.extractfile("ustar/regtype") as fobj:
  162. fobj = io.TextIOWrapper(fobj)
  163. data = fobj.read().encode("iso8859-1")
  164. self.assertEqual(sha256sum(data), sha256_regtype)
  165. try:
  166. fobj.seek(100)
  167. except AttributeError:
  168. # Issue #13815: seek() complained about a missing
  169. # flush() method.
  170. self.fail("seeking failed in text mode")
  171. # Test if symbolic and hard links are resolved by extractfile(). The
  172. # test link members each point to a regular member whose data is
  173. # supposed to be exported.
  174. def _test_fileobj_link(self, lnktype, regtype):
  175. with self.tar.extractfile(lnktype) as a, \
  176. self.tar.extractfile(regtype) as b:
  177. self.assertEqual(a.name, b.name)
  178. def test_fileobj_link1(self):
  179. self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
  180. def test_fileobj_link2(self):
  181. self._test_fileobj_link("./ustar/linktest2/lnktype",
  182. "ustar/linktest1/regtype")
  183. def test_fileobj_symlink1(self):
  184. self._test_fileobj_link("ustar/symtype", "ustar/regtype")
  185. def test_fileobj_symlink2(self):
  186. self._test_fileobj_link("./ustar/linktest2/symtype",
  187. "ustar/linktest1/regtype")
  188. def test_issue14160(self):
  189. self._test_fileobj_link("symtype2", "ustar/regtype")
  190. def test_add_dir_getmember(self):
  191. # bpo-21987
  192. self.add_dir_and_getmember('bar')
  193. self.add_dir_and_getmember('a'*101)
  194. @unittest.skipIf(
  195. (hasattr(os, 'getuid') and os.getuid() > 0o777_7777) or
  196. (hasattr(os, 'getgid') and os.getgid() > 0o777_7777),
  197. "uid or gid too high for USTAR format."
  198. )
  199. def add_dir_and_getmember(self, name):
  200. with os_helper.temp_cwd():
  201. with tarfile.open(tmpname, 'w') as tar:
  202. tar.format = tarfile.USTAR_FORMAT
  203. try:
  204. os.mkdir(name)
  205. tar.add(name)
  206. finally:
  207. os.rmdir(name)
  208. with tarfile.open(tmpname) as tar:
  209. self.assertEqual(
  210. tar.getmember(name),
  211. tar.getmember(name + '/')
  212. )
  213. class GzipUstarReadTest(GzipTest, UstarReadTest):
  214. pass
  215. class Bz2UstarReadTest(Bz2Test, UstarReadTest):
  216. pass
  217. class LzmaUstarReadTest(LzmaTest, UstarReadTest):
  218. pass
  219. class ListTest(ReadTest, unittest.TestCase):
  220. # Override setUp to use default encoding (UTF-8)
  221. def setUp(self):
  222. self.tar = tarfile.open(self.tarname, mode=self.mode)
  223. def test_list(self):
  224. tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
  225. with support.swap_attr(sys, 'stdout', tio):
  226. self.tar.list(verbose=False)
  227. out = tio.detach().getvalue()
  228. self.assertIn(b'ustar/conttype', out)
  229. self.assertIn(b'ustar/regtype', out)
  230. self.assertIn(b'ustar/lnktype', out)
  231. self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
  232. self.assertIn(b'./ustar/linktest2/symtype', out)
  233. self.assertIn(b'./ustar/linktest2/lnktype', out)
  234. # Make sure it puts trailing slash for directory
  235. self.assertIn(b'ustar/dirtype/', out)
  236. self.assertIn(b'ustar/dirtype-with-size/', out)
  237. # Make sure it is able to print unencodable characters
  238. def conv(b):
  239. s = b.decode(self.tar.encoding, 'surrogateescape')
  240. return s.encode('ascii', 'backslashreplace')
  241. self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
  242. self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
  243. b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
  244. self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
  245. b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
  246. self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
  247. self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
  248. # Make sure it prints files separated by one newline without any
  249. # 'ls -l'-like accessories if verbose flag is not being used
  250. # ...
  251. # ustar/conttype
  252. # ustar/regtype
  253. # ...
  254. self.assertRegex(out, br'ustar/conttype ?\r?\n'
  255. br'ustar/regtype ?\r?\n')
  256. # Make sure it does not print the source of link without verbose flag
  257. self.assertNotIn(b'link to', out)
  258. self.assertNotIn(b'->', out)
  259. def test_list_verbose(self):
  260. tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
  261. with support.swap_attr(sys, 'stdout', tio):
  262. self.tar.list(verbose=True)
  263. out = tio.detach().getvalue()
  264. # Make sure it prints files separated by one newline with 'ls -l'-like
  265. # accessories if verbose flag is being used
  266. # ...
  267. # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
  268. # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
  269. # ...
  270. self.assertRegex(out, (br'\?rw-r--r-- tarfile/tarfile\s+7011 '
  271. br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
  272. br'ustar/\w+type ?\r?\n') * 2)
  273. # Make sure it prints the source of link with verbose flag
  274. self.assertIn(b'ustar/symtype -> regtype', out)
  275. self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
  276. self.assertIn(b'./ustar/linktest2/lnktype link to '
  277. b'./ustar/linktest1/regtype', out)
  278. self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
  279. (b'/123' * 125) + b'/longname', out)
  280. self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
  281. (b'/123' * 125) + b'/longname', out)
  282. def test_list_members(self):
  283. tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
  284. def members(tar):
  285. for tarinfo in tar.getmembers():
  286. if 'reg' in tarinfo.name:
  287. yield tarinfo
  288. with support.swap_attr(sys, 'stdout', tio):
  289. self.tar.list(verbose=False, members=members(self.tar))
  290. out = tio.detach().getvalue()
  291. self.assertIn(b'ustar/regtype', out)
  292. self.assertNotIn(b'ustar/conttype', out)
  293. class GzipListTest(GzipTest, ListTest):
  294. pass
  295. class Bz2ListTest(Bz2Test, ListTest):
  296. pass
  297. class LzmaListTest(LzmaTest, ListTest):
  298. pass
  299. class CommonReadTest(ReadTest):
  300. def test_is_tarfile_erroneous(self):
  301. with open(tmpname, "wb"):
  302. pass
  303. # is_tarfile works on filenames
  304. self.assertFalse(tarfile.is_tarfile(tmpname))
  305. # is_tarfile works on path-like objects
  306. self.assertFalse(tarfile.is_tarfile(pathlib.Path(tmpname)))
  307. # is_tarfile works on file objects
  308. with open(tmpname, "rb") as fobj:
  309. self.assertFalse(tarfile.is_tarfile(fobj))
  310. # is_tarfile works on file-like objects
  311. self.assertFalse(tarfile.is_tarfile(io.BytesIO(b"invalid")))
  312. def test_is_tarfile_valid(self):
  313. # is_tarfile works on filenames
  314. self.assertTrue(tarfile.is_tarfile(self.tarname))
  315. # is_tarfile works on path-like objects
  316. self.assertTrue(tarfile.is_tarfile(pathlib.Path(self.tarname)))
  317. # is_tarfile works on file objects
  318. with open(self.tarname, "rb") as fobj:
  319. self.assertTrue(tarfile.is_tarfile(fobj))
  320. # is_tarfile works on file-like objects
  321. with open(self.tarname, "rb") as fobj:
  322. self.assertTrue(tarfile.is_tarfile(io.BytesIO(fobj.read())))
  323. def test_is_tarfile_keeps_position(self):
  324. # Test for issue44289: tarfile.is_tarfile() modifies
  325. # file object's current position
  326. with open(self.tarname, "rb") as fobj:
  327. tarfile.is_tarfile(fobj)
  328. self.assertEqual(fobj.tell(), 0)
  329. with open(self.tarname, "rb") as fobj:
  330. file_like = io.BytesIO(fobj.read())
  331. tarfile.is_tarfile(file_like)
  332. self.assertEqual(file_like.tell(), 0)
  333. def test_empty_tarfile(self):
  334. # Test for issue6123: Allow opening empty archives.
  335. # This test checks if tarfile.open() is able to open an empty tar
  336. # archive successfully. Note that an empty tar archive is not the
  337. # same as an empty file!
  338. with tarfile.open(tmpname, self.mode.replace("r", "w")):
  339. pass
  340. try:
  341. tar = tarfile.open(tmpname, self.mode)
  342. tar.getnames()
  343. except tarfile.ReadError:
  344. self.fail("tarfile.open() failed on empty archive")
  345. else:
  346. self.assertListEqual(tar.getmembers(), [])
  347. finally:
  348. tar.close()
  349. def test_non_existent_tarfile(self):
  350. # Test for issue11513: prevent non-existent gzipped tarfiles raising
  351. # multiple exceptions.
  352. with self.assertRaisesRegex(FileNotFoundError, "xxx"):
  353. tarfile.open("xxx", self.mode)
  354. def test_null_tarfile(self):
  355. # Test for issue6123: Allow opening empty archives.
  356. # This test guarantees that tarfile.open() does not treat an empty
  357. # file as an empty tar archive.
  358. with open(tmpname, "wb"):
  359. pass
  360. self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
  361. self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
  362. def test_ignore_zeros(self):
  363. # Test TarFile's ignore_zeros option.
  364. # generate 512 pseudorandom bytes
  365. data = Random(0).randbytes(512)
  366. for char in (b'\0', b'a'):
  367. # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
  368. # are ignored correctly.
  369. with self.open(tmpname, "w") as fobj:
  370. fobj.write(char * 1024)
  371. tarinfo = tarfile.TarInfo("foo")
  372. tarinfo.size = len(data)
  373. fobj.write(tarinfo.tobuf())
  374. fobj.write(data)
  375. tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
  376. try:
  377. self.assertListEqual(tar.getnames(), ["foo"],
  378. "ignore_zeros=True should have skipped the %r-blocks" %
  379. char)
  380. finally:
  381. tar.close()
  382. def test_premature_end_of_archive(self):
  383. for size in (512, 600, 1024, 1200):
  384. with tarfile.open(tmpname, "w:") as tar:
  385. t = tarfile.TarInfo("foo")
  386. t.size = 1024
  387. tar.addfile(t, io.BytesIO(b"a" * 1024))
  388. with open(tmpname, "r+b") as fobj:
  389. fobj.truncate(size)
  390. with tarfile.open(tmpname) as tar:
  391. with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
  392. for t in tar:
  393. pass
  394. with tarfile.open(tmpname) as tar:
  395. t = tar.next()
  396. with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
  397. tar.extract(t, TEMPDIR)
  398. with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
  399. tar.extractfile(t).read()
  400. def test_length_zero_header(self):
  401. # bpo-39017 (CVE-2019-20907): reading a zero-length header should fail
  402. # with an exception
  403. with self.assertRaisesRegex(tarfile.ReadError, "file could not be opened successfully"):
  404. with tarfile.open(support.findfile('recursion.tar')) as tar:
  405. pass
  406. class MiscReadTestBase(CommonReadTest):
  407. def requires_name_attribute(self):
  408. pass
  409. def test_no_name_argument(self):
  410. self.requires_name_attribute()
  411. with open(self.tarname, "rb") as fobj:
  412. self.assertIsInstance(fobj.name, str)
  413. with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
  414. self.assertIsInstance(tar.name, str)
  415. self.assertEqual(tar.name, os.path.abspath(fobj.name))
  416. def test_no_name_attribute(self):
  417. with open(self.tarname, "rb") as fobj:
  418. data = fobj.read()
  419. fobj = io.BytesIO(data)
  420. self.assertRaises(AttributeError, getattr, fobj, "name")
  421. tar = tarfile.open(fileobj=fobj, mode=self.mode)
  422. self.assertIsNone(tar.name)
  423. def test_empty_name_attribute(self):
  424. with open(self.tarname, "rb") as fobj:
  425. data = fobj.read()
  426. fobj = io.BytesIO(data)
  427. fobj.name = ""
  428. with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
  429. self.assertIsNone(tar.name)
  430. def test_int_name_attribute(self):
  431. # Issue 21044: tarfile.open() should handle fileobj with an integer
  432. # 'name' attribute.
  433. fd = os.open(self.tarname, os.O_RDONLY)
  434. with open(fd, 'rb') as fobj:
  435. self.assertIsInstance(fobj.name, int)
  436. with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
  437. self.assertIsNone(tar.name)
  438. def test_bytes_name_attribute(self):
  439. self.requires_name_attribute()
  440. tarname = os.fsencode(self.tarname)
  441. with open(tarname, 'rb') as fobj:
  442. self.assertIsInstance(fobj.name, bytes)
  443. with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
  444. self.assertIsInstance(tar.name, bytes)
  445. self.assertEqual(tar.name, os.path.abspath(fobj.name))
  446. def test_pathlike_name(self):
  447. tarname = pathlib.Path(self.tarname)
  448. with tarfile.open(tarname, mode=self.mode) as tar:
  449. self.assertIsInstance(tar.name, str)
  450. self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
  451. with self.taropen(tarname) as tar:
  452. self.assertIsInstance(tar.name, str)
  453. self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
  454. with tarfile.TarFile.open(tarname, mode=self.mode) as tar:
  455. self.assertIsInstance(tar.name, str)
  456. self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
  457. if self.suffix == '':
  458. with tarfile.TarFile(tarname, mode='r') as tar:
  459. self.assertIsInstance(tar.name, str)
  460. self.assertEqual(tar.name, os.path.abspath(os.fspath(tarname)))
  461. def test_illegal_mode_arg(self):
  462. with open(tmpname, 'wb'):
  463. pass
  464. with self.assertRaisesRegex(ValueError, 'mode must be '):
  465. tar = self.taropen(tmpname, 'q')
  466. with self.assertRaisesRegex(ValueError, 'mode must be '):
  467. tar = self.taropen(tmpname, 'rw')
  468. with self.assertRaisesRegex(ValueError, 'mode must be '):
  469. tar = self.taropen(tmpname, '')
  470. def test_fileobj_with_offset(self):
  471. # Skip the first member and store values from the second member
  472. # of the testtar.
  473. tar = tarfile.open(self.tarname, mode=self.mode)
  474. try:
  475. tar.next()
  476. t = tar.next()
  477. name = t.name
  478. offset = t.offset
  479. with tar.extractfile(t) as f:
  480. data = f.read()
  481. finally:
  482. tar.close()
  483. # Open the testtar and seek to the offset of the second member.
  484. with self.open(self.tarname) as fobj:
  485. fobj.seek(offset)
  486. # Test if the tarfile starts with the second member.
  487. with tar.open(self.tarname, mode="r:", fileobj=fobj) as tar:
  488. t = tar.next()
  489. self.assertEqual(t.name, name)
  490. # Read to the end of fileobj and test if seeking back to the
  491. # beginning works.
  492. tar.getmembers()
  493. self.assertEqual(tar.extractfile(t).read(), data,
  494. "seek back did not work")
  495. def test_fail_comp(self):
  496. # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
  497. self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
  498. with open(tarname, "rb") as fobj:
  499. self.assertRaises(tarfile.ReadError, tarfile.open,
  500. fileobj=fobj, mode=self.mode)
  501. def test_v7_dirtype(self):
  502. # Test old style dirtype member (bug #1336623):
  503. # Old V7 tars create directory members using an AREGTYPE
  504. # header with a "/" appended to the filename field.
  505. tarinfo = self.tar.getmember("misc/dirtype-old-v7")
  506. self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
  507. "v7 dirtype failed")
  508. def test_xstar_type(self):
  509. # The xstar format stores extra atime and ctime fields inside the
  510. # space reserved for the prefix field. The prefix field must be
  511. # ignored in this case, otherwise it will mess up the name.
  512. try:
  513. self.tar.getmember("misc/regtype-xstar")
  514. except KeyError:
  515. self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
  516. def test_check_members(self):
  517. for tarinfo in self.tar:
  518. self.assertEqual(int(tarinfo.mtime), 0o7606136617,
  519. "wrong mtime for %s" % tarinfo.name)
  520. if not tarinfo.name.startswith("ustar/"):
  521. continue
  522. self.assertEqual(tarinfo.uname, "tarfile",
  523. "wrong uname for %s" % tarinfo.name)
  524. def test_find_members(self):
  525. self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
  526. "could not find all members")
  527. @unittest.skipUnless(hasattr(os, "link"),
  528. "Missing hardlink implementation")
  529. @os_helper.skip_unless_symlink
  530. def test_extract_hardlink(self):
  531. # Test hardlink extraction (e.g. bug #857297).
  532. with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
  533. tar.extract("ustar/regtype", TEMPDIR)
  534. self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
  535. tar.extract("ustar/lnktype", TEMPDIR)
  536. self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
  537. with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
  538. data = f.read()
  539. self.assertEqual(sha256sum(data), sha256_regtype)
  540. tar.extract("ustar/symtype", TEMPDIR)
  541. self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
  542. with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
  543. data = f.read()
  544. self.assertEqual(sha256sum(data), sha256_regtype)
  545. @os_helper.skip_unless_working_chmod
  546. def test_extractall(self):
  547. # Test if extractall() correctly restores directory permissions
  548. # and times (see issue1735).
  549. tar = tarfile.open(tarname, encoding="iso8859-1")
  550. DIR = os.path.join(TEMPDIR, "extractall")
  551. os.mkdir(DIR)
  552. try:
  553. directories = [t for t in tar if t.isdir()]
  554. tar.extractall(DIR, directories)
  555. for tarinfo in directories:
  556. path = os.path.join(DIR, tarinfo.name)
  557. if sys.platform != "win32":
  558. # Win32 has no support for fine grained permissions.
  559. self.assertEqual(tarinfo.mode & 0o777,
  560. os.stat(path).st_mode & 0o777)
  561. def format_mtime(mtime):
  562. if isinstance(mtime, float):
  563. return "{} ({})".format(mtime, mtime.hex())
  564. else:
  565. return "{!r} (int)".format(mtime)
  566. file_mtime = os.path.getmtime(path)
  567. errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
  568. format_mtime(tarinfo.mtime),
  569. format_mtime(file_mtime),
  570. path)
  571. self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
  572. finally:
  573. tar.close()
  574. os_helper.rmtree(DIR)
  575. @os_helper.skip_unless_working_chmod
  576. def test_extract_directory(self):
  577. dirtype = "ustar/dirtype"
  578. DIR = os.path.join(TEMPDIR, "extractdir")
  579. os.mkdir(DIR)
  580. try:
  581. with tarfile.open(tarname, encoding="iso8859-1") as tar:
  582. tarinfo = tar.getmember(dirtype)
  583. tar.extract(tarinfo, path=DIR)
  584. extracted = os.path.join(DIR, dirtype)
  585. self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
  586. if sys.platform != "win32":
  587. self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
  588. finally:
  589. os_helper.rmtree(DIR)
  590. def test_extractall_pathlike_name(self):
  591. DIR = pathlib.Path(TEMPDIR) / "extractall"
  592. with os_helper.temp_dir(DIR), \
  593. tarfile.open(tarname, encoding="iso8859-1") as tar:
  594. directories = [t for t in tar if t.isdir()]
  595. tar.extractall(DIR, directories)
  596. for tarinfo in directories:
  597. path = DIR / tarinfo.name
  598. self.assertEqual(os.path.getmtime(path), tarinfo.mtime)
  599. def test_extract_pathlike_name(self):
  600. dirtype = "ustar/dirtype"
  601. DIR = pathlib.Path(TEMPDIR) / "extractall"
  602. with os_helper.temp_dir(DIR), \
  603. tarfile.open(tarname, encoding="iso8859-1") as tar:
  604. tarinfo = tar.getmember(dirtype)
  605. tar.extract(tarinfo, path=DIR)
  606. extracted = DIR / dirtype
  607. self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
  608. def test_init_close_fobj(self):
  609. # Issue #7341: Close the internal file object in the TarFile
  610. # constructor in case of an error. For the test we rely on
  611. # the fact that opening an empty file raises a ReadError.
  612. empty = os.path.join(TEMPDIR, "empty")
  613. with open(empty, "wb") as fobj:
  614. fobj.write(b"")
  615. try:
  616. tar = object.__new__(tarfile.TarFile)
  617. try:
  618. tar.__init__(empty)
  619. except tarfile.ReadError:
  620. self.assertTrue(tar.fileobj.closed)
  621. else:
  622. self.fail("ReadError not raised")
  623. finally:
  624. os_helper.unlink(empty)
  625. def test_parallel_iteration(self):
  626. # Issue #16601: Restarting iteration over tarfile continued
  627. # from where it left off.
  628. with tarfile.open(self.tarname) as tar:
  629. for m1, m2 in zip(tar, tar):
  630. self.assertEqual(m1.offset, m2.offset)
  631. self.assertEqual(m1.get_info(), m2.get_info())
  632. @unittest.skipIf(zlib is None, "requires zlib")
  633. def test_zlib_error_does_not_leak(self):
  634. # bpo-39039: tarfile.open allowed zlib exceptions to bubble up when
  635. # parsing certain types of invalid data
  636. with unittest.mock.patch("tarfile.TarInfo.fromtarfile") as mock:
  637. mock.side_effect = zlib.error
  638. with self.assertRaises(tarfile.ReadError):
  639. tarfile.open(self.tarname)
  640. def test_next_on_empty_tarfile(self):
  641. fd = io.BytesIO()
  642. tf = tarfile.open(fileobj=fd, mode="w")
  643. tf.close()
  644. fd.seek(0)
  645. with tarfile.open(fileobj=fd, mode="r|") as tf:
  646. self.assertEqual(tf.next(), None)
  647. fd.seek(0)
  648. with tarfile.open(fileobj=fd, mode="r") as tf:
  649. self.assertEqual(tf.next(), None)
  650. class MiscReadTest(MiscReadTestBase, unittest.TestCase):
  651. test_fail_comp = None
  652. class GzipMiscReadTest(GzipTest, MiscReadTestBase, unittest.TestCase):
  653. pass
  654. class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
  655. def requires_name_attribute(self):
  656. self.skipTest("BZ2File have no name attribute")
  657. class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
  658. def requires_name_attribute(self):
  659. self.skipTest("LZMAFile have no name attribute")
  660. class StreamReadTest(CommonReadTest, unittest.TestCase):
  661. prefix="r|"
  662. def test_read_through(self):
  663. # Issue #11224: A poorly designed _FileInFile.read() method
  664. # caused seeking errors with stream tar files.
  665. for tarinfo in self.tar:
  666. if not tarinfo.isreg():
  667. continue
  668. with self.tar.extractfile(tarinfo) as fobj:
  669. while True:
  670. try:
  671. buf = fobj.read(512)
  672. except tarfile.StreamError:
  673. self.fail("simple read-through using "
  674. "TarFile.extractfile() failed")
  675. if not buf:
  676. break
  677. def test_fileobj_regular_file(self):
  678. tarinfo = self.tar.next() # get "regtype" (can't use getmember)
  679. with self.tar.extractfile(tarinfo) as fobj:
  680. data = fobj.read()
  681. self.assertEqual(len(data), tarinfo.size,
  682. "regular file extraction failed")
  683. self.assertEqual(sha256sum(data), sha256_regtype,
  684. "regular file extraction failed")
  685. def test_provoke_stream_error(self):
  686. tarinfos = self.tar.getmembers()
  687. with self.tar.extractfile(tarinfos[0]) as f: # read the first member
  688. self.assertRaises(tarfile.StreamError, f.read)
  689. def test_compare_members(self):
  690. tar1 = tarfile.open(tarname, encoding="iso8859-1")
  691. try:
  692. tar2 = self.tar
  693. while True:
  694. t1 = tar1.next()
  695. t2 = tar2.next()
  696. if t1 is None:
  697. break
  698. self.assertIsNotNone(t2, "stream.next() failed.")
  699. if t2.islnk() or t2.issym():
  700. with self.assertRaises(tarfile.StreamError):
  701. tar2.extractfile(t2)
  702. continue
  703. v1 = tar1.extractfile(t1)
  704. v2 = tar2.extractfile(t2)
  705. if v1 is None:
  706. continue
  707. self.assertIsNotNone(v2, "stream.extractfile() failed")
  708. self.assertEqual(v1.read(), v2.read(),
  709. "stream extraction failed")
  710. finally:
  711. tar1.close()
  712. class GzipStreamReadTest(GzipTest, StreamReadTest):
  713. pass
  714. class Bz2StreamReadTest(Bz2Test, StreamReadTest):
  715. pass
  716. class LzmaStreamReadTest(LzmaTest, StreamReadTest):
  717. pass
  718. class DetectReadTest(TarTest, unittest.TestCase):
  719. def _testfunc_file(self, name, mode):
  720. try:
  721. tar = tarfile.open(name, mode)
  722. except tarfile.ReadError as e:
  723. self.fail()
  724. else:
  725. tar.close()
  726. def _testfunc_fileobj(self, name, mode):
  727. try:
  728. with open(name, "rb") as f:
  729. tar = tarfile.open(name, mode, fileobj=f)
  730. except tarfile.ReadError as e:
  731. self.fail()
  732. else:
  733. tar.close()
  734. def _test_modes(self, testfunc):
  735. if self.suffix:
  736. with self.assertRaises(tarfile.ReadError):
  737. tarfile.open(tarname, mode="r:" + self.suffix)
  738. with self.assertRaises(tarfile.ReadError):
  739. tarfile.open(tarname, mode="r|" + self.suffix)
  740. with self.assertRaises(tarfile.ReadError):
  741. tarfile.open(self.tarname, mode="r:")
  742. with self.assertRaises(tarfile.ReadError):
  743. tarfile.open(self.tarname, mode="r|")
  744. testfunc(self.tarname, "r")
  745. testfunc(self.tarname, "r:" + self.suffix)
  746. testfunc(self.tarname, "r:*")
  747. testfunc(self.tarname, "r|" + self.suffix)
  748. testfunc(self.tarname, "r|*")
  749. def test_detect_file(self):
  750. self._test_modes(self._testfunc_file)
  751. def test_detect_fileobj(self):
  752. self._test_modes(self._testfunc_fileobj)
  753. class GzipDetectReadTest(GzipTest, DetectReadTest):
  754. pass
  755. class Bz2DetectReadTest(Bz2Test, DetectReadTest):
  756. def test_detect_stream_bz2(self):
  757. # Originally, tarfile's stream detection looked for the string
  758. # "BZh91" at the start of the file. This is incorrect because
  759. # the '9' represents the blocksize (900,000 bytes). If the file was
  760. # compressed using another blocksize autodetection fails.
  761. with open(tarname, "rb") as fobj:
  762. data = fobj.read()
  763. # Compress with blocksize 100,000 bytes, the file starts with "BZh11".
  764. with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
  765. fobj.write(data)
  766. self._testfunc_file(tmpname, "r|*")
  767. class LzmaDetectReadTest(LzmaTest, DetectReadTest):
  768. pass
  769. class MemberReadTest(ReadTest, unittest.TestCase):
  770. def _test_member(self, tarinfo, chksum=None, **kwargs):
  771. if chksum is not None:
  772. with self.tar.extractfile(tarinfo) as f:
  773. self.assertEqual(sha256sum(f.read()), chksum,
  774. "wrong sha256sum for %s" % tarinfo.name)
  775. kwargs["mtime"] = 0o7606136617
  776. kwargs["uid"] = 1000
  777. kwargs["gid"] = 100
  778. if "old-v7" not in tarinfo.name:
  779. # V7 tar can't handle alphabetic owners.
  780. kwargs["uname"] = "tarfile"
  781. kwargs["gname"] = "tarfile"
  782. for k, v in kwargs.items():
  783. self.assertEqual(getattr(tarinfo, k), v,
  784. "wrong value in %s field of %s" % (k, tarinfo.name))
  785. def test_find_regtype(self):
  786. tarinfo = self.tar.getmember("ustar/regtype")
  787. self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
  788. def test_find_conttype(self):
  789. tarinfo = self.tar.getmember("ustar/conttype")
  790. self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
  791. def test_find_dirtype(self):
  792. tarinfo = self.tar.getmember("ustar/dirtype")
  793. self._test_member(tarinfo, size=0)
  794. def test_find_dirtype_with_size(self):
  795. tarinfo = self.tar.getmember("ustar/dirtype-with-size")
  796. self._test_member(tarinfo, size=255)
  797. def test_find_lnktype(self):
  798. tarinfo = self.tar.getmember("ustar/lnktype")
  799. self._test_member(tarinfo, size=0, linkname="ustar/regtype")
  800. def test_find_symtype(self):
  801. tarinfo = self.tar.getmember("ustar/symtype")
  802. self._test_member(tarinfo, size=0, linkname="regtype")
  803. def test_find_blktype(self):
  804. tarinfo = self.tar.getmember("ustar/blktype")
  805. self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
  806. def test_find_chrtype(self):
  807. tarinfo = self.tar.getmember("ustar/chrtype")
  808. self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
  809. def test_find_fifotype(self):
  810. tarinfo = self.tar.getmember("ustar/fifotype")
  811. self._test_member(tarinfo, size=0)
  812. def test_find_sparse(self):
  813. tarinfo = self.tar.getmember("ustar/sparse")
  814. self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
  815. def test_find_gnusparse(self):
  816. tarinfo = self.tar.getmember("gnu/sparse")
  817. self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
  818. def test_find_gnusparse_00(self):
  819. tarinfo = self.tar.getmember("gnu/sparse-0.0")
  820. self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
  821. def test_find_gnusparse_01(self):
  822. tarinfo = self.tar.getmember("gnu/sparse-0.1")
  823. self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
  824. def test_find_gnusparse_10(self):
  825. tarinfo = self.tar.getmember("gnu/sparse-1.0")
  826. self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
  827. def test_find_umlauts(self):
  828. tarinfo = self.tar.getmember("ustar/umlauts-"
  829. "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
  830. self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
  831. def test_find_ustar_longname(self):
  832. name = "ustar/" + "12345/" * 39 + "1234567/longname"
  833. self.assertIn(name, self.tar.getnames())
  834. def test_find_regtype_oldv7(self):
  835. tarinfo = self.tar.getmember("misc/regtype-old-v7")
  836. self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
  837. def test_find_pax_umlauts(self):
  838. self.tar.close()
  839. self.tar = tarfile.open(self.tarname, mode=self.mode,
  840. encoding="iso8859-1")
  841. tarinfo = self.tar.getmember("pax/umlauts-"
  842. "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
  843. self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
  844. class LongnameTest:
  845. def test_read_longname(self):
  846. # Test reading of longname (bug #1471427).
  847. longname = self.subdir + "/" + "123/" * 125 + "longname"
  848. try:
  849. tarinfo = self.tar.getmember(longname)
  850. except KeyError:
  851. self.fail("longname not found")
  852. self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
  853. "read longname as dirtype")
  854. def test_read_longlink(self):
  855. longname = self.subdir + "/" + "123/" * 125 + "longname"
  856. longlink = self.subdir + "/" + "123/" * 125 + "longlink"
  857. try:
  858. tarinfo = self.tar.getmember(longlink)
  859. except KeyError:
  860. self.fail("longlink not found")
  861. self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
  862. def test_truncated_longname(self):
  863. longname = self.subdir + "/" + "123/" * 125 + "longname"
  864. tarinfo = self.tar.getmember(longname)
  865. offset = tarinfo.offset
  866. self.tar.fileobj.seek(offset)
  867. fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
  868. with self.assertRaises(tarfile.ReadError):
  869. tarfile.open(name="foo.tar", fileobj=fobj)
  870. def test_header_offset(self):
  871. # Test if the start offset of the TarInfo object includes
  872. # the preceding extended header.
  873. longname = self.subdir + "/" + "123/" * 125 + "longname"
  874. offset = self.tar.getmember(longname).offset
  875. with open(tarname, "rb") as fobj:
  876. fobj.seek(offset)
  877. tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
  878. "iso8859-1", "strict")
  879. self.assertEqual(tarinfo.type, self.longnametype)
  880. def test_longname_directory(self):
  881. # Test reading a longlink directory. Issue #47231.
  882. longdir = ('a' * 101) + '/'
  883. with os_helper.temp_cwd():
  884. with tarfile.open(tmpname, 'w') as tar:
  885. tar.format = self.format
  886. try:
  887. os.mkdir(longdir)
  888. tar.add(longdir)
  889. finally:
  890. os.rmdir(longdir.rstrip("/"))
  891. with tarfile.open(tmpname) as tar:
  892. self.assertIsNotNone(tar.getmember(longdir))
  893. self.assertIsNotNone(tar.getmember(longdir.removesuffix('/')))
  894. class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
  895. subdir = "gnu"
  896. longnametype = tarfile.GNUTYPE_LONGNAME
  897. format = tarfile.GNU_FORMAT
  898. # Since 3.2 tarfile is supposed to accurately restore sparse members and
  899. # produce files with holes. This is what we actually want to test here.
  900. # Unfortunately, not all platforms/filesystems support sparse files, and
  901. # even on platforms that do it is non-trivial to make reliable assertions
  902. # about holes in files. Therefore, we first do one basic test which works
  903. # an all platforms, and after that a test that will work only on
  904. # platforms/filesystems that prove to support sparse files.
  905. def _test_sparse_file(self, name):
  906. self.tar.extract(name, TEMPDIR)
  907. filename = os.path.join(TEMPDIR, name)
  908. with open(filename, "rb") as fobj:
  909. data = fobj.read()
  910. self.assertEqual(sha256sum(data), sha256_sparse,
  911. "wrong sha256sum for %s" % name)
  912. if self._fs_supports_holes():
  913. s = os.stat(filename)
  914. self.assertLess(s.st_blocks * 512, s.st_size)
  915. def test_sparse_file_old(self):
  916. self._test_sparse_file("gnu/sparse")
  917. def test_sparse_file_00(self):
  918. self._test_sparse_file("gnu/sparse-0.0")
  919. def test_sparse_file_01(self):
  920. self._test_sparse_file("gnu/sparse-0.1")
  921. def test_sparse_file_10(self):
  922. self._test_sparse_file("gnu/sparse-1.0")
  923. @staticmethod
  924. def _fs_supports_holes():
  925. # Return True if the platform knows the st_blocks stat attribute and
  926. # uses st_blocks units of 512 bytes, and if the filesystem is able to
  927. # store holes of 4 KiB in files.
  928. #
  929. # The function returns False if page size is larger than 4 KiB.
  930. # For example, ppc64 uses pages of 64 KiB.
  931. if sys.platform.startswith("linux"):
  932. # Linux evidentially has 512 byte st_blocks units.
  933. name = os.path.join(TEMPDIR, "sparse-test")
  934. with open(name, "wb") as fobj:
  935. # Seek to "punch a hole" of 4 KiB
  936. fobj.seek(4096)
  937. fobj.write(b'x' * 4096)
  938. fobj.truncate()
  939. s = os.stat(name)
  940. os_helper.unlink(name)
  941. return (s.st_blocks * 512 < s.st_size)
  942. else:
  943. return False
  944. class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
  945. subdir = "pax"
  946. longnametype = tarfile.XHDTYPE
  947. format = tarfile.PAX_FORMAT
  948. def test_pax_global_headers(self):
  949. tar = tarfile.open(tarname, encoding="iso8859-1")
  950. try:
  951. tarinfo = tar.getmember("pax/regtype1")
  952. self.assertEqual(tarinfo.uname, "foo")
  953. self.assertEqual(tarinfo.gname, "bar")
  954. self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
  955. "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
  956. tarinfo = tar.getmember("pax/regtype2")
  957. self.assertEqual(tarinfo.uname, "")
  958. self.assertEqual(tarinfo.gname, "bar")
  959. self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
  960. "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
  961. tarinfo = tar.getmember("pax/regtype3")
  962. self.assertEqual(tarinfo.uname, "tarfile")
  963. self.assertEqual(tarinfo.gname, "tarfile")
  964. self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
  965. "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
  966. finally:
  967. tar.close()
  968. def test_pax_number_fields(self):
  969. # All following number fields are read from the pax header.
  970. tar = tarfile.open(tarname, encoding="iso8859-1")
  971. try:
  972. tarinfo = tar.getmember("pax/regtype4")
  973. self.assertEqual(tarinfo.size, 7011)
  974. self.assertEqual(tarinfo.uid, 123)
  975. self.assertEqual(tarinfo.gid, 123)
  976. self.assertEqual(tarinfo.mtime, 1041808783.0)
  977. self.assertEqual(type(tarinfo.mtime), float)
  978. self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
  979. self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
  980. finally:
  981. tar.close()
  982. class WriteTestBase(TarTest):
  983. # Put all write tests in here that are supposed to be tested
  984. # in all possible mode combinations.
  985. def test_fileobj_no_close(self):
  986. fobj = io.BytesIO()
  987. with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
  988. tar.addfile(tarfile.TarInfo("foo"))
  989. self.assertFalse(fobj.closed, "external fileobjs must never closed")
  990. # Issue #20238: Incomplete gzip output with mode="w:gz"
  991. data = fobj.getvalue()
  992. del tar
  993. support.gc_collect()
  994. self.assertFalse(fobj.closed)
  995. self.assertEqual(data, fobj.getvalue())
  996. def test_eof_marker(self):
  997. # Make sure an end of archive marker is written (two zero blocks).
  998. # tarfile insists on aligning archives to a 20 * 512 byte recordsize.
  999. # So, we create an archive that has exactly 10240 bytes without the
  1000. # marker, and has 20480 bytes once the marker is written.
  1001. with tarfile.open(tmpname, self.mode) as tar:
  1002. t = tarfile.TarInfo("foo")
  1003. t.size = tarfile.RECORDSIZE - tarfile.BLOCKSIZE
  1004. tar.addfile(t, io.BytesIO(b"a" * t.size))
  1005. with self.open(tmpname, "rb") as fobj:
  1006. self.assertEqual(len(fobj.read()), tarfile.RECORDSIZE * 2)
  1007. class WriteTest(WriteTestBase, unittest.TestCase):
  1008. prefix = "w:"
  1009. def test_100_char_name(self):
  1010. # The name field in a tar header stores strings of at most 100 chars.
  1011. # If a string is shorter than 100 chars it has to be padded with '\0',
  1012. # which implies that a string of exactly 100 chars is stored without
  1013. # a trailing '\0'.
  1014. name = "0123456789" * 10
  1015. tar = tarfile.open(tmpname, self.mode)
  1016. try:
  1017. t = tarfile.TarInfo(name)
  1018. tar.addfile(t)
  1019. finally:
  1020. tar.close()
  1021. tar = tarfile.open(tmpname)
  1022. try:
  1023. self.assertEqual(tar.getnames()[0], name,
  1024. "failed to store 100 char filename")
  1025. finally:
  1026. tar.close()
  1027. def test_tar_size(self):
  1028. # Test for bug #1013882.
  1029. tar = tarfile.open(tmpname, self.mode)
  1030. try:
  1031. path = os.path.join(TEMPDIR, "file")
  1032. with open(path, "wb") as fobj:
  1033. fobj.write(b"aaa")
  1034. tar.add(path)
  1035. finally:
  1036. tar.close()
  1037. self.assertGreater(os.path.getsize(tmpname), 0,
  1038. "tarfile is empty")
  1039. # The test_*_size tests test for bug #1167128.
  1040. def test_file_size(self):
  1041. tar = tarfile.open(tmpname, self.mode)
  1042. try:
  1043. path = os.path.join(TEMPDIR, "file")
  1044. with open(path, "wb"):
  1045. pass
  1046. tarinfo = tar.gettarinfo(path)
  1047. self.assertEqual(tarinfo.size, 0)
  1048. with open(path, "wb") as fobj:
  1049. fobj.write(b"aaa")
  1050. tarinfo = tar.gettarinfo(path)
  1051. self.assertEqual(tarinfo.size, 3)
  1052. finally:
  1053. tar.close()
  1054. def test_directory_size(self):
  1055. path = os.path.join(TEMPDIR, "directory")
  1056. os.mkdir(path)
  1057. try:
  1058. tar = tarfile.open(tmpname, self.mode)
  1059. try:
  1060. tarinfo = tar.gettarinfo(path)
  1061. self.assertEqual(tarinfo.size, 0)
  1062. finally:
  1063. tar.close()
  1064. finally:
  1065. os_helper.rmdir(path)
  1066. # mock the following:
  1067. # os.listdir: so we know that files are in the wrong order
  1068. def test_ordered_recursion(self):
  1069. path = os.path.join(TEMPDIR, "directory")
  1070. os.mkdir(path)
  1071. open(os.path.join(path, "1"), "a").close()
  1072. open(os.path.join(path, "2"), "a").close()
  1073. try:
  1074. tar = tarfile.open(tmpname, self.mode)
  1075. try:
  1076. with unittest.mock.patch('os.listdir') as mock_listdir:
  1077. mock_listdir.return_value = ["2", "1"]
  1078. tar.add(path)
  1079. paths = []
  1080. for m in tar.getmembers():
  1081. paths.append(os.path.split(m.name)[-1])
  1082. self.assertEqual(paths, ["directory", "1", "2"]);
  1083. finally:
  1084. tar.close()
  1085. finally:
  1086. os_helper.unlink(os.path.join(path, "1"))
  1087. os_helper.unlink(os.path.join(path, "2"))
  1088. os_helper.rmdir(path)
  1089. def test_gettarinfo_pathlike_name(self):
  1090. with tarfile.open(tmpname, self.mode) as tar:
  1091. path = pathlib.Path(TEMPDIR) / "file"
  1092. with open(path, "wb") as fobj:
  1093. fobj.write(b"aaa")
  1094. tarinfo = tar.gettarinfo(path)
  1095. tarinfo2 = tar.gettarinfo(os.fspath(path))
  1096. self.assertIsInstance(tarinfo.name, str)
  1097. self.assertEqual(tarinfo.name, tarinfo2.name)
  1098. self.assertEqual(tarinfo.size, 3)
  1099. @unittest.skipUnless(hasattr(os, "link"),
  1100. "Missing hardlink implementation")
  1101. def test_link_size(self):
  1102. link = os.path.join(TEMPDIR, "link")
  1103. target = os.path.join(TEMPDIR, "link_target")
  1104. with open(target, "wb") as fobj:
  1105. fobj.write(b"aaa")
  1106. try:
  1107. os.link(target, link)
  1108. except PermissionError as e:
  1109. self.skipTest('os.link(): %s' % e)
  1110. try:
  1111. tar = tarfile.open(tmpname, self.mode)
  1112. try:
  1113. # Record the link target in the inodes list.
  1114. tar.gettarinfo(target)
  1115. tarinfo = tar.gettarinfo(link)
  1116. self.assertEqual(tarinfo.size, 0)
  1117. finally:
  1118. tar.close()
  1119. finally:
  1120. os_helper.unlink(target)
  1121. os_helper.unlink(link)
  1122. @os_helper.skip_unless_symlink
  1123. def test_symlink_size(self):
  1124. path = os.path.join(TEMPDIR, "symlink")
  1125. os.symlink("link_target", path)
  1126. try:
  1127. tar = tarfile.open(tmpname, self.mode)
  1128. try:
  1129. tarinfo = tar.gettarinfo(path)
  1130. self.assertEqual(tarinfo.size, 0)
  1131. finally:
  1132. tar.close()
  1133. finally:
  1134. os_helper.unlink(path)
  1135. def test_add_self(self):
  1136. # Test for #1257255.
  1137. dstname = os.path.abspath(tmpname)
  1138. tar = tarfile.open(tmpname, self.mode)
  1139. try:
  1140. self.assertEqual(tar.name, dstname,
  1141. "archive name must be absolute")
  1142. tar.add(dstname)
  1143. self.assertEqual(tar.getnames(), [],
  1144. "added the archive to itself")
  1145. with os_helper.change_cwd(TEMPDIR):
  1146. tar.add(dstname)
  1147. self.assertEqual(tar.getnames(), [],
  1148. "added the archive to itself")
  1149. finally:
  1150. tar.close()
  1151. def test_filter(self):
  1152. tempdir = os.path.join(TEMPDIR, "filter")
  1153. os.mkdir(tempdir)
  1154. try:
  1155. for name in ("foo", "bar", "baz"):
  1156. name = os.path.join(tempdir, name)
  1157. os_helper.create_empty_file(name)
  1158. def filter(tarinfo):
  1159. if os.path.basename(tarinfo.name) == "bar":
  1160. return
  1161. tarinfo.uid = 123
  1162. tarinfo.uname = "foo"
  1163. return tarinfo
  1164. tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
  1165. try:
  1166. tar.add(tempdir, arcname="empty_dir", filter=filter)
  1167. finally:
  1168. tar.close()
  1169. # Verify that filter is a keyword-only argument
  1170. with self.assertRaises(TypeError):
  1171. tar.add(tempdir, "empty_dir", True, None, filter)
  1172. tar = tarfile.open(tmpname, "r")
  1173. try:
  1174. for tarinfo in tar:
  1175. self.assertEqual(tarinfo.uid, 123)
  1176. self.assertEqual(tarinfo.uname, "foo")
  1177. self.assertEqual(len(tar.getmembers()), 3)
  1178. finally:
  1179. tar.close()
  1180. finally:
  1181. os_helper.rmtree(tempdir)
  1182. # Guarantee that stored pathnames are not modified. Don't
  1183. # remove ./ or ../ or double slashes. Still make absolute
  1184. # pathnames relative.
  1185. # For details see bug #6054.
  1186. def _test_pathname(self, path, cmp_path=None, dir=False):
  1187. # Create a tarfile with an empty member named path
  1188. # and compare the stored name with the original.
  1189. foo = os.path.join(TEMPDIR, "foo")
  1190. if not dir:
  1191. os_helper.create_empty_file(foo)
  1192. else:
  1193. os.mkdir(foo)
  1194. tar = tarfile.open(tmpname, self.mode)
  1195. try:
  1196. tar.add(foo, arcname=path)
  1197. finally:
  1198. tar.close()
  1199. tar = tarfile.open(tmpname, "r")
  1200. try:
  1201. t = tar.next()
  1202. finally:
  1203. tar.close()
  1204. if not dir:
  1205. os_helper.unlink(foo)
  1206. else:
  1207. os_helper.rmdir(foo)
  1208. self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
  1209. @os_helper.skip_unless_symlink
  1210. def test_extractall_symlinks(self):
  1211. # Test if extractall works properly when tarfile contains symlinks
  1212. tempdir = os.path.join(TEMPDIR, "testsymlinks")
  1213. temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
  1214. os.mkdir(tempdir)
  1215. try:
  1216. source_file = os.path.join(tempdir,'source')
  1217. target_file = os.path.join(tempdir,'symlink')
  1218. with open(source_file,'w') as f:
  1219. f.write('something\n')
  1220. os.symlink(source_file, target_file)
  1221. with tarfile.open(temparchive, 'w') as tar:
  1222. tar.add(source_file, arcname="source")
  1223. tar.add(target_file, arcname="symlink")
  1224. # Let's extract it to the location which contains the symlink
  1225. with tarfile.open(temparchive, errorlevel=2) as tar:
  1226. # this should not raise OSError: [Errno 17] File exists
  1227. try:
  1228. tar.extractall(path=tempdir)
  1229. except OSError:
  1230. self.fail("extractall failed with symlinked files")
  1231. finally:
  1232. os_helper.unlink(temparchive)
  1233. os_helper.rmtree(tempdir)
  1234. def test_pathnames(self):
  1235. self._test_pathname("foo")
  1236. self._test_pathname(os.path.join("foo", ".", "bar"))
  1237. self._test_pathname(os.path.join("foo", "..", "bar"))
  1238. self._test_pathname(os.path.join(".", "foo"))
  1239. self._test_pathname(os.path.join(".", "foo", "."))
  1240. self._test_pathname(os.path.join(".", "foo", ".", "bar"))
  1241. self._test_pathname(os.path.join(".", "foo", "..", "bar"))
  1242. self._test_pathname(os.path.join(".", "foo", "..", "bar"))
  1243. self._test_pathname(os.path.join("..", "foo"))
  1244. self._test_pathname(os.path.join("..", "foo", ".."))
  1245. self._test_pathname(os.path.join("..", "foo", ".", "bar"))
  1246. self._test_pathname(os.path.join("..", "foo", "..", "bar"))
  1247. self._test_pathname("foo" + os.sep + os.sep + "bar")
  1248. self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
  1249. def test_abs_pathnames(self):
  1250. if sys.platform == "win32":
  1251. self._test_pathname("C:\\foo", "foo")
  1252. else:
  1253. self._test_pathname("/foo", "foo")
  1254. self._test_pathname("///foo", "foo")
  1255. def test_cwd(self):
  1256. # Test adding the current working directory.
  1257. with os_helper.change_cwd(TEMPDIR):
  1258. tar = tarfile.open(tmpname, self.mode)
  1259. try:
  1260. tar.add(".")
  1261. finally:
  1262. tar.close()
  1263. tar = tarfile.open(tmpname, "r")
  1264. try:
  1265. for t in tar:
  1266. if t.name != ".":
  1267. self.assertTrue(t.name.startswith("./"), t.name)
  1268. finally:
  1269. tar.close()
  1270. def test_open_nonwritable_fileobj(self):
  1271. for exctype in OSError, EOFError, RuntimeError:
  1272. class BadFile(io.BytesIO):
  1273. first = True
  1274. def write(self, data):
  1275. if self.first:
  1276. self.first = False
  1277. raise exctype
  1278. f = BadFile()
  1279. with self.assertRaises(exctype):
  1280. tar = tarfile.open(tmpname, self.mode, fileobj=f,
  1281. format=tarfile.PAX_FORMAT,
  1282. pax_headers={'non': 'empty'})
  1283. self.assertFalse(f.closed)
  1284. class GzipWriteTest(GzipTest, WriteTest):
  1285. pass
  1286. class Bz2WriteTest(Bz2Test, WriteTest):
  1287. pass
  1288. class LzmaWriteTest(LzmaTest, WriteTest):
  1289. pass
  1290. class StreamWriteTest(WriteTestBase, unittest.TestCase):
  1291. prefix = "w|"
  1292. decompressor = None
  1293. def test_stream_padding(self):
  1294. # Test for bug #1543303.
  1295. tar = tarfile.open(tmpname, self.mode)
  1296. tar.close()
  1297. if self.decompressor:
  1298. dec = self.decompressor()
  1299. with open(tmpname, "rb") as fobj:
  1300. data = fobj.read()
  1301. data = dec.decompress(data)
  1302. self.assertFalse(dec.unused_data, "found trailing data")
  1303. else:
  1304. with self.open(tmpname) as fobj:
  1305. data = fobj.read()
  1306. self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
  1307. "incorrect zero padding")
  1308. @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
  1309. "Missing umask implementation")
  1310. @unittest.skipIf(
  1311. support.is_emscripten or support.is_wasi,
  1312. "Emscripten's/WASI's umask is a stub."
  1313. )
  1314. def test_file_mode(self):
  1315. # Test for issue #8464: Create files with correct
  1316. # permissions.
  1317. if os.path.exists(tmpname):
  1318. os_helper.unlink(tmpname)
  1319. original_umask = os.umask(0o022)
  1320. try:
  1321. tar = tarfile.open(tmpname, self.mode)
  1322. tar.close()
  1323. mode = os.stat(tmpname).st_mode & 0o777
  1324. self.assertEqual(mode, 0o644, "wrong file permissions")
  1325. finally:
  1326. os.umask(original_umask)
  1327. class GzipStreamWriteTest(GzipTest, StreamWriteTest):
  1328. def test_source_directory_not_leaked(self):
  1329. """
  1330. Ensure the source directory is not included in the tar header
  1331. per bpo-41316.
  1332. """
  1333. tarfile.open(tmpname, self.mode).close()
  1334. payload = pathlib.Path(tmpname).read_text(encoding='latin-1')
  1335. assert os.path.dirname(tmpname) not in payload
  1336. class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
  1337. decompressor = bz2.BZ2Decompressor if bz2 else None
  1338. class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
  1339. decompressor = lzma.LZMADecompressor if lzma else None
  1340. class GNUWriteTest(unittest.TestCase):
  1341. # This testcase checks for correct creation of GNU Longname
  1342. # and Longlink extended headers (cp. bug #812325).
  1343. def _length(self, s):
  1344. blocks = len(s) // 512 + 1
  1345. return blocks * 512
  1346. def _calc_size(self, name, link=None):
  1347. # Initial tar header
  1348. count = 512
  1349. if len(name) > tarfile.LENGTH_NAME:
  1350. # GNU longname extended header + longname
  1351. count += 512
  1352. count += self._length(name)
  1353. if link is not None and len(link) > tarfile.LENGTH_LINK:
  1354. # GNU longlink extended header + longlink
  1355. count += 512
  1356. count += self._length(link)
  1357. return count
  1358. def _test(self, name, link=None):
  1359. tarinfo = tarfile.TarInfo(name)
  1360. if link:
  1361. tarinfo.linkname = link
  1362. tarinfo.type = tarfile.LNKTYPE
  1363. tar = tarfile.open(tmpname, "w")
  1364. try:
  1365. tar.format = tarfile.GNU_FORMAT
  1366. tar.addfile(tarinfo)
  1367. v1 = self._calc_size(name, link)
  1368. v2 = tar.offset
  1369. self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
  1370. finally:
  1371. tar.close()
  1372. tar = tarfile.open(tmpname)
  1373. try:
  1374. member = tar.next()
  1375. self.assertIsNotNone(member,
  1376. "unable to read longname member")
  1377. self.assertEqual(tarinfo.name, member.name,
  1378. "unable to read longname member")
  1379. self.assertEqual(tarinfo.linkname, member.linkname,
  1380. "unable to read longname member")
  1381. finally:
  1382. tar.close()
  1383. def test_longname_1023(self):
  1384. self._test(("longnam/" * 127) + "longnam")
  1385. def test_longname_1024(self):
  1386. self._test(("longnam/" * 127) + "longname")
  1387. def test_longname_1025(self):
  1388. self._test(("longnam/" * 127) + "longname_")
  1389. def test_longlink_1023(self):
  1390. self._test("name", ("longlnk/" * 127) + "longlnk")
  1391. def test_longlink_1024(self):
  1392. self._test("name", ("longlnk/" * 127) + "longlink")
  1393. def test_longlink_1025(self):
  1394. self._test("name", ("longlnk/" * 127) + "longlink_")
  1395. def test_longnamelink_1023(self):
  1396. self._test(("longnam/" * 127) + "longnam",
  1397. ("longlnk/" * 127) + "longlnk")
  1398. def test_longnamelink_1024(self):
  1399. self._test(("longnam/" * 127) + "longname",
  1400. ("longlnk/" * 127) + "longlink")
  1401. def test_longnamelink_1025(self):
  1402. self._test(("longnam/" * 127) + "longname_",
  1403. ("longlnk/" * 127) + "longlink_")
  1404. class DeviceHeaderTest(WriteTestBase, unittest.TestCase):
  1405. prefix = "w:"
  1406. def test_headers_written_only_for_device_files(self):
  1407. # Regression test for bpo-18819.
  1408. tempdir = os.path.join(TEMPDIR, "device_header_test")
  1409. os.mkdir(tempdir)
  1410. try:
  1411. tar = tarfile.open(tmpname, self.mode)
  1412. try:
  1413. input_blk = tarfile.TarInfo(name="my_block_device")
  1414. input_reg = tarfile.TarInfo(name="my_regular_file")
  1415. input_blk.type = tarfile.BLKTYPE
  1416. input_reg.type = tarfile.REGTYPE
  1417. tar.addfile(input_blk)
  1418. tar.addfile(input_reg)
  1419. finally:
  1420. tar.close()
  1421. # devmajor and devminor should be *interpreted* as 0 in both...
  1422. tar = tarfile.open(tmpname, "r")
  1423. try:
  1424. output_blk = tar.getmember("my_block_device")
  1425. output_reg = tar.getmember("my_regular_file")
  1426. finally:
  1427. tar.close()
  1428. self.assertEqual(output_blk.devmajor, 0)
  1429. self.assertEqual(output_blk.devminor, 0)
  1430. self.assertEqual(output_reg.devmajor, 0)
  1431. self.assertEqual(output_reg.devminor, 0)
  1432. # ...but the fields should not actually be set on regular files:
  1433. with open(tmpname, "rb") as infile:
  1434. buf = infile.read()
  1435. buf_blk = buf[output_blk.offset:output_blk.offset_data]
  1436. buf_reg = buf[output_reg.offset:output_reg.offset_data]
  1437. # See `struct posixheader` in GNU docs for byte offsets:
  1438. # <https://www.gnu.org/software/tar/manual/html_node/Standard.html>
  1439. device_headers = slice(329, 329 + 16)
  1440. self.assertEqual(buf_blk[device_headers], b"0000000\0" * 2)
  1441. self.assertEqual(buf_reg[device_headers], b"\0" * 16)
  1442. finally:
  1443. os_helper.rmtree(tempdir)
  1444. class CreateTest(WriteTestBase, unittest.TestCase):
  1445. prefix = "x:"
  1446. file_path = os.path.join(TEMPDIR, "spameggs42")
  1447. def setUp(self):
  1448. os_helper.unlink(tmpname)
  1449. @classmethod
  1450. def setUpClass(cls):
  1451. with open(cls.file_path, "wb") as fobj:
  1452. fobj.write(b"aaa")
  1453. @classmethod
  1454. def tearDownClass(cls):
  1455. os_helper.unlink(cls.file_path)
  1456. def test_create(self):
  1457. with tarfile.open(tmpname, self.mode) as tobj:
  1458. tobj.add(self.file_path)
  1459. with self.taropen(tmpname) as tobj:
  1460. names = tobj.getnames()
  1461. self.assertEqual(len(names), 1)
  1462. self.assertIn('spameggs42', names[0])
  1463. def test_create_existing(self):
  1464. with tarfile.open(tmpname, self.mode) as tobj:
  1465. tobj.add(self.file_path)
  1466. with self.assertRaises(FileExistsError):
  1467. tobj = tarfile.open(tmpname, self.mode)
  1468. with self.taropen(tmpname) as tobj:
  1469. names = tobj.getnames()
  1470. self.assertEqual(len(names), 1)
  1471. self.assertIn('spameggs42', names[0])
  1472. def test_create_taropen(self):
  1473. with self.taropen(tmpname, "x") as tobj:
  1474. tobj.add(self.file_path)
  1475. with self.taropen(tmpname) as tobj:
  1476. names = tobj.getnames()
  1477. self.assertEqual(len(names), 1)
  1478. self.assertIn('spameggs42', names[0])
  1479. def test_create_existing_taropen(self):
  1480. with self.taropen(tmpname, "x") as tobj:
  1481. tobj.add(self.file_path)
  1482. with self.assertRaises(FileExistsError):
  1483. with self.taropen(tmpname, "x"):
  1484. pass
  1485. with self.taropen(tmpname) as tobj:
  1486. names = tobj.getnames()
  1487. self.assertEqual(len(names), 1)
  1488. self.assertIn("spameggs42", names[0])
  1489. def test_create_pathlike_name(self):
  1490. with tarfile.open(pathlib.Path(tmpname), self.mode) as tobj:
  1491. self.assertIsInstance(tobj.name, str)
  1492. self.assertEqual(tobj.name, os.path.abspath(tmpname))
  1493. tobj.add(pathlib.Path(self.file_path))
  1494. names = tobj.getnames()
  1495. self.assertEqual(len(names), 1)
  1496. self.assertIn('spameggs42', names[0])
  1497. with self.taropen(tmpname) as tobj:
  1498. names = tobj.getnames()
  1499. self.assertEqual(len(names), 1)
  1500. self.assertIn('spameggs42', names[0])
  1501. def test_create_taropen_pathlike_name(self):
  1502. with self.taropen(pathlib.Path(tmpname), "x") as tobj:
  1503. self.assertIsInstance(tobj.name, str)
  1504. self.assertEqual(tobj.name, os.path.abspath(tmpname))
  1505. tobj.add(pathlib.Path(self.file_path))
  1506. names = tobj.getnames()
  1507. self.assertEqual(len(names), 1)
  1508. self.assertIn('spameggs42', names[0])
  1509. with self.taropen(tmpname) as tobj:
  1510. names = tobj.getnames()
  1511. self.assertEqual(len(names), 1)
  1512. self.assertIn('spameggs42', names[0])
  1513. class GzipCreateTest(GzipTest, CreateTest):
  1514. def test_create_with_compresslevel(self):
  1515. with tarfile.open(tmpname, self.mode, compresslevel=1) as tobj:
  1516. tobj.add(self.file_path)
  1517. with tarfile.open(tmpname, 'r:gz', compresslevel=1) as tobj:
  1518. pass
  1519. class Bz2CreateTest(Bz2Test, CreateTest):
  1520. def test_create_with_compresslevel(self):
  1521. with tarfile.open(tmpname, self.mode, compresslevel=1) as tobj:
  1522. tobj.add(self.file_path)
  1523. with tarfile.open(tmpname, 'r:bz2', compresslevel=1) as tobj:
  1524. pass
  1525. class LzmaCreateTest(LzmaTest, CreateTest):
  1526. # Unlike gz and bz2, xz uses the preset keyword instead of compresslevel.
  1527. # It does not allow for preset to be specified when reading.
  1528. def test_create_with_preset(self):
  1529. with tarfile.open(tmpname, self.mode, preset=1) as tobj:
  1530. tobj.add(self.file_path)
  1531. class CreateWithXModeTest(CreateTest):
  1532. prefix = "x"
  1533. test_create_taropen = None
  1534. test_create_existing_taropen = None
  1535. @unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
  1536. class HardlinkTest(unittest.TestCase):
  1537. # Test the creation of LNKTYPE (hardlink) members in an archive.
  1538. def setUp(self):
  1539. self.foo = os.path.join(TEMPDIR, "foo")
  1540. self.bar = os.path.join(TEMPDIR, "bar")
  1541. with open(self.foo, "wb") as fobj:
  1542. fobj.write(b"foo")
  1543. try:
  1544. os.link(self.foo, self.bar)
  1545. except PermissionError as e:
  1546. self.skipTest('os.link(): %s' % e)
  1547. self.tar = tarfile.open(tmpname, "w")
  1548. self.tar.add(self.foo)
  1549. def tearDown(self):
  1550. self.tar.close()
  1551. os_helper.unlink(self.foo)
  1552. os_helper.unlink(self.bar)
  1553. def test_add_twice(self):
  1554. # The same name will be added as a REGTYPE every
  1555. # time regardless of st_nlink.
  1556. tarinfo = self.tar.gettarinfo(self.foo)
  1557. self.assertEqual(tarinfo.type, tarfile.REGTYPE,
  1558. "add file as regular failed")
  1559. def test_add_hardlink(self):
  1560. tarinfo = self.tar.gettarinfo(self.bar)
  1561. self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
  1562. "add file as hardlink failed")
  1563. def test_dereference_hardlink(self):
  1564. self.tar.dereference = True
  1565. tarinfo = self.tar.gettarinfo(self.bar)
  1566. self.assertEqual(tarinfo.type, tarfile.REGTYPE,
  1567. "dereferencing hardlink failed")
  1568. class PaxWriteTest(GNUWriteTest):
  1569. def _test(self, name, link=None):
  1570. # See GNUWriteTest.
  1571. tarinfo = tarfile.TarInfo(name)
  1572. if link:
  1573. tarinfo.linkname = link
  1574. tarinfo.type = tarfile.LNKTYPE
  1575. tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
  1576. try:
  1577. tar.addfile(tarinfo)
  1578. finally:
  1579. tar.close()
  1580. tar = tarfile.open(tmpname)
  1581. try:
  1582. if link:
  1583. l = tar.getmembers()[0].linkname
  1584. self.assertEqual(link, l, "PAX longlink creation failed")
  1585. else:
  1586. n = tar.getmembers()[0].name
  1587. self.assertEqual(name, n, "PAX longname creation failed")
  1588. finally:
  1589. tar.close()
  1590. def test_pax_global_header(self):
  1591. pax_headers = {
  1592. "foo": "bar",
  1593. "uid": "0",
  1594. "mtime": "1.23",
  1595. "test": "\xe4\xf6\xfc",
  1596. "\xe4\xf6\xfc": "test"}
  1597. tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
  1598. pax_headers=pax_headers)
  1599. try:
  1600. tar.addfile(tarfile.TarInfo("test"))
  1601. finally:
  1602. tar.close()
  1603. # Test if the global header was written correctly.
  1604. tar = tarfile.open(tmpname, encoding="iso8859-1")
  1605. try:
  1606. self.assertEqual(tar.pax_headers, pax_headers)
  1607. self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
  1608. # Test if all the fields are strings.
  1609. for key, val in tar.pax_headers.items():
  1610. self.assertIsNot(type(key), bytes)
  1611. self.assertIsNot(type(val), bytes)
  1612. if key in tarfile.PAX_NUMBER_FIELDS:
  1613. try:
  1614. tarfile.PAX_NUMBER_FIELDS[key](val)
  1615. except (TypeError, ValueError):
  1616. self.fail("unable to convert pax header field")
  1617. finally:
  1618. tar.close()
  1619. def test_pax_extended_header(self):
  1620. # The fields from the pax header have priority over the
  1621. # TarInfo.
  1622. pax_headers = {"path": "foo", "uid": "123"}
  1623. tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
  1624. encoding="iso8859-1")
  1625. try:
  1626. t = tarfile.TarInfo()
  1627. t.name = "\xe4\xf6\xfc" # non-ASCII
  1628. t.uid = 8**8 # too large
  1629. t.pax_headers = pax_headers
  1630. tar.addfile(t)
  1631. finally:
  1632. tar.close()
  1633. tar = tarfile.open(tmpname, encoding="iso8859-1")
  1634. try:
  1635. t = tar.getmembers()[0]
  1636. self.assertEqual(t.pax_headers, pax_headers)
  1637. self.assertEqual(t.name, "foo")
  1638. self.assertEqual(t.uid, 123)
  1639. finally:
  1640. tar.close()
  1641. def test_create_pax_header(self):
  1642. # The ustar header should contain values that can be
  1643. # represented reasonably, even if a better (e.g. higher
  1644. # precision) version is set in the pax header.
  1645. # Issue #45863
  1646. # values that should be kept
  1647. t = tarfile.TarInfo()
  1648. t.name = "foo"
  1649. t.mtime = 1000.1
  1650. t.size = 100
  1651. t.uid = 123
  1652. t.gid = 124
  1653. info = t.get_info()
  1654. header = t.create_pax_header(info, encoding="iso8859-1")
  1655. self.assertEqual(info['name'], "foo")
  1656. # mtime should be rounded to nearest second
  1657. self.assertIsInstance(info['mtime'], int)
  1658. self.assertEqual(info['mtime'], 1000)
  1659. self.assertEqual(info['size'], 100)
  1660. self.assertEqual(info['uid'], 123)
  1661. self.assertEqual(info['gid'], 124)
  1662. self.assertEqual(header,
  1663. b'././@PaxHeader' + bytes(86) \
  1664. + b'0000000\x000000000\x000000000\x0000000000020\x0000000000000\x00010205\x00 x' \
  1665. + bytes(100) + b'ustar\x0000'+ bytes(247) \
  1666. + b'16 mtime=1000.1\n' + bytes(496) + b'foo' + bytes(97) \
  1667. + b'0000644\x000000173\x000000174\x0000000000144\x0000000001750\x00006516\x00 0' \
  1668. + bytes(100) + b'ustar\x0000' + bytes(247))
  1669. # values that should be changed
  1670. t = tarfile.TarInfo()
  1671. t.name = "foo\u3374" # can't be represented in ascii
  1672. t.mtime = 10**10 # too big
  1673. t.size = 10**10 # too big
  1674. t.uid = 8**8 # too big
  1675. t.gid = 8**8+1 # too big
  1676. info = t.get_info()
  1677. header = t.create_pax_header(info, encoding="iso8859-1")
  1678. # name is kept as-is in info but should be added to pax header
  1679. self.assertEqual(info['name'], "foo\u3374")
  1680. self.assertEqual(info['mtime'], 0)
  1681. self.assertEqual(info['size'], 0)
  1682. self.assertEqual(info['uid'], 0)
  1683. self.assertEqual(info['gid'], 0)
  1684. self.assertEqual(header,
  1685. b'././@PaxHeader' + bytes(86) \
  1686. + b'0000000\x000000000\x000000000\x0000000000130\x0000000000000\x00010207\x00 x' \
  1687. + bytes(100) + b'ustar\x0000' + bytes(247) \
  1688. + b'15 path=foo\xe3\x8d\xb4\n16 uid=16777216\n' \
  1689. + b'16 gid=16777217\n20 size=10000000000\n' \
  1690. + b'21 mtime=10000000000\n'+ bytes(424) + b'foo?' + bytes(96) \
  1691. + b'0000644\x000000000\x000000000\x0000000000000\x0000000000000\x00006540\x00 0' \
  1692. + bytes(100) + b'ustar\x0000' + bytes(247))
  1693. class UnicodeTest:
  1694. def test_iso8859_1_filename(self):
  1695. self._test_unicode_filename("iso8859-1")
  1696. def test_utf7_filename(self):
  1697. self._test_unicode_filename("utf7")
  1698. def test_utf8_filename(self):
  1699. self._test_unicode_filename("utf-8")
  1700. def _test_unicode_filename(self, encoding):
  1701. tar = tarfile.open(tmpname, "w", format=self.format,
  1702. encoding=encoding, errors="strict")
  1703. try:
  1704. name = "\xe4\xf6\xfc"
  1705. tar.addfile(tarfile.TarInfo(name))
  1706. finally:
  1707. tar.close()
  1708. tar = tarfile.open(tmpname, encoding=encoding)
  1709. try:
  1710. self.assertEqual(tar.getmembers()[0].name, name)
  1711. finally:
  1712. tar.close()
  1713. def test_unicode_filename_error(self):
  1714. tar = tarfile.open(tmpname, "w", format=self.format,
  1715. encoding="ascii", errors="strict")
  1716. try:
  1717. tarinfo = tarfile.TarInfo()
  1718. tarinfo.name = "\xe4\xf6\xfc"
  1719. self.assertRaises(UnicodeError, tar.addfile, tarinfo)
  1720. tarinfo.name = "foo"
  1721. tarinfo.uname = "\xe4\xf6\xfc"
  1722. self.assertRaises(UnicodeError, tar.addfile, tarinfo)
  1723. finally:
  1724. tar.close()
  1725. def test_unicode_argument(self):
  1726. tar = tarfile.open(tarname, "r",
  1727. encoding="iso8859-1", errors="strict")
  1728. try:
  1729. for t in tar:
  1730. self.assertIs(type(t.name), str)
  1731. self.assertIs(type(t.linkname), str)
  1732. self.assertIs(type(t.uname), str)
  1733. self.assertIs(type(t.gname), str)
  1734. finally:
  1735. tar.close()
  1736. def test_uname_unicode(self):
  1737. t = tarfile.TarInfo("foo")
  1738. t.uname = "\xe4\xf6\xfc"
  1739. t.gname = "\xe4\xf6\xfc"
  1740. tar = tarfile.open(tmpname, mode="w", format=self.format,
  1741. encoding="iso8859-1")
  1742. try:
  1743. tar.addfile(t)
  1744. finally:
  1745. tar.close()
  1746. tar = tarfile.open(tmpname, encoding="iso8859-1")
  1747. try:
  1748. t = tar.getmember("foo")
  1749. self.assertEqual(t.uname, "\xe4\xf6\xfc")
  1750. self.assertEqual(t.gname, "\xe4\xf6\xfc")
  1751. if self.format != tarfile.PAX_FORMAT:
  1752. tar.close()
  1753. tar = tarfile.open(tmpname, encoding="ascii")
  1754. t = tar.getmember("foo")
  1755. self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
  1756. self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
  1757. finally:
  1758. tar.close()
  1759. class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
  1760. format = tarfile.USTAR_FORMAT
  1761. # Test whether the utf-8 encoded version of a filename exceeds the 100
  1762. # bytes name field limit (every occurrence of '\xff' will be expanded to 2
  1763. # bytes).
  1764. def test_unicode_name1(self):
  1765. self._test_ustar_name("0123456789" * 10)
  1766. self._test_ustar_name("0123456789" * 10 + "0", ValueError)
  1767. self._test_ustar_name("0123456789" * 9 + "01234567\xff")
  1768. self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
  1769. def test_unicode_name2(self):
  1770. self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
  1771. self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
  1772. # Test whether the utf-8 encoded version of a filename exceeds the 155
  1773. # bytes prefix + '/' + 100 bytes name limit.
  1774. def test_unicode_longname1(self):
  1775. self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
  1776. self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
  1777. self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
  1778. self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
  1779. def test_unicode_longname2(self):
  1780. self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
  1781. self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
  1782. def test_unicode_longname3(self):
  1783. self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
  1784. self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
  1785. self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
  1786. def test_unicode_longname4(self):
  1787. self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
  1788. self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
  1789. def _test_ustar_name(self, name, exc=None):
  1790. with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
  1791. t = tarfile.TarInfo(name)
  1792. if exc is None:
  1793. tar.addfile(t)
  1794. else:
  1795. self.assertRaises(exc, tar.addfile, t)
  1796. if exc is None:
  1797. with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
  1798. for t in tar:
  1799. self.assertEqual(name, t.name)
  1800. break
  1801. # Test the same as above for the 100 bytes link field.
  1802. def test_unicode_link1(self):
  1803. self._test_ustar_link("0123456789" * 10)
  1804. self._test_ustar_link("0123456789" * 10 + "0", ValueError)
  1805. self._test_ustar_link("0123456789" * 9 + "01234567\xff")
  1806. self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
  1807. def test_unicode_link2(self):
  1808. self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
  1809. self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
  1810. def _test_ustar_link(self, name, exc=None):
  1811. with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
  1812. t = tarfile.TarInfo("foo")
  1813. t.linkname = name
  1814. if exc is None:
  1815. tar.addfile(t)
  1816. else:
  1817. self.assertRaises(exc, tar.addfile, t)
  1818. if exc is None:
  1819. with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
  1820. for t in tar:
  1821. self.assertEqual(name, t.linkname)
  1822. break
  1823. class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
  1824. format = tarfile.GNU_FORMAT
  1825. def test_bad_pax_header(self):
  1826. # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
  1827. # without a hdrcharset=BINARY header.
  1828. for encoding, name in (
  1829. ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
  1830. ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
  1831. with tarfile.open(tarname, encoding=encoding,
  1832. errors="surrogateescape") as tar:
  1833. try:
  1834. t = tar.getmember(name)
  1835. except KeyError:
  1836. self.fail("unable to read bad GNU tar pax header")
  1837. class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
  1838. format = tarfile.PAX_FORMAT
  1839. # PAX_FORMAT ignores encoding in write mode.
  1840. test_unicode_filename_error = None
  1841. def test_binary_header(self):
  1842. # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
  1843. for encoding, name in (
  1844. ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
  1845. ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
  1846. with tarfile.open(tarname, encoding=encoding,
  1847. errors="surrogateescape") as tar:
  1848. try:
  1849. t = tar.getmember(name)
  1850. except KeyError:
  1851. self.fail("unable to read POSIX.1-2008 binary header")
  1852. class AppendTestBase:
  1853. # Test append mode (cp. patch #1652681).
  1854. def setUp(self):
  1855. self.tarname = tmpname
  1856. if os.path.exists(self.tarname):
  1857. os_helper.unlink(self.tarname)
  1858. def _create_testtar(self, mode="w:"):
  1859. with tarfile.open(tarname, encoding="iso8859-1") as src:
  1860. t = src.getmember("ustar/regtype")
  1861. t.name = "foo"
  1862. with src.extractfile(t) as f:
  1863. with tarfile.open(self.tarname, mode) as tar:
  1864. tar.addfile(t, f)
  1865. def test_append_compressed(self):
  1866. self._create_testtar("w:" + self.suffix)
  1867. self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
  1868. class AppendTest(AppendTestBase, unittest.TestCase):
  1869. test_append_compressed = None
  1870. def _add_testfile(self, fileobj=None):
  1871. with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
  1872. tar.addfile(tarfile.TarInfo("bar"))
  1873. def _test(self, names=["bar"], fileobj=None):
  1874. with tarfile.open(self.tarname, fileobj=fileobj) as tar:
  1875. self.assertEqual(tar.getnames(), names)
  1876. def test_non_existing(self):
  1877. self._add_testfile()
  1878. self._test()
  1879. def test_empty(self):
  1880. tarfile.open(self.tarname, "w:").close()
  1881. self._add_testfile()
  1882. self._test()
  1883. def test_empty_fileobj(self):
  1884. fobj = io.BytesIO(b"\0" * 1024)
  1885. self._add_testfile(fobj)
  1886. fobj.seek(0)
  1887. self._test(fileobj=fobj)
  1888. def test_fileobj(self):
  1889. self._create_testtar()
  1890. with open(self.tarname, "rb") as fobj:
  1891. data = fobj.read()
  1892. fobj = io.BytesIO(data)
  1893. self._add_testfile(fobj)
  1894. fobj.seek(0)
  1895. self._test(names=["foo", "bar"], fileobj=fobj)
  1896. def test_existing(self):
  1897. self._create_testtar()
  1898. self._add_testfile()
  1899. self._test(names=["foo", "bar"])
  1900. # Append mode is supposed to fail if the tarfile to append to
  1901. # does not end with a zero block.
  1902. def _test_error(self, data):
  1903. with open(self.tarname, "wb") as fobj:
  1904. fobj.write(data)
  1905. self.assertRaises(tarfile.ReadError, self._add_testfile)
  1906. def test_null(self):
  1907. self._test_error(b"")
  1908. def test_incomplete(self):
  1909. self._test_error(b"\0" * 13)
  1910. def test_premature_eof(self):
  1911. data = tarfile.TarInfo("foo").tobuf()
  1912. self._test_error(data)
  1913. def test_trailing_garbage(self):
  1914. data = tarfile.TarInfo("foo").tobuf()
  1915. self._test_error(data + b"\0" * 13)
  1916. def test_invalid(self):
  1917. self._test_error(b"a" * 512)
  1918. class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
  1919. pass
  1920. class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
  1921. pass
  1922. class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
  1923. pass
  1924. class LimitsTest(unittest.TestCase):
  1925. def test_ustar_limits(self):
  1926. # 100 char name
  1927. tarinfo = tarfile.TarInfo("0123456789" * 10)
  1928. tarinfo.tobuf(tarfile.USTAR_FORMAT)
  1929. # 101 char name that cannot be stored
  1930. tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
  1931. self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
  1932. # 256 char name with a slash at pos 156
  1933. tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
  1934. tarinfo.tobuf(tarfile.USTAR_FORMAT)
  1935. # 256 char name that cannot be stored
  1936. tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
  1937. self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
  1938. # 512 char name
  1939. tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
  1940. self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
  1941. # 512 char linkname
  1942. tarinfo = tarfile.TarInfo("longlink")
  1943. tarinfo.linkname = "123/" * 126 + "longname"
  1944. self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
  1945. # uid > 8 digits
  1946. tarinfo = tarfile.TarInfo("name")
  1947. tarinfo.uid = 0o10000000
  1948. self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
  1949. def test_gnu_limits(self):
  1950. tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
  1951. tarinfo.tobuf(tarfile.GNU_FORMAT)
  1952. tarinfo = tarfile.TarInfo("longlink")
  1953. tarinfo.linkname = "123/" * 126 + "longname"
  1954. tarinfo.tobuf(tarfile.GNU_FORMAT)
  1955. # uid >= 256 ** 7
  1956. tarinfo = tarfile.TarInfo("name")
  1957. tarinfo.uid = 0o4000000000000000000
  1958. self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
  1959. def test_pax_limits(self):
  1960. tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
  1961. tarinfo.tobuf(tarfile.PAX_FORMAT)
  1962. tarinfo = tarfile.TarInfo("longlink")
  1963. tarinfo.linkname = "123/" * 126 + "longname"
  1964. tarinfo.tobuf(tarfile.PAX_FORMAT)
  1965. tarinfo = tarfile.TarInfo("name")
  1966. tarinfo.uid = 0o4000000000000000000
  1967. tarinfo.tobuf(tarfile.PAX_FORMAT)
  1968. class MiscTest(unittest.TestCase):
  1969. def test_char_fields(self):
  1970. self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
  1971. b"foo\0\0\0\0\0")
  1972. self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
  1973. b"foo")
  1974. self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
  1975. "foo")
  1976. self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
  1977. "foo")
  1978. def test_read_number_fields(self):
  1979. # Issue 13158: Test if GNU tar specific base-256 number fields
  1980. # are decoded correctly.
  1981. self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
  1982. self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
  1983. self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
  1984. 0o10000000)
  1985. self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
  1986. 0xffffffff)
  1987. self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
  1988. -1)
  1989. self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
  1990. -100)
  1991. self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
  1992. -0x100000000000000)
  1993. # Issue 24514: Test if empty number fields are converted to zero.
  1994. self.assertEqual(tarfile.nti(b"\0"), 0)
  1995. self.assertEqual(tarfile.nti(b" \0"), 0)
  1996. def test_write_number_fields(self):
  1997. self.assertEqual(tarfile.itn(1), b"0000001\x00")
  1998. self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
  1999. self.assertEqual(tarfile.itn(0o10000000, format=tarfile.GNU_FORMAT),
  2000. b"\x80\x00\x00\x00\x00\x20\x00\x00")
  2001. self.assertEqual(tarfile.itn(0xffffffff, format=tarfile.GNU_FORMAT),
  2002. b"\x80\x00\x00\x00\xff\xff\xff\xff")
  2003. self.assertEqual(tarfile.itn(-1, format=tarfile.GNU_FORMAT),
  2004. b"\xff\xff\xff\xff\xff\xff\xff\xff")
  2005. self.assertEqual(tarfile.itn(-100, format=tarfile.GNU_FORMAT),
  2006. b"\xff\xff\xff\xff\xff\xff\xff\x9c")
  2007. self.assertEqual(tarfile.itn(-0x100000000000000,
  2008. format=tarfile.GNU_FORMAT),
  2009. b"\xff\x00\x00\x00\x00\x00\x00\x00")
  2010. # Issue 32713: Test if itn() supports float values outside the
  2011. # non-GNU format range
  2012. self.assertEqual(tarfile.itn(-100.0, format=tarfile.GNU_FORMAT),
  2013. b"\xff\xff\xff\xff\xff\xff\xff\x9c")
  2014. self.assertEqual(tarfile.itn(8 ** 12 + 0.0, format=tarfile.GNU_FORMAT),
  2015. b"\x80\x00\x00\x10\x00\x00\x00\x00")
  2016. self.assertEqual(tarfile.nti(tarfile.itn(-0.1, format=tarfile.GNU_FORMAT)), 0)
  2017. def test_number_field_limits(self):
  2018. with self.assertRaises(ValueError):
  2019. tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
  2020. with self.assertRaises(ValueError):
  2021. tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
  2022. with self.assertRaises(ValueError):
  2023. tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
  2024. with self.assertRaises(ValueError):
  2025. tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
  2026. def test__all__(self):
  2027. not_exported = {
  2028. 'version', 'grp', 'pwd', 'symlink_exception', 'NUL', 'BLOCKSIZE',
  2029. 'RECORDSIZE', 'GNU_MAGIC', 'POSIX_MAGIC', 'LENGTH_NAME',
  2030. 'LENGTH_LINK', 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
  2031. 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE', 'CONTTYPE',
  2032. 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK', 'GNUTYPE_SPARSE',
  2033. 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE', 'SUPPORTED_TYPES',
  2034. 'REGULAR_TYPES', 'GNU_TYPES', 'PAX_FIELDS', 'PAX_NAME_FIELDS',
  2035. 'PAX_NUMBER_FIELDS', 'stn', 'nts', 'nti', 'itn', 'calc_chksums',
  2036. 'copyfileobj', 'filemode', 'EmptyHeaderError',
  2037. 'TruncatedHeaderError', 'EOFHeaderError', 'InvalidHeaderError',
  2038. 'SubsequentHeaderError', 'ExFileObject', 'main'}
  2039. support.check__all__(self, tarfile, not_exported=not_exported)
  2040. def test_useful_error_message_when_modules_missing(self):
  2041. fname = os.path.join(os.path.dirname(__file__), 'testtar.tar.xz')
  2042. with self.assertRaises(tarfile.ReadError) as excinfo:
  2043. error = tarfile.CompressionError('lzma module is not available'),
  2044. with unittest.mock.patch.object(tarfile.TarFile, 'xzopen', side_effect=error):
  2045. tarfile.open(fname)
  2046. self.assertIn(
  2047. "\n- method xz: CompressionError('lzma module is not available')\n",
  2048. str(excinfo.exception),
  2049. )
  2050. class CommandLineTest(unittest.TestCase):
  2051. def tarfilecmd(self, *args, **kwargs):
  2052. rc, out, err = script_helper.assert_python_ok('-m', 'tarfile', *args,
  2053. **kwargs)
  2054. return out.replace(os.linesep.encode(), b'\n')
  2055. def tarfilecmd_failure(self, *args):
  2056. return script_helper.assert_python_failure('-m', 'tarfile', *args)
  2057. def make_simple_tarfile(self, tar_name):
  2058. files = [support.findfile('tokenize_tests.txt'),
  2059. support.findfile('tokenize_tests-no-coding-cookie-'
  2060. 'and-utf8-bom-sig-only.txt')]
  2061. self.addCleanup(os_helper.unlink, tar_name)
  2062. with tarfile.open(tar_name, 'w') as tf:
  2063. for tardata in files:
  2064. tf.add(tardata, arcname=os.path.basename(tardata))
  2065. def test_bad_use(self):
  2066. rc, out, err = self.tarfilecmd_failure()
  2067. self.assertEqual(out, b'')
  2068. self.assertIn(b'usage', err.lower())
  2069. self.assertIn(b'error', err.lower())
  2070. self.assertIn(b'required', err.lower())
  2071. rc, out, err = self.tarfilecmd_failure('-l', '')
  2072. self.assertEqual(out, b'')
  2073. self.assertNotEqual(err.strip(), b'')
  2074. def test_test_command(self):
  2075. for tar_name in testtarnames:
  2076. for opt in '-t', '--test':
  2077. out = self.tarfilecmd(opt, tar_name)
  2078. self.assertEqual(out, b'')
  2079. def test_test_command_verbose(self):
  2080. for tar_name in testtarnames:
  2081. for opt in '-v', '--verbose':
  2082. out = self.tarfilecmd(opt, '-t', tar_name,
  2083. PYTHONIOENCODING='utf-8')
  2084. self.assertIn(b'is a tar archive.\n', out)
  2085. def test_test_command_invalid_file(self):
  2086. zipname = support.findfile('zipdir.zip')
  2087. rc, out, err = self.tarfilecmd_failure('-t', zipname)
  2088. self.assertIn(b' is not a tar archive.', err)
  2089. self.assertEqual(out, b'')
  2090. self.assertEqual(rc, 1)
  2091. for tar_name in testtarnames:
  2092. with self.subTest(tar_name=tar_name):
  2093. with open(tar_name, 'rb') as f:
  2094. data = f.read()
  2095. try:
  2096. with open(tmpname, 'wb') as f:
  2097. f.write(data[:511])
  2098. rc, out, err = self.tarfilecmd_failure('-t', tmpname)
  2099. self.assertEqual(out, b'')
  2100. self.assertEqual(rc, 1)
  2101. finally:
  2102. os_helper.unlink(tmpname)
  2103. def test_list_command(self):
  2104. for tar_name in testtarnames:
  2105. with support.captured_stdout() as t:
  2106. with tarfile.open(tar_name, 'r') as tf:
  2107. tf.list(verbose=False)
  2108. expected = t.getvalue().encode('ascii', 'backslashreplace')
  2109. for opt in '-l', '--list':
  2110. out = self.tarfilecmd(opt, tar_name,
  2111. PYTHONIOENCODING='ascii')
  2112. self.assertEqual(out, expected)
  2113. def test_list_command_verbose(self):
  2114. for tar_name in testtarnames:
  2115. with support.captured_stdout() as t:
  2116. with tarfile.open(tar_name, 'r') as tf:
  2117. tf.list(verbose=True)
  2118. expected = t.getvalue().encode('ascii', 'backslashreplace')
  2119. for opt in '-v', '--verbose':
  2120. out = self.tarfilecmd(opt, '-l', tar_name,
  2121. PYTHONIOENCODING='ascii')
  2122. self.assertEqual(out, expected)
  2123. def test_list_command_invalid_file(self):
  2124. zipname = support.findfile('zipdir.zip')
  2125. rc, out, err = self.tarfilecmd_failure('-l', zipname)
  2126. self.assertIn(b' is not a tar archive.', err)
  2127. self.assertEqual(out, b'')
  2128. self.assertEqual(rc, 1)
  2129. def test_create_command(self):
  2130. files = [support.findfile('tokenize_tests.txt'),
  2131. support.findfile('tokenize_tests-no-coding-cookie-'
  2132. 'and-utf8-bom-sig-only.txt')]
  2133. for opt in '-c', '--create':
  2134. try:
  2135. out = self.tarfilecmd(opt, tmpname, *files)
  2136. self.assertEqual(out, b'')
  2137. with tarfile.open(tmpname) as tar:
  2138. tar.getmembers()
  2139. finally:
  2140. os_helper.unlink(tmpname)
  2141. def test_create_command_verbose(self):
  2142. files = [support.findfile('tokenize_tests.txt'),
  2143. support.findfile('tokenize_tests-no-coding-cookie-'
  2144. 'and-utf8-bom-sig-only.txt')]
  2145. for opt in '-v', '--verbose':
  2146. try:
  2147. out = self.tarfilecmd(opt, '-c', tmpname, *files,
  2148. PYTHONIOENCODING='utf-8')
  2149. self.assertIn(b' file created.', out)
  2150. with tarfile.open(tmpname) as tar:
  2151. tar.getmembers()
  2152. finally:
  2153. os_helper.unlink(tmpname)
  2154. def test_create_command_dotless_filename(self):
  2155. files = [support.findfile('tokenize_tests.txt')]
  2156. try:
  2157. out = self.tarfilecmd('-c', dotlessname, *files)
  2158. self.assertEqual(out, b'')
  2159. with tarfile.open(dotlessname) as tar:
  2160. tar.getmembers()
  2161. finally:
  2162. os_helper.unlink(dotlessname)
  2163. def test_create_command_dot_started_filename(self):
  2164. tar_name = os.path.join(TEMPDIR, ".testtar")
  2165. files = [support.findfile('tokenize_tests.txt')]
  2166. try:
  2167. out = self.tarfilecmd('-c', tar_name, *files)
  2168. self.assertEqual(out, b'')
  2169. with tarfile.open(tar_name) as tar:
  2170. tar.getmembers()
  2171. finally:
  2172. os_helper.unlink(tar_name)
  2173. def test_create_command_compressed(self):
  2174. files = [support.findfile('tokenize_tests.txt'),
  2175. support.findfile('tokenize_tests-no-coding-cookie-'
  2176. 'and-utf8-bom-sig-only.txt')]
  2177. for filetype in (GzipTest, Bz2Test, LzmaTest):
  2178. if not filetype.open:
  2179. continue
  2180. try:
  2181. tar_name = tmpname + '.' + filetype.suffix
  2182. out = self.tarfilecmd('-c', tar_name, *files)
  2183. with filetype.taropen(tar_name) as tar:
  2184. tar.getmembers()
  2185. finally:
  2186. os_helper.unlink(tar_name)
  2187. def test_extract_command(self):
  2188. self.make_simple_tarfile(tmpname)
  2189. for opt in '-e', '--extract':
  2190. try:
  2191. with os_helper.temp_cwd(tarextdir):
  2192. out = self.tarfilecmd(opt, tmpname)
  2193. self.assertEqual(out, b'')
  2194. finally:
  2195. os_helper.rmtree(tarextdir)
  2196. def test_extract_command_verbose(self):
  2197. self.make_simple_tarfile(tmpname)
  2198. for opt in '-v', '--verbose':
  2199. try:
  2200. with os_helper.temp_cwd(tarextdir):
  2201. out = self.tarfilecmd(opt, '-e', tmpname,
  2202. PYTHONIOENCODING='utf-8')
  2203. self.assertIn(b' file is extracted.', out)
  2204. finally:
  2205. os_helper.rmtree(tarextdir)
  2206. def test_extract_command_different_directory(self):
  2207. self.make_simple_tarfile(tmpname)
  2208. try:
  2209. with os_helper.temp_cwd(tarextdir):
  2210. out = self.tarfilecmd('-e', tmpname, 'spamdir')
  2211. self.assertEqual(out, b'')
  2212. finally:
  2213. os_helper.rmtree(tarextdir)
  2214. def test_extract_command_invalid_file(self):
  2215. zipname = support.findfile('zipdir.zip')
  2216. with os_helper.temp_cwd(tarextdir):
  2217. rc, out, err = self.tarfilecmd_failure('-e', zipname)
  2218. self.assertIn(b' is not a tar archive.', err)
  2219. self.assertEqual(out, b'')
  2220. self.assertEqual(rc, 1)
  2221. class ContextManagerTest(unittest.TestCase):
  2222. def test_basic(self):
  2223. with tarfile.open(tarname) as tar:
  2224. self.assertFalse(tar.closed, "closed inside runtime context")
  2225. self.assertTrue(tar.closed, "context manager failed")
  2226. def test_closed(self):
  2227. # The __enter__() method is supposed to raise OSError
  2228. # if the TarFile object is already closed.
  2229. tar = tarfile.open(tarname)
  2230. tar.close()
  2231. with self.assertRaises(OSError):
  2232. with tar:
  2233. pass
  2234. def test_exception(self):
  2235. # Test if the OSError exception is passed through properly.
  2236. with self.assertRaises(Exception) as exc:
  2237. with tarfile.open(tarname) as tar:
  2238. raise OSError
  2239. self.assertIsInstance(exc.exception, OSError,
  2240. "wrong exception raised in context manager")
  2241. self.assertTrue(tar.closed, "context manager failed")
  2242. def test_no_eof(self):
  2243. # __exit__() must not write end-of-archive blocks if an
  2244. # exception was raised.
  2245. try:
  2246. with tarfile.open(tmpname, "w") as tar:
  2247. raise Exception
  2248. except:
  2249. pass
  2250. self.assertEqual(os.path.getsize(tmpname), 0,
  2251. "context manager wrote an end-of-archive block")
  2252. self.assertTrue(tar.closed, "context manager failed")
  2253. def test_eof(self):
  2254. # __exit__() must write end-of-archive blocks, i.e. call
  2255. # TarFile.close() if there was no error.
  2256. with tarfile.open(tmpname, "w"):
  2257. pass
  2258. self.assertNotEqual(os.path.getsize(tmpname), 0,
  2259. "context manager wrote no end-of-archive block")
  2260. def test_fileobj(self):
  2261. # Test that __exit__() did not close the external file
  2262. # object.
  2263. with open(tmpname, "wb") as fobj:
  2264. try:
  2265. with tarfile.open(fileobj=fobj, mode="w") as tar:
  2266. raise Exception
  2267. except:
  2268. pass
  2269. self.assertFalse(fobj.closed, "external file object was closed")
  2270. self.assertTrue(tar.closed, "context manager failed")
  2271. @unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
  2272. class LinkEmulationTest(ReadTest, unittest.TestCase):
  2273. # Test for issue #8741 regression. On platforms that do not support
  2274. # symbolic or hard links tarfile tries to extract these types of members
  2275. # as the regular files they point to.
  2276. def _test_link_extraction(self, name):
  2277. self.tar.extract(name, TEMPDIR)
  2278. with open(os.path.join(TEMPDIR, name), "rb") as f:
  2279. data = f.read()
  2280. self.assertEqual(sha256sum(data), sha256_regtype)
  2281. # See issues #1578269, #8879, and #17689 for some history on these skips
  2282. @unittest.skipIf(hasattr(os.path, "islink"),
  2283. "Skip emulation - has os.path.islink but not os.link")
  2284. def test_hardlink_extraction1(self):
  2285. self._test_link_extraction("ustar/lnktype")
  2286. @unittest.skipIf(hasattr(os.path, "islink"),
  2287. "Skip emulation - has os.path.islink but not os.link")
  2288. def test_hardlink_extraction2(self):
  2289. self._test_link_extraction("./ustar/linktest2/lnktype")
  2290. @unittest.skipIf(hasattr(os, "symlink"),
  2291. "Skip emulation if symlink exists")
  2292. def test_symlink_extraction1(self):
  2293. self._test_link_extraction("ustar/symtype")
  2294. @unittest.skipIf(hasattr(os, "symlink"),
  2295. "Skip emulation if symlink exists")
  2296. def test_symlink_extraction2(self):
  2297. self._test_link_extraction("./ustar/linktest2/symtype")
  2298. class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
  2299. # Issue5068: The _BZ2Proxy.read() method loops forever
  2300. # on an empty or partial bzipped file.
  2301. def _test_partial_input(self, mode):
  2302. class MyBytesIO(io.BytesIO):
  2303. hit_eof = False
  2304. def read(self, n):
  2305. if self.hit_eof:
  2306. raise AssertionError("infinite loop detected in "
  2307. "tarfile.open()")
  2308. self.hit_eof = self.tell() == len(self.getvalue())
  2309. return super(MyBytesIO, self).read(n)
  2310. def seek(self, *args):
  2311. self.hit_eof = False
  2312. return super(MyBytesIO, self).seek(*args)
  2313. data = bz2.compress(tarfile.TarInfo("foo").tobuf())
  2314. for x in range(len(data) + 1):
  2315. try:
  2316. tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
  2317. except tarfile.ReadError:
  2318. pass # we have no interest in ReadErrors
  2319. def test_partial_input(self):
  2320. self._test_partial_input("r")
  2321. def test_partial_input_bz2(self):
  2322. self._test_partial_input("r:bz2")
  2323. def root_is_uid_gid_0():
  2324. try:
  2325. import pwd, grp
  2326. except ImportError:
  2327. return False
  2328. if pwd.getpwuid(0)[0] != 'root':
  2329. return False
  2330. if grp.getgrgid(0)[0] != 'root':
  2331. return False
  2332. return True
  2333. @unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
  2334. @unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
  2335. class NumericOwnerTest(unittest.TestCase):
  2336. # mock the following:
  2337. # os.chown: so we can test what's being called
  2338. # os.chmod: so the modes are not actually changed. if they are, we can't
  2339. # delete the files/directories
  2340. # os.geteuid: so we can lie and say we're root (uid = 0)
  2341. @staticmethod
  2342. def _make_test_archive(filename_1, dirname_1, filename_2):
  2343. # the file contents to write
  2344. fobj = io.BytesIO(b"content")
  2345. # create a tar file with a file, a directory, and a file within that
  2346. # directory. Assign various .uid/.gid values to them
  2347. items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
  2348. (dirname_1, 77, 76, tarfile.DIRTYPE, None),
  2349. (filename_2, 88, 87, tarfile.REGTYPE, fobj),
  2350. ]
  2351. with tarfile.open(tmpname, 'w') as tarfl:
  2352. for name, uid, gid, typ, contents in items:
  2353. t = tarfile.TarInfo(name)
  2354. t.uid = uid
  2355. t.gid = gid
  2356. t.uname = 'root'
  2357. t.gname = 'root'
  2358. t.type = typ
  2359. tarfl.addfile(t, contents)
  2360. # return the full pathname to the tar file
  2361. return tmpname
  2362. @staticmethod
  2363. @contextmanager
  2364. def _setup_test(mock_geteuid):
  2365. mock_geteuid.return_value = 0 # lie and say we're root
  2366. fname = 'numeric-owner-testfile'
  2367. dirname = 'dir'
  2368. # the names we want stored in the tarfile
  2369. filename_1 = fname
  2370. dirname_1 = dirname
  2371. filename_2 = os.path.join(dirname, fname)
  2372. # create the tarfile with the contents we're after
  2373. tar_filename = NumericOwnerTest._make_test_archive(filename_1,
  2374. dirname_1,
  2375. filename_2)
  2376. # open the tarfile for reading. yield it and the names of the items
  2377. # we stored into the file
  2378. with tarfile.open(tar_filename) as tarfl:
  2379. yield tarfl, filename_1, dirname_1, filename_2
  2380. @unittest.mock.patch('os.chown')
  2381. @unittest.mock.patch('os.chmod')
  2382. @unittest.mock.patch('os.geteuid')
  2383. def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
  2384. mock_chown):
  2385. with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
  2386. filename_2):
  2387. tarfl.extract(filename_1, TEMPDIR, numeric_owner=True)
  2388. tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True)
  2389. # convert to filesystem paths
  2390. f_filename_1 = os.path.join(TEMPDIR, filename_1)
  2391. f_filename_2 = os.path.join(TEMPDIR, filename_2)
  2392. mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
  2393. unittest.mock.call(f_filename_2, 88, 87),
  2394. ],
  2395. any_order=True)
  2396. @unittest.mock.patch('os.chown')
  2397. @unittest.mock.patch('os.chmod')
  2398. @unittest.mock.patch('os.geteuid')
  2399. def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
  2400. mock_chown):
  2401. with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
  2402. filename_2):
  2403. tarfl.extractall(TEMPDIR, numeric_owner=True)
  2404. # convert to filesystem paths
  2405. f_filename_1 = os.path.join(TEMPDIR, filename_1)
  2406. f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
  2407. f_filename_2 = os.path.join(TEMPDIR, filename_2)
  2408. mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
  2409. unittest.mock.call(f_dirname_1, 77, 76),
  2410. unittest.mock.call(f_filename_2, 88, 87),
  2411. ],
  2412. any_order=True)
  2413. # this test requires that uid=0 and gid=0 really be named 'root'. that's
  2414. # because the uname and gname in the test file are 'root', and extract()
  2415. # will look them up using pwd and grp to find their uid and gid, which we
  2416. # test here to be 0.
  2417. @unittest.skipUnless(root_is_uid_gid_0(),
  2418. 'uid=0,gid=0 must be named "root"')
  2419. @unittest.mock.patch('os.chown')
  2420. @unittest.mock.patch('os.chmod')
  2421. @unittest.mock.patch('os.geteuid')
  2422. def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
  2423. mock_chown):
  2424. with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
  2425. tarfl.extract(filename_1, TEMPDIR, numeric_owner=False)
  2426. # convert to filesystem paths
  2427. f_filename_1 = os.path.join(TEMPDIR, filename_1)
  2428. mock_chown.assert_called_with(f_filename_1, 0, 0)
  2429. @unittest.mock.patch('os.geteuid')
  2430. def test_keyword_only(self, mock_geteuid):
  2431. with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
  2432. self.assertRaises(TypeError,
  2433. tarfl.extract, filename_1, TEMPDIR, False, True)
  2434. def setUpModule():
  2435. os_helper.unlink(TEMPDIR)
  2436. os.makedirs(TEMPDIR)
  2437. global testtarnames
  2438. testtarnames = [tarname]
  2439. with open(tarname, "rb") as fobj:
  2440. data = fobj.read()
  2441. # Create compressed tarfiles.
  2442. for c in GzipTest, Bz2Test, LzmaTest:
  2443. if c.open:
  2444. os_helper.unlink(c.tarname)
  2445. testtarnames.append(c.tarname)
  2446. with c.open(c.tarname, "wb") as tar:
  2447. tar.write(data)
  2448. def tearDownModule():
  2449. if os.path.exists(TEMPDIR):
  2450. os_helper.rmtree(TEMPDIR)
  2451. if __name__ == "__main__":
  2452. unittest.main()