// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `file:` URIs (RFC 8089) and the filesystem paths they name. //! //! A `file:` URI is an authority and a path: `file://host/path`, where the //! host is the machine the path is on and an empty one — or `localhost`, //! which RFC 8089 §2 makes equivalent — means this one. So an ordinary local //! path is written with an empty authority and three slashes, //! `file:///etc/hosts`, which is what browsers, editors and desktop //! environments all expect. The two-slash form `file:/etc/hosts` is legal and //! parses to the same path, but is never produced here. //! //! The path is stored the way every other path in this library is: decoded //! segments, escaped on output. A byte that cannot appear literally in a path //! segment is therefore escaped for you, and a `%2F` read back becomes one //! segment containing a `/` rather than two segments — which is why `toPath` //! rejects it rather than writing a path naming a different file. //! //! ## Platforms //! //! `Options.platform` chooses whose path syntax is being read or written, and //! defaults to the platform this was built for. Naming one explicitly is how //! a test — or a tool handling paths from somewhere else — reads a Windows //! path on a POSIX machine. //! //! POSIX is the simple case: a path is a `/`-separated string of arbitrary //! bytes, so the conversion is a split and a join and nothing is lost in //! either direction. //! //! Windows has three shapes, and RFC 8089 Appendix E describes the first two: //! //! * a drive path, `C:\Users\me`, whose drive letter becomes the first path //! segment: `file:///C:/Users/me`. The legacy `file:///C|/Users/me`, //! which Appendix E.2 records, is read back as the same path; //! * a UNC path, `\\server\share\file`, whose server becomes the URI's //! host: `file://server/share/file`; //! * a root-relative path, `\Users\me`, which names a path on whatever the //! current drive is. It is not fully qualified, but it is exactly what //! `file:///Users/me` reads back as, so it is accepted rather than //! leaving that URI with no path at all. //! //! Both separators are accepted on input and `\` is always written, so a //! Windows path round-trips through a URI in canonical form rather than //! byte-for-byte: `C:/a` comes back as `C:\a`. A POSIX path round-trips //! exactly. //! //! Three Windows shapes have no `file:` URI at all, and are rejected rather //! than written down as something else: //! //! * the Win32 device namespace, `\\?\C:\x` and `\\.\PhysicalDrive0`, //! which is not a share — and neither is the `file://./x` that would be //! read back as one; //! * `\C:`, a root-relative path whose first component is a drive //! specification, since `file:///C:` is read by everything as the drive //! itself. A colon cannot appear in a Windows filename anyway; //! * and, in the other direction, `file:////x`, whose path would open with //! the two separators of a UNC prefix under an authority saying it is //! not one. //! //! ## Relative paths //! //! A relative path names nothing on its own, and resolving one needs the //! working directory, which is I/O this library does not do. `fromPath` //! therefore rejects it; ask the caller's `Io` for the directory and descend //! from there: //! //! ```zig //! const cwd = try dir.realpathAlloc(alloc, ".", io); //! const base = try Uri.fromPath(alloc, cwd, .{}); //! const target = try base.child(alloc, &.{ "zig-out", "docs" }); //! ``` const std = @import("std"); const builtin = @import("builtin"); const z46 = @import("z46"); const components = @import("components.zig"); const Allocator = std.mem.Allocator; const Components = components.Components; const Host = components.Host; const Writer = std.Io.Writer; pub const Error = error{ /// A path that names nothing on its own: a relative path, a Windows path /// relative to a drive's current directory (`C:a`), or a URI whose path /// is not rooted. PathNotAbsolute, /// A path with no `file:` URI, or a URI with no path: a NUL byte, a /// separator inside a single path segment, a Windows device path, or a /// shape that would be read back as a different path. InvalidPath, /// The URI names a host other than this machine, and this platform has no /// path that reaches one. POSIX has none at all; on Windows this is a UNC /// path, which only a registered name or a dotted quad can be written as. NonLocalHost, /// `toPath` on something that is not a `file:` URI. NotFileScheme, }; pub const Platform = enum { posix, windows, /// The platform this was built for. pub const native: Platform = if (builtin.os.tag == .windows) .windows else .posix; }; pub const Options = struct { /// Whose path syntax to read or write. platform: Platform = Platform.native, }; // -- path to URI ----------------------------------------------------------- /// The components of a `file:` URI naming `path`, which must be absolute. /// /// The result **borrows** from `path`: its segments point into it, and the /// scheme and an empty host are static. `Uri.fromPath` is the owning version. pub fn fromPath( alloc: Allocator, path: []const u8, opts: Options, ) (Error || Allocator.Error)!Components { if (path.len == 0) return error.PathNotAbsolute; // A NUL ends a path for every system call that takes one, so a URI // carrying one would name a different file than it appears to. if (std.mem.indexOfScalar(u8, path, 0) != null) return error.InvalidPath; return switch (opts.platform) { .posix => posixFromPath(alloc, path), .windows => windowsFromPath(alloc, path), }; } fn posixFromPath(alloc: Allocator, path: []const u8) (Error || Allocator.Error)!Components { if (path[0] != '/') return error.PathNotAbsolute; // The leading `/` is the `rooted` flag rather than a segment, and what is // left of `//foo` is the empty first segment that keeps it distinct from // `/foo` -- POSIX leaves that path implementation-defined, so it is // preserved rather than folded away. return .{ .scheme = "file", .host = .{ .hostname = "" }, .rooted = true, .path = try splitSegments(alloc, path[1..], .posix), }; } fn windowsFromPath(alloc: Allocator, path: []const u8) (Error || Allocator.Error)!Components { if (path.len >= 2 and isSeparator(path[0], .windows) and isSeparator(path[1], .windows)) { const rest = path[2..]; // `\\?\C:\x` and `\\.\PhysicalDrive0` are the Win32 device namespace, // not a share. There is no `file:` URI for either. if (rest.len > 0 and (rest[0] == '?' or rest[0] == '.') and (rest.len == 1 or isSeparator(rest[1], .windows))) { return error.InvalidPath; } const parts = try splitSegments(alloc, rest, .windows); if (parts[0].len == 0) return error.InvalidPath; return .{ .scheme = "file", .host = classifyHost(parts[0]), .rooted = true, // `\\server` on its own reaches no file. The root of the server's // namespace is the only thing it can mean, and a URI has to have // a path for the authority to end. .path = if (parts.len > 1) parts[1..] else &.{""}, }; } if (drivePath(path)) { if (path.len < 3 or !isSeparator(path[2], .windows)) return error.PathNotAbsolute; // The drive becomes the first segment, which is what makes the result // `file:///C:/x` -- three slashes for the empty host, then a path // whose first segment happens to end in a colon. const tail = try splitSegments(alloc, path[3..], .windows); const segs = try alloc.alloc([]const u8, tail.len + 1); segs[0] = path[0..2]; @memcpy(segs[1..], tail); return .{ .scheme = "file", .host = .{ .hostname = "" }, .rooted = true, .path = segs }; } if (isSeparator(path[0], .windows)) { const segs = try splitSegments(alloc, path[1..], .windows); // `\C:` would be written `file:///C:`, which everything that reads a // `file:` URI takes for the drive rather than for a file called `C:` // at the root of the current one. A colon cannot appear in a Windows // filename anyway, so there is nothing real to lose by refusing to // write down the ambiguity. if (driveSegment(segs[0]) != null) return error.InvalidPath; return .{ .scheme = "file", .host = .{ .hostname = "" }, .rooted = true, .path = segs, }; } return error.PathNotAbsolute; } // -- URI to path ----------------------------------------------------------- /// The filesystem path a `file:` URI names, as a fresh slice owned by the /// caller. /// /// Query and fragment are ignored: neither names anything on a filesystem, /// and a `file:` URI that carries one is still pointing at the same file. pub fn toPath( alloc: Allocator, c: Components, opts: Options, ) (Error || Allocator.Error)![]u8 { const scheme = c.scheme orelse return error.NotFileScheme; if (!std.ascii.eqlIgnoreCase(scheme, "file")) return error.NotFileScheme; var host: []const u8 = ""; if (c.host) |h| { // A UNC path cannot name an address literal; Windows spells one as a // name under `ipv6-literal.net` instead, which is a conversion rather // than a reading and belongs to the caller. if (h == .ipv6) return error.NonLocalHost; host = h.text(); } // RFC 8089 §2: an empty host and `localhost` both mean this machine. const local = host.len == 0 or std.ascii.eqlIgnoreCase(host, "localhost"); if (!c.rooted) return error.PathNotAbsolute; if (opts.platform == .posix and !local) return error.NonLocalHost; // A segment holding a separator cannot be written back into a path: // `file:///a%2Fb` names one file called `a/b`, and `/a/b` names two. for (c.path) |seg| { for (seg) |ch| { if (ch == 0 or isSeparator(ch, opts.platform)) return error.InvalidPath; } } if (!local) { for (host) |ch| { if (ch == 0 or isSeparator(ch, opts.platform)) return error.InvalidPath; } // `\\.\` and `\\?\` open the Win32 device namespace rather than // naming a server, so those two hosts have no UNC path either. (Only // Windows gets this far: POSIX has already refused every host.) if (host.len == 1 and (host[0] == '.' or host[0] == '?')) return error.InvalidPath; } else if (opts.platform == .windows) { // A Windows path opening with two separators is a UNC prefix, and // this one has an empty authority saying it is not. `file:////a` has // no Windows path, and `\\a` is not it. const has_drive = c.path.len > 0 and driveSegment(c.path[0]) != null; if (!has_drive and c.path.len >= 2 and c.path[0].len == 0) return error.InvalidPath; } var aw: Writer.Allocating = .init(alloc); errdefer aw.deinit(); writePath(&aw.writer, c.path, host, local, opts.platform) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, }; return aw.toOwnedSlice(); } fn writePath( w: *Writer, path: []const []const u8, host: []const u8, local: bool, platform: Platform, ) Writer.Error!void { if (platform == .posix) { if (path.len == 0) return w.writeByte('/'); for (path) |seg| { try w.writeByte('/'); try w.writeAll(seg); } return; } var segs = path; if (!local) { try w.writeAll("\\\\"); try w.writeAll(host); } else if (segs.len > 0) { if (driveSegment(segs[0])) |letter| { try w.writeByte(letter); try w.writeByte(':'); segs = segs[1..]; } } // `file:///C:` is the drive, and `C:` on its own would be the *current // directory* on it, so the root separator is written either way. if (segs.len == 0) return w.writeByte('\\'); for (segs) |seg| { try w.writeByte('\\'); try w.writeAll(seg); } } // -- internals ------------------------------------------------------------- fn isSeparator(c: u8, platform: Platform) bool { return c == '/' or (platform == .windows and c == '\\'); } /// Whether `path` begins with a drive specification, `C:`. fn drivePath(path: []const u8) bool { return path.len >= 2 and std.ascii.isAlphabetic(path[0]) and path[1] == ':'; } /// The drive letter of a path segment that is one, `C:` — or the `C|` that /// older software wrote in a URI instead, which RFC 8089 Appendix E.2 records. fn driveSegment(seg: []const u8) ?u8 { if (seg.len != 2 or !std.ascii.isAlphabetic(seg[0])) return null; return if (seg[1] == ':' or seg[1] == '|') seg[0] else null; } /// Split a path into segments on every separator, keeping the empty ones: a /// trailing separator becomes a trailing empty segment, which is what makes /// `/a/b/` a directory rather than a file. fn splitSegments( alloc: Allocator, path: []const u8, platform: Platform, ) Allocator.Error![]const []const u8 { var n: usize = 1; for (path) |c| { if (isSeparator(c, platform)) n += 1; } const segs = try alloc.alloc([]const u8, n); var i: usize = 0; var start: usize = 0; for (path, 0..) |c, j| { if (!isSeparator(c, platform)) continue; segs[i] = path[start..j]; i += 1; start = j + 1; } segs[i] = path[start..]; return segs; } /// Classify a UNC server name the way the parser classifies a host, so that a /// name which happens to be a dotted quad comes back from /// `file://192.0.2.1/share` as the same `Host` it went in as. fn classifyHost(name: []const u8) Host { return if (z46.Ipv4Address.isValid(name)) .{ .ipv4 = name } else .{ .hostname = name }; }