dockge/backend/container-file-explorer.ts
Weapie b401bd7472
All checks were successful
Docker image / publish (push) Successful in 1m30s
Update Dockge fork and publish Docker images to Gitea
2026-11-11 17:01:23 +01:00

314 lines
11 KiB
TypeScript

import { execFile } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { posix } from "node:path";
import { promisify } from "node:util";
import { fileChunkBytes, maxContainerFileBytes } from "../common/container-files";
import { containerId, docker } from "./container-management";
import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const transferLimit = 4;
const ttl = 2 * 60 * 1000;
interface Transfer {
owner: string;
id: string;
path: string;
type: "download" | "upload";
data: Buffer;
offset: number;
expected?: string;
busy: boolean;
timer: NodeJS.Timeout;
}
function checkedPath(value: unknown): string {
if (typeof value !== "string" || !value.startsWith("/") || value.includes("\0")
|| Buffer.byteLength(value) > 4096 || posix.normalize(value) !== value || (value !== "/" && value.endsWith("/"))) {
throw new ValidationError("containerFileInvalidPath");
}
return value;
}
// Positional arguments are always data. Reject symbolic-link parents before working on a path.
const shell = `
directory() {
cd -P -- "$1" && [ "$(pwd -P)" = "$1" ]
}
in_parent() {
p=\${1%/*}
directory "\${p:-/}" || exit 24
}
exists() {
[ -e "$1" ] || [ -L "$1" ]
}
`;
const list = `
directory "$1" || exit 24
count=0
for entry in ./* ./.[!.]* ./..?*; do
exists "$entry" || continue
count=$((count + 1))
[ "$count" -le 3000 ] || exit 25
kind=other
if [ -L "$entry" ]; then kind=link
elif [ -d "$entry" ]; then kind=directory
elif [ -f "$entry" ]; then kind=file
fi
metadata=$(stat -c '%s %Y' -- "$entry") || exit 24
printf '%s\\0%s\\0%s\\0' "\${entry#./}" "$kind" "$metadata"
done
`;
const read = `
in_parent "$1"
name=./\${1##*/}
[ ! -L "$name" ] || exit 24
if [ -d "$name" ]; then
tar -cf - -- "$name"
else
[ -f "$name" ] || exit 24
head -c "$2" -- "$name"
fi
`;
const write = `
in_parent "$1"
name=./\${1##*/}
if [ -n "$2" ]; then
[ -f "$name" ] && [ ! -L "$name" ] || exit 23
sum=$(sha256sum < "$name") || exit 24
[ "\${sum%% *}" = "$2" ] || exit 23
mode=$(stat -c '%a' -- "$name") || exit 24
owner=$(stat -c '%u:%g' -- "$name") || exit 24
else
if exists "$name"; then exit 23; fi
fi
temp=$(mktemp ./.dockge.XXXXXX) || exit 24
trap 'rm -f -- "$temp"' EXIT
cat > "$temp" || exit 24
[ "$(stat -c '%s' -- "$temp")" = "$3" ] || exit 24
if [ -n "$2" ]; then
if [ "$(stat -c '%u:%g' -- "$temp")" != "$owner" ]; then
chown -- "$owner" "$temp" || exit 24
fi
chmod -- "$mode" "$temp" || exit 24
[ -f "$name" ] && [ ! -L "$name" ] || exit 23
sum=$(sha256sum < "$name") || exit 24
[ "\${sum%% *}" = "$2" ] || exit 23
mv -fT -- "$temp" "$name" || exit 24
else
mv -nT -- "$temp" "$name" || exit 24
[ ! -e "$temp" ] || exit 23
fi
`;
const change = `
case "$1" in
mkdir)
in_parent "$2"
mkdir -- "./\${2##*/}" || exit 24
;;
delete)
in_parent "$2"
rm -r -- "./\${2##*/}" || exit 24
;;
move|copy)
in_parent "$2"
in_parent "$3"
if exists "./\${3##*/}"; then exit 23; fi
if [ "$1" = move ]; then
mv -nT -- "$2" "./\${3##*/}" && ! exists "$2" || exit 23
else
staging=$(mktemp -d ./.dockge.XXXXXX) || exit 24
trap 'rm -rf -- "$staging"' EXIT
cp -a -- "$2" "$staging/item" || exit 24
mv -nT -- "$staging/item" "./\${3##*/}" || exit 24
! exists "$staging/item" || exit 23
fi
;;
esac
`;
export class ContainerFileExplorer {
private readonly transfers = new Map<string, Transfer>();
disconnect(owner: string) {
for (const [ token, transfer ] of this.transfers) {
if (transfer.owner === owner) {
this.release(token);
}
}
}
async request(owner: string, request: unknown): Promise<object> {
if (!request || typeof request !== "object") {
throw new ValidationError("containerFileInvalidRequest");
}
const args = request as Record<string, unknown>;
const action = args.action;
if (action === "chunk" || action === "finish" || action === "cancel") {
return this.transferRequest(owner, action, args);
}
const id = containerId(args.id);
const path = checkedPath(args.path);
await this.requireRunning(id);
if (action === "list") {
const { stdout } = await docker([ "container", "inspect", "--format", "{{.Name}}", "--", id ]);
const fields = (await this.run(id, list, [ path ])).toString("utf8").split("\0");
const entries = [];
for (let i = 0; i + 2 < fields.length; i += 3) {
const [ size, modified ] = fields[i + 2].split(" ").map(Number);
entries.push({ name: fields[i],
type: fields[i + 1],
size,
modified });
}
return { entries,
name: stdout.trim().replace(/^\//, "") };
}
if (path === "/") {
throw new ValidationError("containerFileInvalidPath");
}
if (action === "download" || action === "upload") {
return this.openTransfer(owner, id, path, action, args);
}
if (action === "mkdir" || action === "delete" || action === "move" || action === "copy") {
const target = action === "move" || action === "copy" ? checkedPath(args.target) : "";
if (target && (target === "/" || target === path || target.startsWith(path + "/") || path.startsWith(target + "/"))) {
throw new ValidationError("containerFileInvalidPath");
}
await this.run(id, change, [ action, path, target ]);
return {};
}
throw new ValidationError("containerFileInvalidRequest");
}
private async requireRunning(id: string) {
const { stdout } = await docker([ "container", "inspect", "--format", "{{.State.Running}} {{.State.Paused}}", "--", id ]);
if (stdout.trim() !== "true false") {
throw new ValidationError("containerFileNotRunning");
}
}
private async run(id: string, script: string, args: string[], input?: Buffer) {
const pending = exec("docker", [
"container", "exec", ...(input ? [ "-i" ] : []), id, "sh", "-c", shell + script, "dockge-files", ...args,
], {
encoding: "buffer",
timeout: 30000,
maxBuffer: maxContainerFileBytes + 1024,
windowsHide: true,
});
if (input) {
pending.child.stdin?.on("error", () => {});
pending.child.stdin?.end(input);
}
try {
return (await pending).stdout;
} catch (error) {
const code = (error as { code?: string | number }).code;
const messages: Record<string, string> = {
"23": "containerFileConflict",
"25": "containerFileTooManyEntries",
"126": "containerFileToolsUnavailable",
"127": "containerFileToolsUnavailable",
ERR_CHILD_PROCESS_STDIO_MAXBUFFER: "containerFileTooLarge",
};
throw new ValidationError(messages[String(code)] || "containerFileFailed");
}
}
private release(token: string) {
const transfer = this.transfers.get(token);
if (transfer) {
clearTimeout(transfer.timer);
this.transfers.delete(token);
}
}
private async openTransfer(owner: string, id: string, path: string, type: Transfer["type"], args: Record<string, unknown>) {
if (this.transfers.size >= transferLimit || Array.from(this.transfers.values()).some(value => value.owner === owner)) {
throw new ValidationError("containerFileTransferBusy");
}
const size = args.size;
const expected = args.expected;
if (type === "upload" && (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0 || size > maxContainerFileBytes
|| (expected !== undefined && (typeof expected !== "string" || !/^[0-9a-f]{64}$/.test(expected))))) {
throw new ValidationError("containerFileInvalidRequest");
}
const token = randomUUID();
const transfer: Transfer = {
owner,
id,
path,
type,
expected: typeof expected === "string" ? expected : undefined,
data: Buffer.alloc(type === "upload" ? Number(size) : 0),
offset: 0,
busy: true,
timer: setTimeout(() => this.release(token), ttl).unref(),
};
this.transfers.set(token, transfer);
try {
if (type === "download") {
transfer.data = await this.run(id, read, [ path, String(maxContainerFileBytes + 1) ]);
if (transfer.data.length > maxContainerFileBytes) {
throw new ValidationError("containerFileTooLarge");
}
}
transfer.busy = false;
return {
token,
size: transfer.data.length,
revision: type === "download" ? createHash("sha256").update(transfer.data).digest("hex") : undefined,
};
} catch (error) {
this.release(token);
throw error;
}
}
private async transferRequest(owner: string, action: string, args: Record<string, unknown>) {
const token = args.token;
const transfer = typeof token === "string" && this.transfers.get(token);
if (!transfer || transfer.owner !== owner || transfer.busy || typeof token !== "string") {
throw new ValidationError("containerFileTransferExpired");
}
transfer.timer.refresh();
if (action === "cancel") {
this.release(token);
return {};
}
if (action === "finish") {
if (transfer.type !== "upload" || transfer.offset !== transfer.data.length) {
throw new ValidationError("containerFileInvalidRequest");
}
transfer.busy = true;
try {
await this.requireRunning(transfer.id);
await this.run(transfer.id, write, [ transfer.path, transfer.expected || "", String(transfer.data.length) ], transfer.data);
return {};
} finally {
this.release(token);
}
}
if (args.offset !== transfer.offset || transfer.offset >= transfer.data.length) {
throw new ValidationError("containerFileInvalidRequest");
}
const end = Math.min(transfer.offset + fileChunkBytes, transfer.data.length);
if (transfer.type === "download") {
const data = transfer.data.subarray(transfer.offset, end);
transfer.offset = end;
if (end === transfer.data.length) {
this.release(token);
}
return { data };
}
if (!Buffer.isBuffer(args.data) || args.data.length !== end - transfer.offset) {
throw new ValidationError("containerFileInvalidRequest");
}
args.data.copy(transfer.data, transfer.offset);
transfer.offset = end;
return {};
}
}