Skip to content

bpo-40049: Check if symlink exists when extracting from tarfile #19187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Lib/tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -2232,6 +2232,8 @@ def makelink(self, tarinfo, targetpath):
try:
# For systems that support symbolic and hard links.
if tarinfo.issym():
if os.path.lexists(targetpath):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps include a short comment here explaining why this is needed? Something along the lines of "tar should overwrite existing files with symlinks, but os.symlink raises an exception rather than overwriting."

os.unlink(targetpath)
os.symlink(tarinfo.linkname, targetpath)
else:
# See extract().
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,18 @@ def test_compare_members(self):
finally:
tar1.close()

@support.skip_unless_symlink
def test_symlink_overwrite(self):
# Test for issue #40049: Extracting a symlink over an existing file
# in stream mode causes a backwards seek
sympath = os.path.join(TEMPDIR, 'symtype2')
pathlib.Path(sympath).touch()
try:
self.tar.extract('symtype2', TEMPDIR)
self.assertTrue(os.path.islink(sympath))
finally:
pathlib.Path(sympath).unlink(missing_ok=True)

class GzipStreamReadTest(GzipTest, StreamReadTest):
pass

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The :mod:`tarfile` module now checks for an existing symlink before creating a
new one during extraction. This prevents premature scanning of the
archive and errors when extracting from a stream.