-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathregular-file.ts
More file actions
366 lines (342 loc) · 11 KB
/
Copy pathregular-file.ts
File metadata and controls
366 lines (342 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import type { Stats } from "node:fs";
import fsSync from "node:fs";
import type { FileHandle } from "node:fs/promises";
import fs from "node:fs/promises";
import path from "node:path";
import { sameFileIdentity } from "./file-identity.js";
import { isNotFoundPathError } from "./path.js";
import { assertNoSymlinkParents, assertNoSymlinkParentsSync } from "./symlink-parents.js";
export type RegularFileStatResult = { missing: true } | { missing: false; stat: Stats };
type RegularFileAppendFlagConstants = Pick<
typeof fsSync.constants,
"O_APPEND" | "O_CREAT" | "O_WRONLY"
> &
Partial<Pick<typeof fsSync.constants, "O_NOFOLLOW">>;
export type AppendRegularFileOptions = {
filePath: string;
content: string | Uint8Array;
encoding?: BufferEncoding;
maxFileBytes?: number;
mode?: number;
rejectSymlinkParents?: boolean;
};
export function resolveRegularFileAppendFlags(
constants: RegularFileAppendFlagConstants = fsSync.constants,
): number {
const noFollow = constants.O_NOFOLLOW;
return (
constants.O_CREAT |
constants.O_APPEND |
constants.O_WRONLY |
(typeof noFollow === "number" ? noFollow : 0)
);
}
function resolveRegularFileReadFlags(): number {
return (
fsSync.constants.O_RDONLY |
(typeof fsSync.constants.O_NOFOLLOW === "number" && process.platform !== "win32"
? fsSync.constants.O_NOFOLLOW
: 0)
);
}
async function readFileHandleBounded(params: {
handle: FileHandle;
filePath: string;
maxBytes?: number;
}): Promise<Buffer> {
if (params.maxBytes === undefined) {
return await params.handle.readFile();
}
const chunks: Buffer[] = [];
const scratch = Buffer.allocUnsafe(Math.min(64 * 1024, Math.max(1, params.maxBytes + 1)));
let total = 0;
while (true) {
const { bytesRead } = await params.handle.read(scratch, 0, scratch.length, null);
if (bytesRead === 0) {
return Buffer.concat(chunks, total);
}
total += bytesRead;
if (total > params.maxBytes) {
throw new Error(`File exceeds ${params.maxBytes} bytes: ${params.filePath}`);
}
chunks.push(Buffer.from(scratch.subarray(0, bytesRead)));
}
}
function readFileDescriptorBounded(params: {
fd: number;
filePath: string;
maxBytes?: number;
}): Buffer {
if (params.maxBytes === undefined) {
return fsSync.readFileSync(params.fd);
}
const chunks: Buffer[] = [];
const scratch = Buffer.allocUnsafe(Math.min(64 * 1024, Math.max(1, params.maxBytes + 1)));
let total = 0;
while (true) {
const bytesRead = fsSync.readSync(params.fd, scratch, 0, scratch.length, null);
if (bytesRead === 0) {
return Buffer.concat(chunks, total);
}
total += bytesRead;
if (total > params.maxBytes) {
throw new Error(`File exceeds ${params.maxBytes} bytes: ${params.filePath}`);
}
chunks.push(Buffer.from(scratch.subarray(0, bytesRead)));
}
}
export async function statRegularFile(filePath: string): Promise<RegularFileStatResult> {
let stat: Stats;
try {
stat = await fs.lstat(filePath);
} catch (err) {
if (isNotFoundPathError(err)) {
return { missing: true };
}
throw err;
}
if (stat.isSymbolicLink() || !stat.isFile()) {
throw new Error("path must be a regular file");
}
return { missing: false, stat };
}
export function statRegularFileSync(filePath: string): RegularFileStatResult {
let stat: Stats;
try {
stat = fsSync.lstatSync(filePath);
} catch (err) {
if (isNotFoundPathError(err)) {
return { missing: true };
}
throw err;
}
if (stat.isSymbolicLink() || !stat.isFile()) {
throw new Error("path must be a regular file");
}
return { missing: false, stat };
}
export async function readRegularFile(params: {
filePath: string;
maxBytes?: number;
}): Promise<{ buffer: Buffer; stat: Stats }> {
const result = await statRegularFile(params.filePath);
if (result.missing) {
throw Object.assign(new Error(`File not found: ${params.filePath}`), { code: "ENOENT" });
}
if (params.maxBytes !== undefined && result.stat.size > params.maxBytes) {
throw new Error(`File exceeds ${params.maxBytes} bytes: ${params.filePath}`);
}
const handle = await fs.open(params.filePath, resolveRegularFileReadFlags());
try {
const stat = await handle.stat();
verifyStableReadTarget({
filePath: params.filePath,
pathStat: await fs.lstat(params.filePath),
postOpenStat: stat,
preOpenStat: result.stat,
});
if (params.maxBytes !== undefined && stat.size > params.maxBytes) {
throw new Error(`File exceeds ${params.maxBytes} bytes: ${params.filePath}`);
}
// With a byte cap, avoid readFile(): a raced file growth would allocate
// the oversized content before the post-read check could reject it.
const buffer = await readFileHandleBounded({
handle,
filePath: params.filePath,
maxBytes: params.maxBytes,
});
return { buffer, stat };
} finally {
await handle.close();
}
}
function verifyStableReadTarget(params: {
preOpenStat: Stats;
postOpenStat: Stats;
pathStat: Stats;
filePath: string;
}): void {
if (!params.postOpenStat.isFile() || params.pathStat.isSymbolicLink() || !params.pathStat.isFile()) {
throw new Error(`File is not a regular file: ${params.filePath}`);
}
if (
!sameFileIdentity(params.preOpenStat, params.postOpenStat) ||
!sameFileIdentity(params.pathStat, params.postOpenStat)
) {
throw new Error(`File changed during read: ${params.filePath}`);
}
}
function readOpenedRegularFileSync(params: {
fd: number;
filePath: string;
preOpenStat: Stats;
maxBytes?: number;
}): { buffer: Buffer; stat: Stats } {
const stat = fsSync.fstatSync(params.fd);
verifyStableReadTarget({
filePath: params.filePath,
pathStat: fsSync.lstatSync(params.filePath),
postOpenStat: stat,
preOpenStat: params.preOpenStat,
});
if (params.maxBytes !== undefined && stat.size > params.maxBytes) {
throw new Error(`File exceeds ${params.maxBytes} bytes: ${params.filePath}`);
}
// Keep capped sync reads incremental for the same reason as async reads:
// readFileSync(fd) would buffer a raced oversized file before throwing.
const buffer = readFileDescriptorBounded({
fd: params.fd,
filePath: params.filePath,
maxBytes: params.maxBytes,
});
return { buffer, stat };
}
export function readRegularFileSync(params: { filePath: string; maxBytes?: number }): {
buffer: Buffer;
stat: Stats;
} {
const result = statRegularFileSync(params.filePath);
if (result.missing) {
throw Object.assign(new Error(`File not found: ${params.filePath}`), { code: "ENOENT" });
}
if (params.maxBytes !== undefined && result.stat.size > params.maxBytes) {
throw new Error(`File exceeds ${params.maxBytes} bytes: ${params.filePath}`);
}
const fd = fsSync.openSync(params.filePath, resolveRegularFileReadFlags());
try {
return readOpenedRegularFileSync({
fd,
filePath: params.filePath,
preOpenStat: result.stat,
maxBytes: params.maxBytes,
});
} finally {
fsSync.closeSync(fd);
}
}
function verifyStableAppendTarget(params: {
preOpenStat?: Stats;
postOpenStat: Stats;
filePath: string;
}): void {
if (!params.postOpenStat.isFile()) {
throw new Error(`Refusing to append to non-file: ${params.filePath}`);
}
if (params.postOpenStat.nlink > 1) {
throw new Error(`Refusing to append to hardlinked file: ${params.filePath}`);
}
const pre = params.preOpenStat;
if (pre && (pre.dev !== params.postOpenStat.dev || pre.ino !== params.postOpenStat.ino)) {
throw new Error(`Refusing to append after file changed: ${params.filePath}`);
}
}
export async function appendRegularFile(options: AppendRegularFileOptions): Promise<void> {
if (options.rejectSymlinkParents === true) {
const resolvedDir = path.resolve(path.dirname(options.filePath));
await assertNoSymlinkParents({
rootDir: path.parse(resolvedDir).root,
targetPath: resolvedDir,
allowMissing: false,
allowRootChildSymlink: true,
requireDirectories: true,
messagePrefix: "Refusing to append under",
});
}
let preOpenStat: Stats | undefined;
try {
const stat = await fs.lstat(options.filePath);
if (stat.isSymbolicLink()) {
throw new Error(`Refusing to append through symlink: ${options.filePath}`);
}
if (!stat.isFile()) {
throw new Error(`Refusing to append to non-file: ${options.filePath}`);
}
preOpenStat = stat;
} catch (err) {
if (!isNotFoundPathError(err)) {
throw err;
}
}
const contentBytes = Buffer.isBuffer(options.content)
? options.content.byteLength
: Buffer.byteLength(options.content, options.encoding ?? "utf8");
if (
options.maxFileBytes !== undefined &&
(preOpenStat?.size ?? 0) + contentBytes > options.maxFileBytes
) {
return;
}
const handle = await fs.open(
options.filePath,
resolveRegularFileAppendFlags(),
options.mode ?? 0o600,
);
try {
const stat = await handle.stat();
verifyStableAppendTarget({ preOpenStat, postOpenStat: stat, filePath: options.filePath });
if (options.maxFileBytes !== undefined && stat.size + contentBytes > options.maxFileBytes) {
return;
}
await handle.chmod(options.mode ?? 0o600);
await handle.appendFile(options.content, options.encoding ?? "utf8");
} finally {
await handle.close();
}
}
export function appendRegularFileSync(options: AppendRegularFileOptions): void {
if (options.rejectSymlinkParents === true) {
const resolvedDir = path.resolve(path.dirname(options.filePath));
assertNoSymlinkParentsSync({
rootDir: path.parse(resolvedDir).root,
targetPath: resolvedDir,
allowMissing: false,
allowRootChildSymlink: true,
requireDirectories: true,
messagePrefix: "Refusing to append under",
});
}
let preOpenStat: Stats | undefined;
try {
const stat = fsSync.lstatSync(options.filePath);
if (stat.isSymbolicLink()) {
throw new Error(`Refusing to append through symlink: ${options.filePath}`);
}
if (!stat.isFile()) {
throw new Error(`Refusing to append to non-file: ${options.filePath}`);
}
preOpenStat = stat;
} catch (err) {
if (!isNotFoundPathError(err)) {
throw err;
}
}
const contentBuffer =
typeof options.content === "string"
? Buffer.from(options.content, options.encoding ?? "utf8")
: Buffer.from(options.content);
if (
options.maxFileBytes !== undefined &&
(preOpenStat?.size ?? 0) + contentBuffer.byteLength > options.maxFileBytes
) {
return;
}
const fd = fsSync.openSync(
options.filePath,
resolveRegularFileAppendFlags(),
options.mode ?? 0o600,
);
try {
const stat = fsSync.fstatSync(fd);
verifyStableAppendTarget({ preOpenStat, postOpenStat: stat, filePath: options.filePath });
if (
options.maxFileBytes !== undefined &&
stat.size + contentBuffer.byteLength > options.maxFileBytes
) {
return;
}
fsSync.fchmodSync(fd, options.mode ?? 0o600);
fsSync.writeSync(fd, contentBuffer, 0, contentBuffer.byteLength);
} finally {
fsSync.closeSync(fd);
}
}