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
分支
36k
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 摘要。