Skip to content

tarfile: Appending nothing to a TAR with PAX global headers corrupts it #149674

@spbnick

Description

@spbnick

Bug report

Bug description:

It appears that opening a TAR file with tarfile in append mode corrupts it, if it was created with global PAX headers. This works without PAX headers.

Might be related to #149578

Reproducer

import traceback
import tarfile
import sys
import io

for case, kwargs in dict(
    without_pax_headers=dict(
        mode='w'
    ),
    with_pax_headers=dict(
        mode='w', pax_headers=dict(abc="def")
    ),
).items():
    filename = case + ".tar"
    print(case, end=" ", file=sys.stderr)
    try:
        with tarfile.TarFile(filename, **kwargs) as tar:
            contents = b"contents"
            tarinfo = tarfile.TarInfo("file")
            tarinfo.size = len(contents)
            tar.addfile(tarinfo, io.BytesIO(contents))
        with tarfile.TarFile(filename, mode='a'):
            pass
        with tarfile.TarFile(filename, mode='a'):
            pass
        print("PASS", file=sys.stderr)
    except Exception:
        print("FAIL", file=sys.stderr)
        print(traceback.format_exc(), file=sys.stderr)

The output I get from this is:

without_pax_headers PASS
with_pax_headers FAIL
Traceback (most recent call last):
  File "<python-input-0>", line 24, in <module>
    with tarfile.TarFile(filename, mode='a'):
         ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.15/tarfile.py", line 1834, in __init__
    raise ReadError(str(e)) from None
tarfile.ReadError: end of file header

CPython versions tested on:

3.15

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions