// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Pathnames: the virtual name space a server presents, and the one place the //! protocol quotes a pathname rather than sending it bare. //! //! RFC 959 has nothing to say about what a pathname looks like — it is //! "a character string identifying a file", and a TOPS-20 server was free to //! answer in TOPS-20 syntax. RFC 3659 §2.2 finally wrote down what everybody //! had converged on: a tree with `/` between the components, `/` at the root, //! and no way to name a file above it. That is what `resolve` implements, and //! it is a security boundary as much as a convenience — a server that joins a //! client's string onto a root directory without normalising it first serves //! `/etc/shadow` to anyone who asks for `../../../etc/shadow`. const std = @import("std"); const Io = std.Io; /// The longest path this library will build. Longer than any real file system /// allows, and short enough that a resolution buffer can live on the stack. pub const max_len = 4096; /// The root of the virtual name space, and the working directory a session /// starts in. pub const root = "/"; pub const ResolveError = error{ /// The resolved path would be longer than `max_len`. PathTooLong, /// The path holds a NUL, which no file system can name and which would /// truncate the path if it reached a C API. InvalidPath, }; /// Resolves `arg` against `cwd`, writing the result into `buffer` and /// returning the part of it that was used. /// /// The result is always absolute, always normalised, and always inside the /// root: `.` and empty components are dropped, `..` removes the component /// before it, and a `..` at the root is a no-op rather than an escape. This is /// what a chroot does, and doing it lexically here rather than trusting the /// file system to do it means a backend that is not a file system at all gets /// the same containment for free. /// /// `arg` is taken relative to `cwd` unless it begins with `/`. `cwd` must /// itself be absolute — the output of an earlier `resolve` is the intended /// source of it. /// /// Symbolic links are not followed, because they cannot be: this is a /// syntactic operation on a name, and whether the name reaches a link is the /// backend's business. A backend that follows links must contain them itself. pub fn resolve(buffer: []u8, cwd: []const u8, arg: []const u8) ResolveError![]u8 { if (buffer.len == 0) return error.PathTooLong; if (std.mem.findScalar(u8, arg, 0) != null) return error.InvalidPath; var len: usize = 0; // `len` counts the bytes written; the path is stored without a trailing // slash, so the root is the empty string until it is written out at the // end. That makes "push" and "pop" trivial and needs no component stack. if (!std.mem.startsWith(u8, arg, "/")) { std.debug.assert(std.mem.startsWith(u8, cwd, "/")); const trimmed = std.mem.trimEnd(u8, cwd, "/"); if (trimmed.len > buffer.len) return error.PathTooLong; @memcpy(buffer[0..trimmed.len], trimmed); len = trimmed.len; } var components = std.mem.splitScalar(u8, arg, '/'); while (components.next()) |component| { if (component.len == 0 or std.mem.eql(u8, component, ".")) continue; if (std.mem.eql(u8, component, "..")) { len = std.mem.findScalarLast(u8, buffer[0..len], '/') orelse 0; continue; } if (len + 1 + component.len > buffer.len) return error.PathTooLong; if (len + 1 + component.len > max_len) return error.PathTooLong; buffer[len] = '/'; @memcpy(buffer[len + 1 ..][0..component.len], component); len += 1 + component.len; } if (len == 0) { if (buffer.len < root.len) return error.PathTooLong; @memcpy(buffer[0..root.len], root); return buffer[0..root.len]; } return buffer[0..len]; } /// The last component of a resolved path, or the empty string for the root. pub fn basename(resolved: []const u8) []const u8 { const slash = std.mem.findScalarLast(u8, resolved, '/') orelse return resolved; return resolved[slash + 1 ..]; } /// The path holding `resolved`, or the root when `resolved` is a child of it. pub fn parent(resolved: []const u8) []const u8 { const slash = std.mem.findScalarLast(u8, resolved, '/') orelse return root; return if (slash == 0) root else resolved[0..slash]; } /// Whether `resolved` is the root itself. pub fn isRoot(resolved: []const u8) bool { return std.mem.eql(u8, resolved, root); } /// Writes a pathname as a 257 reply carries it: inside double quotes, with any /// double quote in the name written twice. /// /// RFC 959 §5.3.2 asks for this in the reply to `MKD` and `PWD`, and only /// there. Everywhere else a pathname is sent bare, which is why a name with a /// space in it is unambiguous in `RETR` — the argument runs to the end of the /// line — and would not be here, where a reply may say more after the name. pub fn writeQuoted(w: *Io.Writer, name: []const u8) Io.Writer.Error!void { try w.writeByte('"'); var rest = name; while (std.mem.findScalar(u8, rest, '"')) |i| { try w.writeAll(rest[0 .. i + 1]); try w.writeByte('"'); rest = rest[i + 1 ..]; } try w.writeAll(rest); try w.writeByte('"'); } /// Formats a pathname for `{f}` as a 257 reply carries it. See `writeQuoted`. pub fn quoted(name: []const u8) Quoted { return .{ .name = name }; } pub const Quoted = struct { name: []const u8, pub fn format(q: Quoted, w: *Io.Writer) Io.Writer.Error!void { return writeQuoted(w, q.name); } }; pub const UnquoteError = error{ /// The text did not begin with a quoted pathname. NoQuotedName, /// The name did not fit in the buffer given. PathTooLong, }; /// Reads the quoted pathname at the front of a 257 reply into `buffer`. /// /// Everything after the closing quote is the server's commentary and is /// ignored. A reply with no quotes at all is an error rather than a guess: /// `PWD` is how a client learns where it is, and a client that mistakes /// `257 "/pub" is current directory` for the path `/pub" is current directory` /// will spend the rest of the session addressing files that do not exist. pub fn unquote(buffer: []u8, text: []const u8) UnquoteError![]u8 { if (text.len == 0 or text[0] != '"') return error.NoQuotedName; var len: usize = 0; var i: usize = 1; while (i < text.len) { if (text[i] == '"') { // A doubled quote is one quote in the name; a single one ends it. if (i + 1 < text.len and text[i + 1] == '"') { i += 2; } else { return buffer[0..len]; } } else { i += 1; } if (len == buffer.len) return error.PathTooLong; buffer[len] = text[i - 1]; len += 1; } return error.NoQuotedName; } // -- tests ---------------------------------------------------------------- const testing = std.testing; fn expectResolve(cwd: []const u8, arg: []const u8, expected: []const u8) !void { var buffer: [max_len]u8 = undefined; try testing.expectEqualStrings(expected, try resolve(&buffer, cwd, arg)); } test "absolute arguments ignore the working directory" { try expectResolve("/pub/files", "/etc", "/etc"); try expectResolve("/pub/files", "/", "/"); } test "relative arguments join onto it" { try expectResolve("/pub", "files", "/pub/files"); try expectResolve("/", "pub", "/pub"); try expectResolve("/pub/files", "", "/pub/files"); } test "dot and empty components are dropped" { try expectResolve("/", "/pub/./files", "/pub/files"); try expectResolve("/", "/pub//files///", "/pub/files"); try expectResolve("/pub", ".", "/pub"); } test "dot dot goes up one" { try expectResolve("/pub/files", "..", "/pub"); try expectResolve("/pub/files", "../..", "/"); try expectResolve("/", "/pub/files/../other", "/pub/other"); } test "dot dot cannot climb above the root" { // The whole point of resolving lexically: none of these may name anything // outside the tree the server is serving. try expectResolve("/", "..", "/"); try expectResolve("/", "../../..", "/"); try expectResolve("/", "../../../etc/shadow", "/etc/shadow"); try expectResolve("/pub", "../../../../etc/shadow", "/etc/shadow"); try expectResolve("/", "/..", "/"); } test "a NUL is not a pathname" { var buffer: [max_len]u8 = undefined; try testing.expectError(error.InvalidPath, resolve(&buffer, "/", "pub\x00/etc")); } test "a path longer than the buffer is refused" { var buffer: [16]u8 = undefined; try testing.expectError(error.PathTooLong, resolve(&buffer, "/", "a-name-far-too-long-for-this")); } test "basename and parent" { try testing.expectEqualStrings("files", basename("/pub/files")); try testing.expectEqualStrings("pub", basename("/pub")); try testing.expectEqualStrings("", basename("/")); try testing.expectEqualStrings("/pub", parent("/pub/files")); try testing.expectEqualStrings("/", parent("/pub")); try testing.expectEqualStrings("/", parent("/")); try testing.expect(isRoot("/")); try testing.expect(!isRoot("/pub")); } fn expectQuoted(name: []const u8, expected: []const u8) !void { var buffer: [128]u8 = undefined; const written = try std.fmt.bufPrint(&buffer, "{f}", .{quoted(name)}); try testing.expectEqualStrings(expected, written); var back: [128]u8 = undefined; try testing.expectEqualStrings(name, try unquote(&back, written)); } test "quoting a pathname" { try expectQuoted("/pub", "\"/pub\""); try expectQuoted("/", "\"/\""); try expectQuoted("", "\"\""); try expectQuoted("with space", "\"with space\""); try expectQuoted("with\"quote", "\"with\"\"quote\""); try expectQuoted("\"", "\"\"\"\""); try expectQuoted("\"\"", "\"\"\"\"\"\""); } test "unquoting ignores what the server says after the name" { var buffer: [128]u8 = undefined; try testing.expectEqualStrings( "/pub", try unquote(&buffer, "\"/pub\" is the current directory"), ); } test "a 257 reply with no quoted name is an error, not a guess" { var buffer: [128]u8 = undefined; try testing.expectError(error.NoQuotedName, unquote(&buffer, "/pub")); try testing.expectError(error.NoQuotedName, unquote(&buffer, "")); try testing.expectError(error.NoQuotedName, unquote(&buffer, "\"unterminated")); } test "a name longer than the buffer is refused" { var buffer: [4]u8 = undefined; try testing.expectError(error.PathTooLong, unquote(&buffer, "\"far too long\"")); }