// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! LDAP URLs (RFC 4516). //! //! An LDAP URL is not a URI whose query happens to be interesting: everything //! after the host is positional, separated by `?` rather than by `&`, and the //! search filter sitting in the third position is made of the characters a //! generic parser reads as structure. `(&(objectClass=person)(cn=Bob))` has an //! `&` in it, so `Uri.parse` cuts it in two at that `&` and hands back the //! halves as unrelated query parameters. That is why this is a parser of its //! own rather than a view over `Uri`. //! //! ```zig //! const url = try uri.ldap.Url.parse(alloc, "ldap://ldap.example.com/dc=example,dc=com?cn,mail?sub?(sn=Jensen)"); //! defer url.deinit(); //! //! url.host.?.hostname // "ldap.example.com" //! url.effectivePort().? // 389 //! url.dn.? // "dc=example,dc=com" //! url.attributes // .{ "cn", "mail" } //! url.effectiveScope() // .sub //! url.effectiveFilter() // "(sn=Jensen)" //! ``` //! //! The grammar, from RFC 4516 §2: //! //! ```text //! ldapurl = scheme "://" [host [":" port]] //! ["/" dn ["?" [attributes] ["?" [scope] //! ["?" [filter] ["?" extensions]]]]] //! ``` //! //! Every piece after the scheme is optional, and RFC 4516 §2 gives each one a //! default. The fields hold exactly what was written — `null` where nothing //! was — the way `Uri.port` does; `effectivePort`, `effectiveDn`, //! `effectiveScope` and `effectiveFilter` are where the defaults are applied. //! //! Like the rest of this library, components are stored *decoded* and //! re-escaped on output, and splitting happens before decoding — so a `%3F` //! inside a filter is a literal `?` in the filter rather than a separator. const std = @import("std"); const components = @import("components.zig"); const format_mod = @import("format.zig"); const parse_mod = @import("parse.zig"); const percent = @import("percent.zig"); const schemes = @import("schemes.zig"); const Allocator = std.mem.Allocator; const Components = components.Components; const Host = components.Host; const Writer = std.Io.Writer; pub const Error = error{ /// The text has no scheme, or its scheme is not one this module knows. NotAnLdapUrl, /// The scheme is not followed by `//`. RFC 4516 §2 requires it even when /// the authority itself is empty, as in `ldapi:///`. MissingAuthority, /// The authority carries `user@` or `user:password@`. RFC 4516 has no /// userinfo: LDAP credentials are supplied by the bind operation, not by /// the URL, and quietly dropping them would mean connecting anonymously /// where the caller expected otherwise. UnexpectedUserinfo, /// The scope is written, but is not `base`, `one` or `sub`. InvalidScope, /// An attribute description is empty, as in `?cn,,mail`. EmptyAttributeDescription, /// An extension has no type, as in `?!` or `?a,,b`. EmptyExtensionType, /// There is a fifth `?`. The grammar has room for four, and a `?` inside /// any component has to be percent-encoded. ExtraQuestionMark, } || parse_mod.Error; /// The URL schemes this module parses. pub const Scheme = enum { /// RFC 4516. Port 389 by default. ldap, /// LDAP over TLS on a port of its own, port 636 by default. Never /// standardized — RFC 4513 §2.1 recommends StartTLS on an `ldap` URL /// instead — but universally implemented, so it is accepted here. ldaps, /// OpenLDAP's extension for LDAP over a Unix domain socket, where the /// host is the percent-encoded socket path (`ldapi://%2Frun%2Fslapd.sock/`) /// and an empty host means the implementation's default. It has no port. ldapi, /// The scheme as it is written in a URL. pub fn text(self: Scheme) []const u8 { return @tagName(self); } /// The scheme named by `s`, matched case-insensitively (RFC 3986 §3.1), /// or null if it is not an LDAP scheme. pub fn fromText(s: []const u8) ?Scheme { inline for (@typeInfo(Scheme).@"enum".field_names) |name| { if (std.ascii.eqlIgnoreCase(s, name)) return @field(Scheme, name); } return null; } /// The default port, or null for `ldapi`, which has no port at all. pub fn defaultPort(self: Scheme) ?u16 { return schemes.defaultPort(self.text()); } }; /// How much of the tree a search covers (RFC 4511 §4.5.1.2). pub const Scope = enum { /// The base object alone. base, /// The immediate children of the base object, but not the base object. one, /// The base object and its entire subtree. sub, /// The scope as it is written in a URL. pub fn text(self: Scope) []const u8 { return @tagName(self); } /// The scope named by `s`, or null. Matched case-insensitively: RFC 4516 /// writes these in lowercase and says nothing about case, and every /// implementation compares without regard to it. pub fn fromText(s: []const u8) ?Scope { inline for (@typeInfo(Scope).@"enum".field_names) |name| { if (std.ascii.eqlIgnoreCase(s, name)) return @field(Scope, name); } return null; } }; /// One entry of the extensions list, RFC 4516 §2: `[!]type[=value]`. /// /// The RFC calls the two halves `extype` and `exvalue`. A type the reader does /// not recognize may be ignored unless it is `critical`, in which case the URL /// must not be used at all. pub const Extension = struct { /// Written with a leading `!`. critical: bool = false, /// An OID or a registered name, e.g. `bindname`. name: []const u8, /// Null when the extension was written bare, with no `=`. That is /// distinct from an empty value, exactly as it is for a query parameter. value: ?[]const u8 = null, pub fn eql(a: Extension, b: Extension) bool { if (a.critical != b.critical) return false; if (!std.mem.eql(u8, a.name, b.name)) return false; if (a.value == null or b.value == null) return (a.value == null) == (b.value == null); return std.mem.eql(u8, a.value.?, b.value.?); } }; /// A parsed LDAP URL. /// /// Owns an arena holding all of its strings, so every accessor is /// allocation-free; `deinit` frees the lot. pub const Url = struct { arena: *std.heap.ArenaAllocator, scheme: Scheme, /// Null when the authority is empty, as in `ldap:///dc=example,dc=com`, /// which names the server the client is already talking to. host: ?Host = null, /// Exactly what was written; `effectivePort` folds in the default. port: ?u16 = null, /// The search base, decoded. Null when no `/` was written at all, which /// means the same thing as an empty DN — the root DSE — but is written /// back the way it came. dn: ?[]const u8 = null, /// The attribute descriptions to return. Empty means none were written, /// which RFC 4516 §2 defines as requesting all user attributes. attributes: []const []const u8 = &.{}, /// Null when no scope was written; the default is `.base`. scope: ?Scope = null, /// An RFC 4515 filter, decoded. Null when none was written; the default /// is `(objectClass=*)`. filter: ?[]const u8 = null, extensions: []const Extension = &.{}, pub const ParseOptions = parse_mod.Options; // -- construction ------------------------------------------------------ pub fn parse(alloc: Allocator, text: []const u8) Error!Url { return parseOpts(alloc, text, .{}); } pub fn parseOpts(alloc: Allocator, text: []const u8, opts: ParseOptions) Error!Url { const arena = try alloc.create(std.heap.ArenaAllocator); arena.* = .init(alloc); errdefer destroyArena(arena); return parseInto(arena, text, opts); } pub fn deinit(self: Url) void { destroyArena(self.arena); } // -- inspection -------------------------------------------------------- /// The port a client would connect to: the explicit one if there is one, /// otherwise the scheme's default. Null only for `ldapi`, whose address /// is a socket path rather than a host and port. pub fn effectivePort(self: Url) ?u16 { return self.port orelse self.scheme.defaultPort(); } /// The search base, which is the empty DN — the root DSE — when none was /// written. pub fn effectiveDn(self: Url) []const u8 { return self.dn orelse ""; } /// The scope to search with, defaulting to `.base` (RFC 4516 §2). pub fn effectiveScope(self: Url) Scope { return self.scope orelse .base; } /// The filter to search with, defaulting to `(objectClass=*)` /// (RFC 4516 §2). pub fn effectiveFilter(self: Url) []const u8 { return self.filter orelse "(objectClass=*)"; } /// Whether an extension this reader does not understand makes the URL /// unusable: RFC 4516 §2 says a critical extension that cannot be honored /// means the URL must not be processed at all. pub fn hasCriticalExtension(self: Url) bool { for (self.extensions) |ext| { if (ext.critical) return true; } return false; } /// The first extension named `name`, matched case-insensitively — an /// extension type is an OID or a registered name, and names are compared /// without regard to case. pub fn extension(self: Url, name: []const u8) ?Extension { for (self.extensions) |ext| { if (std.ascii.eqlIgnoreCase(ext.name, name)) return ext; } return null; } pub fn eql(self: Url, other: Url) bool { if (self.scheme != other.scheme) return false; if (self.host == null or other.host == null) { if ((self.host == null) != (other.host == null)) return false; } else if (!self.host.?.eql(other.host.?)) return false; if (self.port != other.port) return false; if (!optEqlStr(self.dn, other.dn)) return false; if (self.attributes.len != other.attributes.len) return false; for (self.attributes, other.attributes) |a, b| { if (!std.mem.eql(u8, a, b)) return false; } if (self.scope != other.scope) return false; if (!optEqlStr(self.filter, other.filter)) return false; if (self.extensions.len != other.extensions.len) return false; for (self.extensions, other.extensions) |a, b| { if (!a.eql(b)) return false; } return true; } // -- text -------------------------------------------------------------- /// Write the URL to `w`, re-escaping each component. /// /// The result is canonical rather than identical: a trailing run of empty /// `?` sections is dropped, since nothing distinguishes it from their /// absence, and escaping is normalized the way `Uri` normalizes it. pub fn write(self: Url, w: *Writer) Writer.Error!void { try w.writeAll(self.scheme.text()); try w.writeAll("://"); try format_mod.writeAuthority(w, .{ .host = self.host, .port = self.port }, .{}); // How many `?` sections have to be written for the last non-empty one // to land in the right position. const sections: usize = if (self.extensions.len > 0) 4 else if (self.filter != null) 3 else if (self.scope != null) 2 else if (self.attributes.len > 0) 1 else 0; if (self.dn == null and sections == 0) return; try w.writeByte('/'); try percent.encode(w, self.effectiveDn(), &dn_set); if (sections >= 1) { try w.writeByte('?'); for (self.attributes, 0..) |attr, i| { if (i > 0) try w.writeByte(','); try percent.encode(w, attr, &attribute_set); } } if (sections >= 2) { try w.writeByte('?'); if (self.scope) |s| try w.writeAll(s.text()); } if (sections >= 3) { try w.writeByte('?'); if (self.filter) |f| try percent.encode(w, f, &filter_set); } if (sections >= 4) { try w.writeByte('?'); for (self.extensions, 0..) |ext, i| { if (i > 0) try w.writeByte(','); if (ext.critical) try w.writeByte('!'); try percent.encode(w, ext.name, &extension_name_set); if (ext.value) |v| { try w.writeByte('='); try percent.encode(w, v, &extension_value_set); } } } } /// Render to a fresh slice owned by the caller. pub fn toText(self: Url, alloc: Allocator) Allocator.Error![]u8 { var aw: Writer.Allocating = .init(alloc); errdefer aw.deinit(); self.write(&aw.writer) catch |err| switch (err) { error.WriteFailed => return error.OutOfMemory, }; return aw.toOwnedSlice(); } /// `std.fmt` support: `{f}` renders the URL. pub fn format(self: Url, w: *Writer) Writer.Error!void { return self.write(w); } }; // -- character sets -------------------------------------------------------- // // Each is the largest set of bytes that can be written literally without // changing how the URL re-parses -- and without producing something that is // not a URI, which is why a filter's `|` comes out as `%7C` even though every // LDAP tool in the world prints it raw: RFC 3986 has no place for `|` in a // path, and RFC 4516 §3 asks for exactly this encoding. const pchar = percent.unreserved_punct ++ percent.sub_delims ++ ":@"; /// A DN sits where a path does. A literal `/` would let a generic URI parser /// split it in two, `?` would start the attribute list, and `#` -- which /// RFC 4514 §2.4 uses to introduce a hex-encoded attribute value -- would be /// read as the start of a fragment. const dn_set: percent.CharSet = percent.segment; /// `,` separates one attribute description from the next. const attribute_set: percent.CharSet = percent.charSet(.{ .add = pchar, .sub = "," }); /// RFC 4515's `(`, `)`, `&`, `!`, `*` and `=` are all sub-delims and survive /// literally, which keeps the common filters readable. const filter_set: percent.CharSet = percent.segment; /// `,` separates extensions, `=` starts the value, and a leading `!` marks /// criticality. const extension_name_set: percent.CharSet = percent.charSet(.{ .add = pchar, .sub = ",=!" }); /// Only the *first* `=` splits an extension, so a later one is unambiguous. const extension_value_set: percent.CharSet = percent.charSet(.{ .add = pchar, .sub = "," }); // -- internals ------------------------------------------------------------- fn destroyArena(arena: *std.heap.ArenaAllocator) void { const alloc = arena.child_allocator; arena.deinit(); alloc.destroy(arena); } fn optEqlStr(a: ?[]const u8, b: ?[]const u8) bool { if (a == null or b == null) return (a == null) == (b == null); return std.mem.eql(u8, a.?, b.?); } fn parseInto(arena: *std.heap.ArenaAllocator, text: []const u8, opts: Url.ParseOptions) Error!Url { const alloc = arena.allocator(); var rest = text; // scheme ":" // // Stopping at the first structural delimiter rather than at the first `:` // keeps a relative reference from being mistaken for a scheme -- `/a:b` // has no scheme at all, and should be reported as such. const colon = std.mem.indexOfAny(u8, rest, ":/?#") orelse return error.NotAnLdapUrl; if (rest[colon] != ':') return error.NotAnLdapUrl; const scheme = Scheme.fromText(rest[0..colon]) orelse return error.NotAnLdapUrl; rest = rest[colon + 1 ..]; // "//" authority if (!std.mem.startsWith(u8, rest, "//")) return error.MissingAuthority; rest = rest[2..]; // The authority ends at the `/` before the DN or the `?` before the // attributes. `#` is deliberately not a delimiter: an LDAP URL has no // fragment, and a DN may legitimately contain a `#`. var authority: Components = .{}; { const end = std.mem.indexOfAny(u8, rest, "/?") orelse rest.len; try parse_mod.parseAuthority(alloc, rest[0..end], opts, &authority); rest = rest[end..]; } if (authority.username != null or authority.password != null) return error.UnexpectedUserinfo; // An empty authority is no host at all rather than a host whose name is // empty: `ldap:///dc=example,dc=com` names no server, and leaves the // client to use whichever one it is already talking to. const host: ?Host = if (authority.host) |h| (if (h.text().len == 0) null else h) else null; var url: Url = .{ .arena = arena, .scheme = scheme, .host = host, .port = authority.port, }; // "/" dn if (rest.len > 0 and rest[0] == '/') { rest = rest[1..]; const end = std.mem.indexOfScalar(u8, rest, '?') orelse rest.len; url.dn = try percent.decode(alloc, rest[0..end], opts.strict_percent); rest = rest[end..]; } else if (rest.len > 0) { // `ldap://host?cn`, with the `/` that the grammar puts before the // first `?` left out. It is accepted rather than rejected, since it // is unambiguous -- but as an *empty* DN rather than an absent one, // because writing any later section means writing that `/` back, and // reading the result would then find an empty DN where this parse had // found none. std.debug.assert(rest[0] == '?'); url.dn = ""; } // The four `?`-separated sections. Each is optional and may be empty, and // whatever is left of `rest` always starts at a `?` -- everything else was // consumed above. var fields: [4][]const u8 = @splat(""); var count: usize = 0; while (rest.len > 0) { std.debug.assert(rest[0] == '?'); if (count == fields.len) return error.ExtraQuestionMark; rest = rest[1..]; const end = std.mem.indexOfScalar(u8, rest, '?') orelse rest.len; fields[count] = rest[0..end]; count += 1; rest = rest[end..]; } url.attributes = try parseAttributes(alloc, fields[0], opts); if (fields[1].len > 0) { const s = try percent.decode(alloc, fields[1], opts.strict_percent); url.scope = Scope.fromText(s) orelse return error.InvalidScope; } if (fields[2].len > 0) { url.filter = try percent.decode(alloc, fields[2], opts.strict_percent); } url.extensions = try parseExtensions(alloc, fields[3], opts); return url; } fn parseAttributes(alloc: Allocator, text: []const u8, opts: Url.ParseOptions) Error![]const []const u8 { if (text.len == 0) return &.{}; const out = try alloc.alloc([]const u8, std.mem.count(u8, text, ",") + 1); var it = std.mem.splitScalar(u8, text, ','); for (out) |*attr| { const field = it.next().?; if (field.len == 0) return error.EmptyAttributeDescription; attr.* = try percent.decode(alloc, field, opts.strict_percent); } return out; } fn parseExtensions(alloc: Allocator, text: []const u8, opts: Url.ParseOptions) Error![]const Extension { if (text.len == 0) return &.{}; const out = try alloc.alloc(Extension, std.mem.count(u8, text, ",") + 1); var it = std.mem.splitScalar(u8, text, ','); for (out) |*ext| { var field = it.next().?; const critical = field.len > 0 and field[0] == '!'; if (critical) field = field[1..]; // Only the first `=` is a separator; the rest belong to the value. const eq = std.mem.indexOfScalar(u8, field, '='); const name = if (eq) |i| field[0..i] else field; if (name.len == 0) return error.EmptyExtensionType; ext.* = .{ .critical = critical, .name = try percent.decode(alloc, name, opts.strict_percent), .value = if (eq) |i| try percent.decode(alloc, field[i + 1 ..], opts.strict_percent) else null, }; } return out; }