Skip to main content

parsec_url/
host.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The host parser and serializer: domains, IPv4, IPv6 and opaque hosts.
5//! A host is written straight into the URL's serialization; only the kind
6//! is kept beside it.
7
8use std::fmt;
9use std::net::{Ipv4Addr, Ipv6Addr};
10
11use crate::ParseError;
12use crate::idna;
13use crate::percent::{self, C0};
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub(crate) enum HostKind {
17    None,
18    Domain,
19    Ipv4,
20    Ipv6,
21    Opaque,
22    Empty,
23}
24
25/// Forbidden host code points, and the forbidden domain code points that
26/// add the C0 controls, `%` and DEL to them.
27const FORBIDDEN_HOST: u8 = 1;
28const FORBIDDEN_DOMAIN: u8 = 2;
29
30static FORBIDDEN: [u8; 128] = {
31    let mut t = [0; 128];
32    let mut b = 0;
33    while b < 128 {
34        let host = matches!(
35            b as u8,
36            0 | b'\t'
37                | b'\n'
38                | b'\r'
39                | b' '
40                | b'#'
41                | b'/'
42                | b':'
43                | b'<'
44                | b'>'
45                | b'?'
46                | b'@'
47                | b'['
48                | b'\\'
49                | b']'
50                | b'^'
51                | b'|'
52        );
53        let domain = host || b < 0x20 || b == b'%' as usize || b == 0x7F;
54        t[b] = ((host as u8) * FORBIDDEN_HOST) | ((domain as u8) * FORBIDDEN_DOMAIN);
55        b += 1;
56    }
57    t
58};
59
60/// What a byte of a domain needs: lowercasing, rejecting, or the slow
61/// path for percent-decoding and IDNA.
62const UPPER: u8 = 1;
63const FORBIDDEN_BYTE: u8 = 2;
64const SLOW: u8 = 4;
65
66static DOMAIN_BYTE: [u8; 256] = {
67    let mut t = [0; 256];
68    let mut b = 0;
69    while b < 256 {
70        t[b] = if b >= 0x80 || b == b'%' as usize {
71            SLOW
72        } else if FORBIDDEN[b] & FORBIDDEN_DOMAIN != 0 {
73            FORBIDDEN_BYTE
74        } else if (b as u8).is_ascii_uppercase() {
75            UPPER
76        } else {
77            0
78        };
79        b += 1;
80    }
81    t
82};
83
84pub(crate) fn forbidden_domain(b: u8) -> bool {
85    b < 128 && FORBIDDEN[b as usize] & FORBIDDEN_DOMAIN != 0
86}
87
88/// Parses `input`, which isn't empty unless `special` is false, and
89/// appends the serialized host to `out`.
90pub(crate) fn parse_into(
91    out: &mut String,
92    input: &str,
93    special: bool,
94) -> Result<HostKind, ParseError> {
95    let bytes = input.as_bytes();
96    if bytes.first() == Some(&b'[') {
97        if bytes.last() != Some(&b']') || bytes.len() < 2 {
98            return Err(ParseError::InvalidIpv6Address);
99        }
100        let address =
101            parse_ipv6(&bytes[1..bytes.len() - 1]).ok_or(ParseError::InvalidIpv6Address)?;
102        out.push('[');
103        write_ipv6(out, address);
104        out.push(']');
105        return Ok(HostKind::Ipv6);
106    }
107    if !special {
108        return parse_opaque(out, input);
109    }
110    let start = out.len();
111    // The common case: ASCII and no percent sign, lowercased as it's
112    // copied, with no IDNA to do. One pass gathers what the host has.
113    let seen = bytes
114        .iter()
115        .fold(0, |seen, &b| seen | DOMAIN_BYTE[b as usize]);
116    if seen & SLOW == 0 {
117        if seen & FORBIDDEN_BYTE != 0 {
118            return Err(ParseError::InvalidDomainCharacter);
119        }
120        if seen & UPPER != 0 {
121            out.extend(bytes.iter().map(|b| b.to_ascii_lowercase() as char));
122        } else {
123            out.push_str(input);
124        }
125    } else {
126        let decoded = percent::decode(bytes);
127        let domain = std::str::from_utf8(&decoded).map_err(|_| ParseError::IdnaError)?;
128        if domain.is_ascii() {
129            out.extend(domain.bytes().map(|b| b.to_ascii_lowercase() as char));
130        } else {
131            out.push_str(&idna::to_ascii(domain).ok_or(ParseError::IdnaError)?);
132        }
133        let ascii = &out.as_bytes()[start..];
134        if ascii.is_empty() {
135            return Err(ParseError::IdnaError);
136        }
137        if ascii.iter().any(|&b| forbidden_domain(b)) {
138            return Err(ParseError::InvalidDomainCharacter);
139        }
140    }
141    if ends_in_number(&out.as_bytes()[start..]) {
142        let address = parse_ipv4(&out.as_bytes()[start..]).ok_or(ParseError::InvalidIpv4Address)?;
143        out.truncate(start);
144        write_ipv4(out, address);
145        return Ok(HostKind::Ipv4);
146    }
147    Ok(HostKind::Domain)
148}
149
150fn parse_opaque(out: &mut String, input: &str) -> Result<HostKind, ParseError> {
151    if input
152        .bytes()
153        .any(|b| b < 128 && FORBIDDEN[b as usize] & FORBIDDEN_HOST != 0)
154    {
155        return Err(ParseError::InvalidDomainCharacter);
156    }
157    if input.is_empty() {
158        return Ok(HostKind::Empty);
159    }
160    percent::encode_into(out, input, C0);
161    Ok(HostKind::Opaque)
162}
163
164/// Whether the last label, a trailing empty one aside, is a number.
165fn ends_in_number(domain: &[u8]) -> bool {
166    let domain = domain.strip_suffix(b".").unwrap_or(domain);
167    let last = match domain.iter().rposition(|&b| b == b'.') {
168        Some(at) => &domain[at + 1..],
169        None => domain,
170    };
171    if !last.is_empty() && last.iter().all(u8::is_ascii_digit) {
172        return true;
173    }
174    matches!(last, [b'0', b'x' | b'X', rest @ ..] if rest.iter().all(u8::is_ascii_hexdigit))
175}
176
177/// An IPv4 number, `None` if it isn't one; values past `u32` come back as
178/// `u64::MAX`, which every caller rejects.
179fn parse_ipv4_number(part: &[u8]) -> Option<u64> {
180    if part.is_empty() {
181        return None;
182    }
183    let (digits, radix) = match part {
184        [b'0', b'x' | b'X', rest @ ..] => (rest, 16),
185        [b'0', rest @ ..] if !rest.is_empty() => (rest, 8),
186        _ => (part, 10),
187    };
188    let mut value: u64 = 0;
189    for &b in digits {
190        let d = (b as char).to_digit(radix)? as u64;
191        value = value.saturating_mul(radix as u64).saturating_add(d);
192    }
193    Some(value)
194}
195
196fn parse_ipv4(input: &[u8]) -> Option<u32> {
197    let input = input.strip_suffix(b".").unwrap_or(input);
198    let mut numbers = [0u64; 4];
199    let mut count = 0;
200    for part in input.split(|&b| b == b'.') {
201        if count == 4 {
202            return None;
203        }
204        numbers[count] = parse_ipv4_number(part)?;
205        count += 1;
206    }
207    let (last, rest) = numbers[..count].split_last()?;
208    if rest.iter().any(|&n| n > 255) || *last >= 256u64.pow(5 - count as u32) {
209        return None;
210    }
211    let mut ipv4 = *last;
212    for (i, &n) in rest.iter().enumerate() {
213        ipv4 += n << (8 * (3 - i));
214    }
215    Some(ipv4 as u32)
216}
217
218fn write_ipv4(out: &mut String, address: u32) {
219    use std::fmt::Write;
220    let _ = write!(out, "{}", Ipv4Addr::from(address));
221}
222
223fn parse_ipv6(input: &[u8]) -> Option<[u16; 8]> {
224    let mut address = [0u16; 8];
225    let mut piece = 0;
226    let mut compress = None;
227    let mut p = 0;
228    let at = |p: usize| input.get(p).copied();
229    if at(0) == Some(b':') {
230        if at(1) != Some(b':') {
231            return None;
232        }
233        p = 2;
234        piece = 1;
235        compress = Some(1);
236    }
237    while let Some(c) = at(p) {
238        if piece == 8 {
239            return None;
240        }
241        if c == b':' {
242            if compress.is_some() {
243                return None;
244            }
245            p += 1;
246            piece += 1;
247            compress = Some(piece);
248            continue;
249        }
250        let (mut value, mut length) = (0u16, 0);
251        while length < 4
252            && let Some(d) = at(p).and_then(|c| (c as char).to_digit(16))
253        {
254            value = value * 0x10 + d as u16;
255            p += 1;
256            length += 1;
257        }
258        match at(p) {
259            Some(b'.') => {
260                if length == 0 {
261                    return None;
262                }
263                p -= length;
264                if piece > 6 {
265                    return None;
266                }
267                let mut seen = 0;
268                while let Some(c) = at(p) {
269                    if seen > 0 {
270                        if c == b'.' && seen < 4 {
271                            p += 1;
272                        } else {
273                            return None;
274                        }
275                    }
276                    if !at(p).is_some_and(|c| c.is_ascii_digit()) {
277                        return None;
278                    }
279                    let mut part: Option<u16> = None;
280                    while let Some(c) = at(p).filter(u8::is_ascii_digit) {
281                        let n = (c - b'0') as u16;
282                        part = match part {
283                            None => Some(n),
284                            Some(0) => return None,
285                            Some(v) => Some(v * 10 + n),
286                        };
287                        if part > Some(255) {
288                            return None;
289                        }
290                        p += 1;
291                    }
292                    address[piece] = address[piece] * 0x100 + part?;
293                    seen += 1;
294                    if seen == 2 || seen == 4 {
295                        piece += 1;
296                    }
297                }
298                if seen != 4 {
299                    return None;
300                }
301                break;
302            }
303            Some(b':') => {
304                p += 1;
305                at(p)?;
306            }
307            Some(_) => return None,
308            None => {}
309        }
310        address[piece] = value;
311        piece += 1;
312    }
313    if let Some(compress) = compress {
314        let mut swaps = piece - compress;
315        piece = 7;
316        while piece != 0 && swaps > 0 {
317            address.swap(piece, compress + swaps - 1);
318            piece -= 1;
319            swaps -= 1;
320        }
321    } else if piece != 8 {
322        return None;
323    }
324    Some(address)
325}
326
327fn write_ipv6(out: &mut String, address: [u16; 8]) {
328    use std::fmt::Write;
329    // The first longest run of two or more zero pieces becomes "::".
330    let (mut best, mut best_len, mut run, mut run_len) = (None, 1, 0, 0);
331    for (i, &piece) in address.iter().enumerate() {
332        if piece == 0 {
333            if run_len == 0 {
334                run = i;
335            }
336            run_len += 1;
337            if run_len > best_len {
338                best = Some(run);
339                best_len = run_len;
340            }
341        } else {
342            run_len = 0;
343        }
344    }
345    let mut i = 0;
346    while i < 8 {
347        if best == Some(i) {
348            out.push_str(if i == 0 { "::" } else { ":" });
349            i += best_len;
350            continue;
351        }
352        let _ = write!(out, "{:x}", address[i]);
353        if i != 7 {
354            out.push(':');
355        }
356        i += 1;
357    }
358}
359
360/// A host as `Host::parse` gives it: what a special URL's host can be.
361#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
362pub enum Host {
363    Domain(String),
364    Ipv4(Ipv4Addr),
365    Ipv6(Ipv6Addr),
366}
367
368impl Host {
369    /// Runs the host parser as a special URL's host would, so a domain
370    /// goes through IDNA and a number-ending one must be IPv4.
371    pub fn parse(input: &str) -> Result<Host, ParseError> {
372        if input.is_empty() {
373            return Err(ParseError::EmptyHost);
374        }
375        let mut s = String::new();
376        Ok(match parse_into(&mut s, input, true)? {
377            // The serializations are canonical, so std reads them back.
378            HostKind::Ipv4 => Host::Ipv4(s.parse().map_err(|_| ParseError::InvalidIpv4Address)?),
379            HostKind::Ipv6 => Host::Ipv6(
380                s[1..s.len() - 1]
381                    .parse()
382                    .map_err(|_| ParseError::InvalidIpv6Address)?,
383            ),
384            _ => Host::Domain(s),
385        })
386    }
387}
388
389impl fmt::Display for Host {
390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391        match self {
392            Host::Domain(d) => f.write_str(d),
393            Host::Ipv4(a) => write!(f, "{a}"),
394            Host::Ipv6(a) => {
395                let mut s = String::from("[");
396                write_ipv6(&mut s, a.segments());
397                s.push(']');
398                f.write_str(&s)
399            }
400        }
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    fn host(input: &str) -> Option<String> {
409        let mut s = String::new();
410        parse_into(&mut s, input, true).ok().map(|_| s)
411    }
412
413    #[test]
414    fn ipv4_forms() {
415        assert_eq!(host("0x7f.1").as_deref(), Some("127.0.0.1"));
416        assert_eq!(host("4294967295").as_deref(), Some("255.255.255.255"));
417        assert_eq!(host("4294967296"), None);
418        assert_eq!(host("1.2.3.4.5"), None);
419        assert_eq!(host("09"), None);
420        assert_eq!(host("a.0x"), None);
421        assert_eq!(host("foo.09"), None);
422        assert_eq!(host("example.com").as_deref(), Some("example.com"));
423    }
424
425    #[test]
426    fn ipv6_forms() {
427        assert_eq!(host("[::1]").as_deref(), Some("[::1]"));
428        assert_eq!(host("[0:0:1:0:0:0:0:0]").as_deref(), Some("[0:0:1::]"));
429        assert_eq!(host("[::127.0.0.1]").as_deref(), Some("[::7f00:1]"));
430        assert_eq!(host("[1:2:3:4:5:6:7:8:9]"), None);
431        assert_eq!(host("[::1"), None);
432    }
433}