python / python/cpython

`ZipFile.mkdir()` corrupts archives during an active write

未关闭
#156,078 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Bug description:
Summary

ZipFile.mkdir() does not reject calls made while another writable member handle returned by ZipFile.open(..., mode="w") is active. On seekable output,mkdir() seeks back to the current central-directory start and writes a new local header there. This overwrites or aliases the active member's local header and can produce a corrupt ZIP archive without raising an exception.

Minimal Reproducer
import io
import zipfile

buffer = io.BytesIO()
zf = zipfile.ZipFile(buffer, "w")

member = zf.open("file.txt", mode="w")
zf.mkdir("directory")       # Should reject this operation
member.write(b"payload")
member.close()
zf.close()

with zipfile.ZipFile(io.BytesIO(buffer.getvalue())) as broken:
    print(broken.namelist())
    print(broken.read("directory/"))
Observed behavior:
['directory/', 'file.txt']
Traceback (most recent call last):
  File "/home/ubuntu/cpython-main/test.py", line 15, in <module>
    print(broken.read("directory/"))
          ~~~~~~~~~~~^^^^^^^^^^^^^^
  File "/home/ubuntu/cpython-main/Lib/zipfile/__init__.py", line 2165, in read
    with self.open(name, "r", pwd) as fp:
         ~~~~~~~~~^^^^^^^^^^^^^^^^
  File "/home/ubuntu/cpython-main/Lib/zipfile/__init__.py", line 2239, in open
    raise BadZipFile(
        'File name in directory %r and header %r differ.'
        % (zinfo.orig_filename, fname))
zipfile.BadZipFile: File name in directory 'directory/' and header b'file.txt' differ.

The exact error may vary with the archive contents, but the resulting archive is structurally inconsistent.

Expected Behavior

mkdir() should reject the operation before changing the archive, consistent with the existing behavior of open(..., mode="w"), write(), writestr(), and close() when a writable member handle is active. A ValueError with a message explaining that another write handle is open would be appropriate.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-156079

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Lib/zipfile/init.py 中的 ZipFile.mkdir 开始,将其对活动可写成员句柄的处理与 open(..., mode="w")、write()、writestr() 和 close() 进行比较。运行最小复现程序;完成标准是 mkdir 在更改归档文件之前以 ValueError 拒绝该操作。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
30/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。