Something went wrong. Try again.
A URI parser and formatter for Zig, modelled on Python's hyperlink package, with LDAP URLs, file: URIs and sdns:// DNS stamps beside it.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An RFC 3986 URI-reference parser.//!//! Parsing splits on delimiters first and decodes second, so a percent-encoded//! delimiter (`%2F` in a path segment, `%40` in a username) never splits the//! reference — it just ends up as a literal byte in the decoded component.
const std = @import("std");const z46 = @import("z46");
const percent = @import("percent.zig");const components = @import("components.zig");
const Components = components.Components;const Host = components.Host;const QueryParam = components.QueryParam;
pub const Error = error{ /// Text before the first `:` is not a well-formed scheme. InvalidScheme, /// The authority has trailing junk after the host, e.g. `//[::1]x`. InvalidAuthority, /// An IPv6 literal is missing its closing `]`. UnterminatedIPv6Literal, /// The port is not a decimal number that fits in a u16. InvalidPort, /// The text inside `[` and `]` is not a valid IPv6 address. InvalidIPv6Literal,} || percent.Error || std.mem.Allocator.Error;
pub const Options = struct { /// Reject a `%` that is not followed by two hex digits, instead of keeping /// it as a literal `%`. See `percent.decode`. strict_percent: bool = false,};
/// Parse a URI-reference into `Components`, allocating every decoded string/// from `alloc`. Nothing borrows from `text`.pub fn parse(alloc: std.mem.Allocator, text: []const u8, opts: Options) Error!Components { var out: Components = .{}; var rest = text;
// scheme ":" // Stop at the first structural delimiter: if it is not a `:`, the reference // is relative and everything so far belongs to the path. if (std.mem.indexOfAny(u8, rest, ":/?#")) |i| { if (rest[i] == ':') { const s = rest[0..i]; if (s.len == 0 or !std.ascii.isAlphabetic(s[0])) return error.InvalidScheme; for (s[1..]) |c| { if (!percent.scheme.has(c)) return error.InvalidScheme; } out.scheme = try alloc.dupe(u8, s); rest = rest[i + 1 ..]; } }
// "//" authority if (rest.len >= 2 and rest[0] == '/' and rest[1] == '/') { rest = rest[2..]; const end = std.mem.indexOfAny(u8, rest, "/?#") orelse rest.len; try parseAuthority(alloc, rest[0..end], opts, &out); rest = rest[end..]; }
// path { const end = std.mem.indexOfAny(u8, rest, "?#") orelse rest.len; var path_text = rest[0..end]; rest = rest[end..];
if (path_text.len > 0) { if (path_text[0] == '/') { out.rooted = true; path_text = path_text[1..]; } var n: usize = 1; for (path_text) |c| { if (c == '/') n += 1; } const segs = try alloc.alloc([]const u8, n); var it = std.mem.splitScalar(u8, path_text, '/'); for (segs) |*seg| seg.* = try percent.decode(alloc, it.next().?, opts.strict_percent); out.path = segs; } }
// "?" query if (rest.len > 0 and rest[0] == '?') { rest = rest[1..]; const end = std.mem.indexOfScalar(u8, rest, '#') orelse rest.len; out.query = try parseQuery(alloc, rest[0..end], opts); rest = rest[end..]; }
// "#" fragment if (rest.len > 0 and rest[0] == '#') { out.fragment = try percent.decode(alloc, rest[1..], opts.strict_percent); }
return out;}
/// Parse the query string between `?` and `#` into decoded key/value pairs.////// An empty query string yields no parameters, so `http://x/?` and `http://x/`/// are the same URI. `+` is left alone: it means a space only under/// `application/x-www-form-urlencoded`, which is a form convention rather than/// part of URI syntax.pub fn parseQuery(alloc: std.mem.Allocator, text: []const u8, opts: Options) Error![]const QueryParam { if (text.len == 0) return &.{};
var n: usize = 1; for (text) |c| { if (c == '&') n += 1; } const params = try alloc.alloc(QueryParam, n); var it = std.mem.splitScalar(u8, text, '&'); for (params) |*param| { const pair = it.next().?; if (std.mem.indexOfScalar(u8, pair, '=')) |i| { param.* = .{ .key = try percent.decode(alloc, pair[0..i], opts.strict_percent), .value = try percent.decode(alloc, pair[i + 1 ..], opts.strict_percent), }; } else { param.* = .{ .key = try percent.decode(alloc, pair, opts.strict_percent) }; } } return params;}
/// Parse `[userinfo "@"] host [":" port]` into the authority fields of `out`,/// leaving the rest of it alone.////// Public because `ldap` needs the same authority grammar: RFC 4516 §2 takes/// its host and port straight from RFC 3986 §3.2.2 and §3.2.3.pub fn parseAuthority(alloc: std.mem.Allocator, authority: []const u8, opts: Options, out: *Components) Error!void { var rest = authority;
// Split on the first `@`: userinfo may not contain a literal one. if (std.mem.indexOfScalar(u8, rest, '@')) |i| { const userinfo = rest[0..i]; if (std.mem.indexOfScalar(u8, userinfo, ':')) |j| { out.username = try percent.decode(alloc, userinfo[0..j], opts.strict_percent); out.password = try percent.decode(alloc, userinfo[j + 1 ..], opts.strict_percent); } else { out.username = try percent.decode(alloc, userinfo, opts.strict_percent); } rest = rest[i + 1 ..]; }
if (rest.len > 0 and rest[0] == '[') { const close = std.mem.indexOfScalar(u8, rest, ']') orelse return error.UnterminatedIPv6Literal; const literal = rest[1..close]; try validateIPv6Literal(literal); out.host = .{ .ipv6 = try alloc.dupe(u8, literal) }; rest = rest[close + 1 ..]; if (rest.len > 0 and rest[0] != ':') return error.InvalidAuthority; } else { const end = std.mem.indexOfScalar(u8, rest, ':') orelse rest.len; const host = try percent.decode(alloc, rest[0..end], opts.strict_percent); // RFC 3986 §3.2.2 tries IPv4address first and falls back to reg-name, // so anything z46 will not accept is simply a host name. That makes // `192.168.01.1` a name rather than an address, because a dec-octet // may not have a leading zero -- which is the point: a parser that // reads it as octal and one that reads it as decimal would disagree // about which host it is. out.host = if (z46.Ipv4Address.isValid(host)) .{ .ipv4 = host } else .{ .hostname = host }; rest = rest[end..]; }
// An authority with a bare trailing `:` and no digits has no port, which is // what RFC 3986 §3.2.3 allows and what browsers do. if (rest.len > 0) { std.debug.assert(rest[0] == ':'); const digits = rest[1..]; if (digits.len > 0) { out.port = std.fmt.parseUnsigned(u16, digits, 10) catch return error.InvalidPort; } }}
/// Check the text between `[` and `]` (RFC 3986 §3.2.2), which is an/// IPv6address, optionally with an RFC 6874 zone identifier, or an IPvFuture.////// The literal is stored exactly as written rather than canonicalised, so this/// only rejects; it never rewrites.fn validateIPv6Literal(literal: []const u8) Error!void { // IPvFuture (`[v7.something]`) is a forward-compatibility escape hatch // with no defined interpretation, so there is nothing to validate beyond // its shape: `v` HEXDIG+ `.` and at least one character after the dot. if (literal.len > 0 and (literal[0] == 'v' or literal[0] == 'V')) { const dot = std.mem.indexOfScalar(u8, literal, '.') orelse return error.InvalidIPv6Literal; if (dot < 2 or dot + 1 >= literal.len) return error.InvalidIPv6Literal; for (literal[1..dot]) |c| { if (!std.ascii.isHex(c)) return error.InvalidIPv6Literal; } return; }
// A zone identifier is percent-encoded in a URI (RFC 6874: `%25` for the // `%` that introduces it), so the address ends at the first `%`. const address = if (std.mem.indexOfScalar(u8, literal, '%')) |i| blk: { const rest = literal[i + 1 ..]; // `%25` and then a non-empty zone. if (!std.mem.startsWith(u8, rest, "25") or rest.len <= 2) { return error.InvalidIPv6Literal; } break :blk literal[0..i]; } else literal;
if (!z46.Ipv6Address.isValid(address)) return error.InvalidIPv6Literal;}