Skip to main content

ldap_client_proto/
dn.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! RFC 4514 Distinguished Name parser.
4
5use std::fmt::{self, Write};
6
7use crate::ProtoError;
8use crate::syntax::{escape_attribute_type, hex_pair, hex_pair_at, is_attribute_type};
9
10const ESCAPABLE: &[u8] = b"\\\"+,;<>#= ";
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Dn {
14    pub rdns: Vec<Rdn>,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Rdn {
19    pub components: Vec<(String, AttributeValue)>,
20}
21
22/// An RDN value: text, or the BER encoding that RFC 4514 section 2.4 writes
23/// as `#` and hex digits.
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25pub enum AttributeValue {
26    Text(String),
27    Ber(Vec<u8>),
28}
29
30impl AttributeValue {
31    pub fn as_text(&self) -> Option<&str> {
32        match self {
33            Self::Text(text) => Some(text),
34            Self::Ber(_) => None,
35        }
36    }
37}
38
39impl From<&str> for AttributeValue {
40    fn from(text: &str) -> Self {
41        Self::Text(text.to_owned())
42    }
43}
44
45impl From<String> for AttributeValue {
46    fn from(text: String) -> Self {
47        Self::Text(text)
48    }
49}
50
51impl PartialEq<str> for AttributeValue {
52    fn eq(&self, other: &str) -> bool {
53        self.as_text() == Some(other)
54    }
55}
56
57impl PartialEq<&str> for AttributeValue {
58    fn eq(&self, other: &&str) -> bool {
59        self.as_text() == Some(*other)
60    }
61}
62
63impl Dn {
64    pub fn parse(input: &str) -> Result<Self, ProtoError> {
65        let input = input.trim_start();
66        if input.is_empty() {
67            return Ok(Dn { rdns: Vec::new() });
68        }
69        let mut parser = Parser { input, pos: 0 };
70        Ok(Dn {
71            rdns: parser.rdns()?,
72        })
73    }
74
75    pub fn is_empty(&self) -> bool {
76        self.rdns.is_empty()
77    }
78
79    /// The DN without its first RDN, or `None` for a DN of one RDN or none.
80    pub fn parent(&self) -> Option<Dn> {
81        match self.rdns.split_first() {
82            Some((_, rest)) if !rest.is_empty() => Some(Dn {
83                rdns: rest.to_vec(),
84            }),
85            _ => None,
86        }
87    }
88}
89
90/// A cursor that only stops on ASCII bytes, so every index it slices the
91/// input at is a character boundary.
92struct Parser<'a> {
93    input: &'a str,
94    pos: usize,
95}
96
97impl Parser<'_> {
98    fn peek(&self) -> Option<u8> {
99        self.input.as_bytes().get(self.pos).copied()
100    }
101
102    fn skip_whitespace(&mut self) {
103        while self.peek().is_some_and(is_trailing_whitespace) {
104            self.pos += 1;
105        }
106    }
107
108    fn error_at(&self, pos: usize, what: &str) -> ProtoError {
109        ProtoError::Protocol(format!("{what} at byte {pos}"))
110    }
111
112    fn error(&self, what: &str) -> ProtoError {
113        self.error_at(self.pos, what)
114    }
115
116    fn rdns(&mut self) -> Result<Vec<Rdn>, ProtoError> {
117        let mut rdns = vec![self.rdn()?];
118        while self.peek() == Some(b',') {
119            self.pos += 1;
120            rdns.push(self.rdn()?);
121        }
122        match self.peek() {
123            None => Ok(rdns),
124            Some(_) => Err(self.error("expected ',' or end of DN")),
125        }
126    }
127
128    fn rdn(&mut self) -> Result<Rdn, ProtoError> {
129        let mut components = vec![self.ava()?];
130        while self.peek() == Some(b'+') {
131            self.pos += 1;
132            components.push(self.ava()?);
133        }
134        Ok(Rdn { components })
135    }
136
137    fn ava(&mut self) -> Result<(String, AttributeValue), ProtoError> {
138        let start = self.pos;
139        while self
140            .peek()
141            .is_some_and(|b| !matches!(b, b'=' | b',' | b'+'))
142        {
143            self.pos += 1;
144        }
145        if self.peek() != Some(b'=') {
146            return Err(self.error("expected '=' in attribute value assertion"));
147        }
148        let attr = self.input[start..self.pos].trim();
149        if attr.is_empty() {
150            return Err(self.error_at(start, "empty attribute type"));
151        }
152        if !is_attribute_type(attr) {
153            return Err(self.error_at(start, &format!("invalid attribute type {attr:?}")));
154        }
155        self.pos += 1;
156
157        let value = match self.peek() {
158            Some(b'#') => self.hex_value()?,
159            Some(b'"') => self.quoted_value()?,
160            _ => self.text_value()?,
161        };
162        Ok((attr.to_owned(), value))
163    }
164
165    fn hex_value(&mut self) -> Result<AttributeValue, ProtoError> {
166        self.pos += 1;
167        let start = self.pos;
168        while self
169            .peek()
170            .is_some_and(|b| !matches!(b, b',' | b'+') && !is_trailing_whitespace(b))
171        {
172            self.pos += 1;
173        }
174        let digits = &self.input.as_bytes()[start..self.pos];
175        let (pairs, odd) = digits.as_chunks::<2>();
176        let bytes = odd
177            .is_empty()
178            .then(|| {
179                pairs
180                    .iter()
181                    .map(|[high, low]| hex_pair(*high, *low))
182                    .collect::<Option<Vec<u8>>>()
183            })
184            .flatten();
185        match bytes {
186            Some(bytes) if !bytes.is_empty() => {
187                self.skip_whitespace();
188                Ok(AttributeValue::Ber(bytes))
189            }
190            _ => Err(self.error_at(
191                start,
192                "invalid hex-string in DN value: expected even number of hex digits after '#'",
193            )),
194        }
195    }
196
197    fn quoted_value(&mut self) -> Result<AttributeValue, ProtoError> {
198        self.pos += 1;
199        let start = self.pos;
200        while self.peek().is_some_and(|b| b != b'"') {
201            self.pos += 1;
202        }
203        if self.peek().is_none() {
204            return Err(self.error_at(start, "unterminated quoted string in DN"));
205        }
206        let value = self.input[start..self.pos].to_owned();
207        self.pos += 1;
208        self.skip_whitespace();
209        Ok(AttributeValue::Text(value))
210    }
211
212    fn text_value(&mut self) -> Result<AttributeValue, ProtoError> {
213        let bytes = self.input.as_bytes();
214        let mut out = Vec::new();
215        // Only unescaped trailing whitespace is trimmed. RFC 4514 names the space;
216        // tab, CR and LF are trimmed as well, as the surrounding `trim` used to.
217        let mut keep = 0;
218        while let Some(b) = self.peek() {
219            match b {
220                b',' | b'+' => break,
221                b'\\' => {
222                    let at = self.pos;
223                    self.pos += 1;
224                    if let Some(byte) = hex_pair_at(bytes, self.pos) {
225                        out.push(byte);
226                        self.pos += 2;
227                    } else if let Some(c) = self.peek().filter(|c| ESCAPABLE.contains(c)) {
228                        out.push(c);
229                        self.pos += 1;
230                    } else {
231                        return Err(self.error_at(at, "invalid escape in DN value"));
232                    }
233                    keep = out.len();
234                }
235                _ => {
236                    out.push(b);
237                    self.pos += 1;
238                    if !is_trailing_whitespace(b) {
239                        keep = out.len();
240                    }
241                }
242            }
243        }
244        out.truncate(keep);
245        String::from_utf8(out)
246            .map(AttributeValue::Text)
247            .map_err(|e| ProtoError::Protocol(format!("invalid UTF-8 in DN value: {e}")))
248    }
249}
250
251const fn is_trailing_whitespace(b: u8) -> bool {
252    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
253}
254
255/// Escape a DN value per RFC 4514 ยง2.4.
256pub fn escape_dn_value(value: &str) -> String {
257    let mut out = String::with_capacity(value.len());
258    let mut chars = value.chars().peekable();
259    let mut first = true;
260
261    while let Some(ch) = chars.next() {
262        let is_last = chars.peek().is_none();
263        let needs_escape = match ch {
264            '"' | '+' | ',' | ';' | '<' | '>' | '\\' => true,
265            '#' if first => true,
266            ' ' if first || is_last => true,
267            '\0' => true,
268            '\t' | '\n' | '\r' if is_last => true,
269            _ => false,
270        };
271        if needs_escape {
272            if ch.is_ascii_control() {
273                let _ = write!(out, "\\{:02x}", ch as u8);
274            } else {
275                out.push('\\');
276                out.push(ch);
277            }
278        } else {
279            out.push(ch);
280        }
281        first = false;
282    }
283    out
284}
285
286impl fmt::Display for Dn {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        for (i, rdn) in self.rdns.iter().enumerate() {
289            if i > 0 {
290                f.write_str(",")?;
291            }
292            write!(f, "{rdn}")?;
293        }
294        Ok(())
295    }
296}
297
298impl fmt::Display for AttributeValue {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        match self {
301            Self::Text(text) => f.write_str(&escape_dn_value(text)),
302            Self::Ber(bytes) => {
303                f.write_char('#')?;
304                bytes.iter().try_for_each(|b| write!(f, "{b:02x}"))
305            }
306        }
307    }
308}
309
310impl fmt::Display for Rdn {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        for (i, (attr, value)) in self.components.iter().enumerate() {
313            if i > 0 {
314                f.write_str("+")?;
315            }
316            write!(f, "{}={value}", escape_attribute_type(attr))?;
317        }
318        Ok(())
319    }
320}
321
322impl std::str::FromStr for Dn {
323    type Err = ProtoError;
324    fn from_str(s: &str) -> Result<Self, Self::Err> {
325        Self::parse(s)
326    }
327}