Skip to content

Commit 5330eb0

Browse files
fabasoadisaacs
authored andcommitted
fix: consistent TOCTOU behavior in sync t.list
This brings the TOCTOU handling behavior in t.list synchronous behavior to be the same as the async behavior, and other high-level methods. That is, if there is a write to a file after testing its size, then the *smaller* data size will be used, rather than potentially trying to read too much data into memory all at once. PR-URL: #444 Credit: @fabasoad Close: #444 Reviewed-by: @isaacs
1 parent dcb0287 commit 5330eb0

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/list.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,16 +57,18 @@ export const filesFilter = (opt: TarOptions, files: string[]) => {
5757
const listFileSync = (opt: TarOptionsSyncFile) => {
5858
const p = new Parser(opt)
5959
const file = opt.file
60-
let fd
60+
let fd: number | undefined
6161
try {
62-
const stat = fs.statSync(file)
63-
const readSize = opt.maxReadSize || 16 * 1024 * 1024
62+
fd = fs.openSync(file, 'r')
63+
const stat: fs.Stats = fs.fstatSync(fd)
64+
const readSize: number = opt.maxReadSize || 16 * 1024 * 1024
6465
if (stat.size < readSize) {
65-
p.end(fs.readFileSync(file))
66+
const buf = Buffer.allocUnsafe(stat.size)
67+
fs.readSync(fd, buf, 0, stat.size, 0)
68+
p.end(buf)
6669
} else {
6770
let pos = 0
6871
const buf = Buffer.allocUnsafe(readSize)
69-
fd = fs.openSync(file, 'r')
7072
while (pos < stat.size) {
7173
const bytesRead = fs.readSync(fd, buf, 0, readSize, pos)
7274
pos += bytesRead

0 commit comments

Comments
 (0)