file_put_contents() is racy
还没有人认领这个 Issue。
- 主要语言
- C
- 星标
- 40.4k
- 派生
- 8.2k
- 平均合并
- 2 天 13 小时
- 30 天内合并 PR
- 96
描述
Imagine following sequence (two processes A and B writing some serialized data to file called "cache.dat" using file_put_contents():
- Process A: open the cache file for writing
- Process B: open the same cache file for writing
- Process A: truncate the file to zero length
- Process B: truncate the file to zero length
- Process A: write the cached data (e.g. 1002 byte long serialized data)
- Process B: write the cached data (e.g. 1000 byte long serialized data)
- Process A: close the file
- Procees B: close the file
This results in a file with 1000 bytes from Process B and 2 extra bytes from process A and you end up with unserialize(): Extra data starting at offset 1000 of 1002 bytes if you later try to unserialize the file.
Since it seems that many developers incorrectly believe that a function called file_put_contents() would actually write a file with the given contents, I'm suggesting that PHP internal implementation should instead be (unless FILE_APPEND or LOCK_EX in flags)
- Create a new temporary file in the same directory with the target filename.
- Write the given data (argument to file_put_contents()) into said file.
- Close the file
- Rename the temporary file to final target filename.
Since only the rename() is guaranteed to be atomic in POSIX compatible systems (and even that requires rename within the same directory), this is the only way to make sure you don't end up with mixture of two files when multiple processes are calling file_put_contents() at nearly the same time. And in case NFS is used, you cannot assume that LOCK_EX actually works so you must use rename() semantics.
And maybe allow current behavior with some new flag (FILE_ALLOW_RACY?) with documentation "Reduce syscalls to improve performance but caller must guarantee that two processes are not trying to write into the same file concurrently."
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 ext/standard/file.c 第 492 行附近开始,跟踪 file_put_contents() 对普通写入、FILE_APPEND 和 LOCK_EX 的处理。检查所提议的同目录临时文件和重命名流程,然后确定并发写入所需的行为和覆盖范围,包括任何 FILE_ALLOW_RACY 替代方案及文档。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, php
- 领域
- operating-systems
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100