Skip to main content

eggfetch_http_connect/
target.rs

1//! CONNECT authority ownership.
2//!
3//! Centralizes `host:port` formatting so every consumer does not
4//! reimplement IPv6 bracketing.
5
6use crate::error::ConnectError;
7
8/// CONNECT destination in authority form.
9///
10/// Holds a validated host and port. [`ConnectTarget::authority`] renders
11/// the exact `host:port` string used for both the `CONNECT` request-target
12/// and the `Host` header so they cannot diverge.
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
14pub struct ConnectTarget {
15    host: String,
16    port: u16,
17}
18
19impl ConnectTarget {
20    /// Create a CONNECT target.
21    ///
22    /// # Errors
23    ///
24    /// Returns [`ConnectError::InvalidTarget`] when the host is empty,
25    /// contains request-line control bytes (`CR`, `LF`, other C0 controls,
26    /// `DEL`, or space), or has malformed IPv6 brackets. Bracketed
27    /// (`[::1]`) and unbracketed (`::1`) IPv6 literals are both accepted
28    /// and normalize to the same bracketed authority. No path, query, or
29    /// body semantics exist in this type.
30    pub fn new(host: impl Into<String>, port: u16) -> Result<Self, ConnectError> {
31        let host = host.into();
32        validate_host(&host)?;
33        Ok(Self { host, port })
34    }
35
36    /// Return the raw host as supplied (brackets preserved when given).
37    #[must_use]
38    pub fn host(&self) -> &str {
39        &self.host
40    }
41
42    /// Return the port.
43    #[must_use]
44    pub fn port(&self) -> u16 {
45        self.port
46    }
47
48    /// Render the authority-form `host:port` target.
49    ///
50    /// Domains render as `example.com:443`, IPv4 as `127.0.0.1:443`,
51    /// and IPv6 bracketed as `[::1]:443`. Pre-bracketed and unbracketed
52    /// IPv6 normalize to the same bracketed form.
53    #[must_use]
54    pub fn authority(&self) -> String {
55        authority_form(&self.host, self.port)
56    }
57}
58
59/// Render authority without re-validating (already validated at construction).
60fn authority_form(host: &str, port: u16) -> String {
61    if let Some(inner) = strip_brackets(host) {
62        format!("[{inner}]:{port}")
63    } else if host.contains(':') {
64        format!("[{host}]:{port}")
65    } else {
66        format!("{host}:{port}")
67    }
68}
69
70/// Return the inner literal when `host` is fully bracketed.
71fn strip_brackets(host: &str) -> Option<&str> {
72    if host.starts_with('[') && host.ends_with(']') && host.len() >= 2 {
73        Some(&host[1..host.len() - 1])
74    } else {
75        None
76    }
77}
78
79/// Validate a CONNECT host without echoing it in errors.
80fn validate_host(host: &str) -> Result<(), ConnectError> {
81    if host.is_empty() {
82        return Err(ConnectError::InvalidTarget);
83    }
84    // Bracket shape: brackets may only wrap the whole host.
85    if host.contains('[') || host.contains(']') {
86        let Some(inner) = strip_brackets(host) else {
87            return Err(ConnectError::InvalidTarget);
88        };
89        if inner.is_empty() || inner.contains('[') || inner.contains(']') {
90            return Err(ConnectError::InvalidTarget);
91        }
92        validate_host_inner(inner)?;
93        return Ok(());
94    }
95    validate_host_inner(host)
96}
97
98/// Validate the unbracketed host body.
99fn validate_host_inner(host: &str) -> Result<(), ConnectError> {
100    if host.is_empty() {
101        return Err(ConnectError::InvalidTarget);
102    }
103    for c in host.chars() {
104        // Reject request-line control bytes: C0, DEL, and space. This
105        // blocks CR/LF injection and other control smuggling while
106        // leaving ordinary domain/IPv4/IPv6 text untouched.
107        if c == '\r' || c == '\n' || c.is_control() || c == ' ' || c == '\u{7f}' {
108            return Err(ConnectError::InvalidTarget);
109        }
110    }
111    Ok(())
112}