Skip to main content

net_io/
proxy_parse.rs

1//! The PROXY protocol parser (versions 1 and 2): a sans-IO state machine.
2//!
3//! Give [`ProxyParser::feed`] every byte received so far; it resumes where it
4//! stopped and never reads past the end of the header, so the bytes after
5//! `consumed` stay application data. The grammar follows the HAProxy PROXY
6//! protocol specification; the v1 text is parsed strictly (single spaces, no
7//! leading zeros, addresses parsed by this module's own grammar).
8
9use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
10use std::str;
11
12use crate::crc32c::Crc32c;
13use crate::proxy::{ProxyError, ProxyFacts, ProxyVersions};
14
15const V1_PREFIX: &[u8] = b"PROXY ";
16const V1_MAX: usize = 107;
17const V2_SIGNATURE: [u8; 12] = [
18    0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A,
19];
20const V2_FIXED: usize = 16;
21
22const TLV_ALPN: u8 = 0x01;
23const TLV_AUTHORITY: u8 = 0x02;
24const TLV_CRC32C: u8 = 0x03;
25const TLV_NOOP: u8 = 0x04;
26const TLV_UNIQUE_ID: u8 = 0x05;
27const TLV_SSL: u8 = 0x20;
28const SSL_VERSION: u8 = 0x21;
29const SSL_CN: u8 = 0x22;
30const SSL_CIPHER: u8 = 0x23;
31const SSL_SIG_ALG: u8 = 0x24;
32const SSL_KEY_ALG: u8 = 0x25;
33const TLV_NETNS: u8 = 0x30;
34const UNIQUE_ID_MAX: usize = 128;
35
36/// Which version the parser is reading.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38enum Kind {
39    Undecided,
40    V1,
41    V2,
42}
43
44/// A sans-IO PROXY header parser for one connection.
45///
46/// # Examples
47///
48/// ```
49/// use net_io::{ProxyParser, ProxyProgress, ProxyVersions};
50/// let mut parser = ProxyParser::new(ProxyVersions::Both, 1024);
51/// let bytes = b"PROXY TCP4 192.0.2.1 198.51.100.2 51000 443\r\nGET / HTTP/1.1\r\n";
52/// match parser.feed(bytes)? {
53///     ProxyProgress::Done { header, consumed } => {
54///         assert_eq!(&bytes[consumed..], b"GET / HTTP/1.1\r\n");
55///         assert_eq!(header.source.unwrap().to_string(), "192.0.2.1:51000");
56///     }
57///     ProxyProgress::NeedMore { .. } => unreachable!(),
58/// }
59/// # Ok::<(), net_io::ProxyError>(())
60/// ```
61#[derive(Clone, Debug)]
62pub struct ProxyParser {
63    versions: ProxyVersions,
64    v2_body_max: u16,
65    kind: Kind,
66    /// v1: bytes already searched for the line end.
67    scanned: usize,
68}
69
70/// What [`ProxyParser::feed`] found.
71#[derive(Debug)]
72pub enum ProxyProgress<'a> {
73    /// The header is incomplete: feed again with at least this many more bytes.
74    NeedMore {
75        /// The fewest additional bytes that can make progress.
76        at_least: usize,
77    },
78    /// A complete header; the bytes from `consumed` on are application data.
79    Done {
80        /// The header, borrowing from the input.
81        header: ProxyHeader<'a>,
82        /// The header's length in bytes.
83        consumed: usize,
84    },
85}
86
87/// A parsed PROXY header, borrowing from the bytes it was parsed from.
88#[non_exhaustive]
89#[derive(Clone, Copy, Debug)]
90pub struct ProxyHeader<'a> {
91    /// 1 or 2.
92    pub version: u8,
93    /// `Proxy`, or `Local` (a connection made by the proxy itself, such as a
94    /// health check: keep the socket's own addresses).
95    pub command: ProxyCommand,
96    /// The transport of the proxied connection (`Unspecified` for a v2 `LOCAL`
97    /// header with a family the specification does not list).
98    pub transport: ProxyTransport,
99    /// The real client; `None` for `LOCAL`, v1 `UNKNOWN`, and v2 `UNSPEC`.
100    pub source: Option<ProxyAddress<'a>>,
101    /// The address the client connected to; `None` as for `source`.
102    pub destination: Option<ProxyAddress<'a>>,
103    /// The v2 TLVs (empty for v1, and for a v2 `LOCAL` header whose family is
104    /// unknown or whose address block is short, which is ignored whole); `NOOP`
105    /// entries are skipped.
106    pub tlvs: Tlvs<'a>,
107    crc_checked: bool,
108}
109
110/// The PROXY command.
111#[non_exhaustive]
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum ProxyCommand {
114    /// A proxied connection.
115    Proxy,
116    /// A connection made by the proxy itself.
117    Local,
118}
119
120/// The transport of the proxied connection.
121#[non_exhaustive]
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
123pub enum ProxyTransport {
124    /// A stream (TCP, or a Unix stream socket).
125    Stream,
126    /// Datagrams.
127    Datagram,
128    /// Not given.
129    Unspecified,
130}
131
132/// An address in a PROXY header.
133#[non_exhaustive]
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
135pub enum ProxyAddress<'a> {
136    /// An IP address and port.
137    Ip(SocketAddr),
138    /// A Unix socket path (v2 only), with trailing zero bytes removed.
139    Unix(&'a [u8]),
140}
141
142impl ProxyAddress<'_> {
143    /// The IP socket address, if this is one.
144    #[must_use]
145    pub fn socket_addr(&self) -> Option<SocketAddr> {
146        match self {
147            ProxyAddress::Ip(a) => Some(*a),
148            ProxyAddress::Unix(_) => None,
149        }
150    }
151}
152
153impl std::fmt::Display for ProxyAddress<'_> {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        match self {
156            ProxyAddress::Ip(a) => write!(f, "{a}"),
157            ProxyAddress::Unix(p) => write!(f, "{}", String::from_utf8_lossy(p)),
158        }
159    }
160}
161
162/// One v2 TLV.
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub struct Tlv<'a> {
165    /// The type byte.
166    pub kind: u8,
167    /// The value.
168    pub value: &'a [u8],
169}
170
171/// The TLVs of a v2 header, already checked to fit the declared length.
172#[derive(Clone, Copy, Debug)]
173pub struct Tlvs<'a> {
174    rest: &'a [u8],
175}
176
177impl<'a> Iterator for Tlvs<'a> {
178    type Item = Tlv<'a>;
179
180    fn next(&mut self) -> Option<Tlv<'a>> {
181        loop {
182            let (tlv, rest) = split_tlv(self.rest)?;
183            self.rest = rest;
184            if tlv.kind != TLV_NOOP {
185                return Some(tlv);
186            }
187        }
188    }
189}
190
191/// The SSL facts a proxy that terminated TLS reports (v2 TLV `0x20`).
192#[non_exhaustive]
193#[derive(Clone, Copy, Debug)]
194pub struct ProxySsl<'a> {
195    /// The client flags: bit 0 SSL, bit 1 a client certificate on this
196    /// connection, bit 2 one in the session.
197    pub client: u8,
198    /// Whether the client certificate was verified (`verify` field 0).
199    pub verified: bool,
200    /// The TLS version, such as `TLSv1.3`.
201    pub version: Option<&'a str>,
202    /// The client certificate's common name.
203    pub common_name: Option<&'a str>,
204    /// The cipher.
205    pub cipher: Option<&'a str>,
206    /// The certificate's signature algorithm.
207    pub signature_algorithm: Option<&'a str>,
208    /// The certificate's key algorithm.
209    pub key_algorithm: Option<&'a str>,
210}
211
212impl<'a> ProxyHeader<'a> {
213    fn find(&self, kind: u8) -> Option<&'a [u8]> {
214        let mut tlvs = self.tlvs;
215        tlvs.find(|t| t.kind == kind).map(|t| t.value)
216    }
217
218    /// The ALPN protocol the proxy negotiated with the client (TLV `0x01`).
219    #[must_use]
220    pub fn alpn(&self) -> Option<&'a [u8]> {
221        self.find(TLV_ALPN)
222    }
223
224    /// The authority (host name) the client asked for (TLV `0x02`), if UTF-8.
225    #[must_use]
226    pub fn authority(&self) -> Option<&'a str> {
227        self.find(TLV_AUTHORITY)
228            .and_then(|v| str::from_utf8(v).ok())
229    }
230
231    /// The proxy's unique connection id (TLV `0x05`, at most 128 bytes).
232    #[must_use]
233    pub fn unique_id(&self) -> Option<&'a [u8]> {
234        self.find(TLV_UNIQUE_ID)
235    }
236
237    /// The SSL facts (TLV `0x20`).
238    #[must_use]
239    pub fn ssl(&self) -> Option<ProxySsl<'a>> {
240        let v = self.find(TLV_SSL)?;
241        let client = v[0];
242        let verify = u32::from_be_bytes([v[1], v[2], v[3], v[4]]);
243        let mut ssl = ProxySsl {
244            client,
245            verified: verify == 0,
246            version: None,
247            common_name: None,
248            cipher: None,
249            signature_algorithm: None,
250            key_algorithm: None,
251        };
252        let mut rest = &v[5..];
253        while let Some((sub, more)) = split_tlv(rest) {
254            let text = str::from_utf8(sub.value).ok();
255            match sub.kind {
256                SSL_VERSION => ssl.version = text,
257                SSL_CN => ssl.common_name = text,
258                SSL_CIPHER => ssl.cipher = text,
259                SSL_SIG_ALG => ssl.signature_algorithm = text,
260                SSL_KEY_ALG => ssl.key_algorithm = text,
261                _ => {}
262            }
263            rest = more;
264        }
265        Some(ssl)
266    }
267
268    /// The network namespace (TLV `0x30`).
269    #[must_use]
270    pub fn network_namespace(&self) -> Option<&'a [u8]> {
271        self.find(TLV_NETNS)
272    }
273
274    /// Whether a CRC32C TLV was present and matched.
275    #[must_use]
276    pub fn crc_checked(&self) -> bool {
277        self.crc_checked
278    }
279
280    /// The facts net-io keeps after the header's bytes are gone (fixed arrays;
281    /// a value longer than its array is left out).
282    #[must_use]
283    pub fn to_facts(&self) -> ProxyFacts {
284        ProxyFacts::from_parts(
285            self.alpn(),
286            self.authority(),
287            self.unique_id(),
288            self.ssl().map(|s| s.client),
289        )
290    }
291}
292
293impl ProxyParser {
294    /// A parser accepting `versions`, refusing a v2 header whose body (after the
295    /// 16 fixed bytes) is longer than `v2_body_max`.
296    #[must_use]
297    pub fn new(versions: ProxyVersions, v2_body_max: u16) -> ProxyParser {
298        ProxyParser {
299            versions,
300            v2_body_max,
301            kind: Kind::Undecided,
302            scanned: 0,
303        }
304    }
305
306    /// Parses from `input`, which holds every byte received so far.
307    ///
308    /// # Errors
309    ///
310    /// [`ProxyError`]: the bytes are not an allowed header, or are malformed.
311    pub fn feed<'a>(&mut self, input: &'a [u8]) -> Result<ProxyProgress<'a>, ProxyError> {
312        if self.kind == Kind::Undecided {
313            let Some(&first) = input.first() else {
314                return Ok(ProxyProgress::NeedMore { at_least: 1 });
315            };
316            let v1 = matches!(self.versions, ProxyVersions::V1 | ProxyVersions::Both);
317            let v2 = matches!(self.versions, ProxyVersions::V2 | ProxyVersions::Both);
318            self.kind = match first {
319                b'P' if v1 => Kind::V1,
320                0x0D if v2 => Kind::V2,
321                _ => return Err(ProxyError::NotProxy),
322            };
323        }
324        match self.kind {
325            Kind::V1 => self.feed_v1(input),
326            _ => self.feed_v2(input),
327        }
328    }
329
330    fn feed_v1<'a>(&mut self, input: &'a [u8]) -> Result<ProxyProgress<'a>, ProxyError> {
331        let n = input.len().min(V1_PREFIX.len());
332        if input[..n] != V1_PREFIX[..n] {
333            return Err(ProxyError::NotProxy);
334        }
335        let limit = input.len().min(V1_MAX);
336        let start = self.scanned.min(limit);
337        let Some(lf) = input[start..limit].iter().position(|&b| b == b'\n') else {
338            if input.len() >= V1_MAX {
339                return Err(ProxyError::V1TooLong);
340            }
341            self.scanned = limit;
342            return Ok(ProxyProgress::NeedMore { at_least: 1 });
343        };
344        let lf = start + lf;
345        if lf == 0 || input[lf - 1] != b'\r' {
346            return Err(ProxyError::V1Syntax { at: offset(lf) });
347        }
348        let header = parse_v1_line(&input[..lf - 1])?;
349        Ok(ProxyProgress::Done {
350            header,
351            consumed: lf + 1,
352        })
353    }
354
355    fn feed_v2<'a>(&mut self, input: &'a [u8]) -> Result<ProxyProgress<'a>, ProxyError> {
356        let n = input.len().min(V2_SIGNATURE.len());
357        if input[..n] != V2_SIGNATURE[..n] {
358            return Err(ProxyError::NotProxy);
359        }
360        if input.len() < V2_FIXED {
361            return Ok(ProxyProgress::NeedMore {
362                at_least: V2_FIXED - input.len(),
363            });
364        }
365        let version = input[12] >> 4;
366        if version != 2 {
367            return Err(ProxyError::V2BadVersion);
368        }
369        let command = match input[12] & 0x0F {
370            0x0 => ProxyCommand::Local,
371            0x1 => ProxyCommand::Proxy,
372            _ => return Err(ProxyError::V2BadCommand),
373        };
374        let family = input[13];
375        let known = match family {
376            0x00 => Some((0, ProxyTransport::Unspecified)),
377            0x11 => Some((12, ProxyTransport::Stream)),
378            0x12 => Some((12, ProxyTransport::Datagram)),
379            0x21 => Some((36, ProxyTransport::Stream)),
380            0x22 => Some((36, ProxyTransport::Datagram)),
381            0x31 => Some((216, ProxyTransport::Stream)),
382            0x32 => Some((216, ProxyTransport::Datagram)),
383            _ => None,
384        };
385        // LOCAL: the receiver uses the real endpoints and ignores the family and
386        // the address block, as the specification says (section 2.2), so neither
387        // is checked; an unknown family is reported as unspecified.
388        let (address_len, transport) = match (known, command) {
389            (Some(k), _) => k,
390            (None, ProxyCommand::Local) => (0, ProxyTransport::Unspecified),
391            (None, ProxyCommand::Proxy) => return Err(ProxyError::V2BadFamily),
392        };
393        let declared = u16::from_be_bytes([input[14], input[15]]);
394        if declared > self.v2_body_max {
395            return Err(ProxyError::V2LengthTooLarge {
396                declared,
397                max: self.v2_body_max,
398            });
399        }
400        let total = V2_FIXED + usize::from(declared);
401        if input.len() < total {
402            return Ok(ProxyProgress::NeedMore {
403                at_least: total - input.len(),
404            });
405        }
406        let header = &input[..total];
407        let body = &header[V2_FIXED..];
408        let local = command == ProxyCommand::Local;
409        if body.len() < address_len && !local {
410            return Err(ProxyError::V2AddressTooShort);
411        }
412        // Where the TLVs start. A LOCAL header whose family is unknown or whose
413        // block is shorter than its family's addresses has no place where they
414        // could start: the whole body is the ignored block.
415        let tlv_at = if local && (known.is_none() || body.len() < address_len) {
416            body.len()
417        } else {
418            address_len
419        };
420        let (source, destination) = if local {
421            (None, None)
422        } else {
423            v2_addresses(family >> 4, &body[..address_len])
424        };
425        let tlv_bytes = &body[tlv_at..];
426        let crc_checked = check_tlvs(header, V2_FIXED + tlv_at)?;
427        Ok(ProxyProgress::Done {
428            header: ProxyHeader {
429                version: 2,
430                command,
431                transport,
432                source,
433                destination,
434                tlvs: Tlvs { rest: tlv_bytes },
435                crc_checked,
436            },
437            consumed: total,
438        })
439    }
440}
441
442/// A byte offset within a v1 line, which is at most 107 bytes.
443fn offset(at: usize) -> u8 {
444    u8::try_from(at).unwrap_or(u8::MAX)
445}
446
447/// One TLV from the front of `bytes`, or `None` when fewer than a whole TLV remain.
448fn split_tlv(bytes: &[u8]) -> Option<(Tlv<'_>, &[u8])> {
449    if bytes.len() < 3 {
450        return None;
451    }
452    let len = usize::from(u16::from_be_bytes([bytes[1], bytes[2]]));
453    let value = bytes.get(3..3 + len)?;
454    Some((
455        Tlv {
456            kind: bytes[0],
457            value,
458        },
459        &bytes[3 + len..],
460    ))
461}
462
463/// Walks every TLV of `header` (starting at `start`) and checks it ends exactly
464/// at the declared length; verifies CRC32C, the unique id, and the SSL TLV.
465/// Returns whether a checksum was verified.
466fn check_tlvs(header: &[u8], start: usize) -> Result<bool, ProxyError> {
467    let mut pos = start;
468    let mut crc_checked = false;
469    while pos < header.len() {
470        let rest = &header[pos..];
471        let Some((tlv, _)) = split_tlv(rest) else {
472            return Err(ProxyError::V2TlvOverrun);
473        };
474        let value_at = pos + 3;
475        match tlv.kind {
476            TLV_CRC32C => {
477                if tlv.value.len() != 4 {
478                    return Err(ProxyError::V2CrcMismatch);
479                }
480                let expected =
481                    u32::from_be_bytes([tlv.value[0], tlv.value[1], tlv.value[2], tlv.value[3]]);
482                let mut c = Crc32c::new();
483                c.update(&header[..value_at]);
484                c.update(&[0; 4]);
485                c.update(&header[value_at + 4..]);
486                if c.finish() != expected {
487                    return Err(ProxyError::V2CrcMismatch);
488                }
489                crc_checked = true;
490            }
491            TLV_UNIQUE_ID if tlv.value.len() > UNIQUE_ID_MAX => {
492                return Err(ProxyError::V2UniqueIdTooLong);
493            }
494            TLV_SSL => check_ssl(tlv.value)?,
495            _ => {}
496        }
497        pos = value_at + tlv.value.len();
498    }
499    Ok(crc_checked)
500}
501
502fn check_ssl(value: &[u8]) -> Result<(), ProxyError> {
503    if value.len() < 5 {
504        return Err(ProxyError::V2SslMalformed);
505    }
506    let mut rest = &value[5..];
507    while !rest.is_empty() {
508        match split_tlv(rest) {
509            Some((_, more)) => rest = more,
510            None => return Err(ProxyError::V2SslMalformed),
511        }
512    }
513    Ok(())
514}
515
516fn v2_addresses(family: u8, block: &[u8]) -> (Option<ProxyAddress<'_>>, Option<ProxyAddress<'_>>) {
517    let port = |b: &[u8]| u16::from_be_bytes([b[0], b[1]]);
518    match family {
519        0x1 => {
520            let src = Ipv4Addr::new(block[0], block[1], block[2], block[3]);
521            let dst = Ipv4Addr::new(block[4], block[5], block[6], block[7]);
522            (
523                Some(ProxyAddress::Ip(SocketAddr::new(
524                    IpAddr::V4(src),
525                    port(&block[8..]),
526                ))),
527                Some(ProxyAddress::Ip(SocketAddr::new(
528                    IpAddr::V4(dst),
529                    port(&block[10..]),
530                ))),
531            )
532        }
533        0x2 => {
534            let mut s = [0u8; 16];
535            let mut d = [0u8; 16];
536            s.copy_from_slice(&block[..16]);
537            d.copy_from_slice(&block[16..32]);
538            (
539                Some(ProxyAddress::Ip(SocketAddr::new(
540                    IpAddr::V6(Ipv6Addr::from(s)),
541                    port(&block[32..]),
542                ))),
543                Some(ProxyAddress::Ip(SocketAddr::new(
544                    IpAddr::V6(Ipv6Addr::from(d)),
545                    port(&block[34..]),
546                ))),
547            )
548        }
549        0x3 => (
550            Some(ProxyAddress::Unix(trim_zeros(&block[..108]))),
551            Some(ProxyAddress::Unix(trim_zeros(&block[108..216]))),
552        ),
553        _ => (None, None),
554    }
555}
556
557fn trim_zeros(path: &[u8]) -> &[u8] {
558    let end = path.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1);
559    &path[..end]
560}
561
562/// Parses a v1 line without its CRLF.
563fn parse_v1_line(line: &[u8]) -> Result<ProxyHeader<'static>, ProxyError> {
564    let rest = &line[V1_PREFIX.len()..];
565    let base = V1_PREFIX.len();
566    let empty = Tlvs { rest: &[] };
567    if let Some(after) = rest.strip_prefix(b"UNKNOWN") {
568        // The receiver ignores everything after UNKNOWN on the line.
569        if after.is_empty() || after[0] == b' ' {
570            return Ok(ProxyHeader {
571                version: 1,
572                command: ProxyCommand::Proxy,
573                transport: ProxyTransport::Unspecified,
574                source: None,
575                destination: None,
576                tlvs: empty,
577                crc_checked: false,
578            });
579        }
580        return Err(ProxyError::V1Syntax {
581            at: offset(base + 7),
582        });
583    }
584    let mut fields = [&[][..]; 5];
585    let mut count = 0;
586    let mut at = base;
587    for field in rest.split(|&b| b == b' ') {
588        if field.is_empty() || count == 5 {
589            return Err(ProxyError::V1Syntax { at: offset(at) });
590        }
591        fields[count] = field;
592        count += 1;
593        at += field.len() + 1;
594    }
595    if count != 5 {
596        return Err(ProxyError::V1Syntax {
597            at: offset(line.len()),
598        });
599    }
600    let v6 = match fields[0] {
601        b"TCP4" => false,
602        b"TCP6" => true,
603        _ => return Err(ProxyError::V1Syntax { at: offset(base) }),
604    };
605    let address = |text: &[u8]| -> Result<IpAddr, ProxyError> {
606        let mine = if v6 {
607            parse_ipv6(text).map(IpAddr::V6)
608        } else {
609            parse_ipv4(text).map(IpAddr::V4)
610        };
611        if let Some(ip) = mine {
612            return Ok(ip);
613        }
614        // Only a failure pays for the other family, to name the error.
615        let other = if v6 {
616            parse_ipv4(text).is_some()
617        } else {
618            parse_ipv6(text).is_some()
619        };
620        Err(if other {
621            ProxyError::FamilyMismatch
622        } else {
623            ProxyError::V1BadAddress
624        })
625    };
626    let src = address(fields[1])?;
627    let dst = address(fields[2])?;
628    let sport = parse_port(fields[3]).ok_or(ProxyError::V1BadPort)?;
629    let dport = parse_port(fields[4]).ok_or(ProxyError::V1BadPort)?;
630    Ok(ProxyHeader {
631        version: 1,
632        command: ProxyCommand::Proxy,
633        transport: ProxyTransport::Stream,
634        source: Some(ProxyAddress::Ip(SocketAddr::new(src, sport))),
635        destination: Some(ProxyAddress::Ip(SocketAddr::new(dst, dport))),
636        tlvs: empty,
637        crc_checked: false,
638    })
639}
640
641/// A decimal port, 0 to 65535, no sign and no leading zeros.
642fn parse_port(text: &[u8]) -> Option<u16> {
643    decimal(text, 5).and_then(|v| u16::try_from(v).ok())
644}
645
646/// Decimal digits only, at most `max_digits`, no leading zero unless the value is 0.
647fn decimal(text: &[u8], max_digits: usize) -> Option<u32> {
648    if text.is_empty() || text.len() > max_digits || (text.len() > 1 && text[0] == b'0') {
649        return None;
650    }
651    text.iter().try_fold(0u32, |acc, &b| {
652        b.is_ascii_digit().then(|| acc * 10 + u32::from(b - b'0'))
653    })
654}
655
656/// A dotted-quad IPv4 address: four decimal octets, no leading zeros.
657fn parse_ipv4(text: &[u8]) -> Option<Ipv4Addr> {
658    let mut octets = [0u8; 4];
659    let mut n = 0;
660    for part in text.split(|&b| b == b'.') {
661        if n == 4 {
662            return None;
663        }
664        octets[n] = u8::try_from(decimal(part, 3)?).ok()?;
665        n += 1;
666    }
667    (n == 4).then(|| Ipv4Addr::from(octets))
668}
669
670/// An IPv6 address in RFC 4291 text form: eight groups of one to four hex
671/// digits, at most one `::`, optionally ending in a dotted-quad IPv4 address.
672/// No zone index.
673fn parse_ipv6(text: &[u8]) -> Option<Ipv6Addr> {
674    let (head, tail, compressed) = match find_double_colon(text) {
675        Some(i) => (&text[..i], &text[i + 2..], true),
676        None => (text, &[][..], false),
677    };
678    if compressed && find_double_colon(tail).is_some() {
679        return None;
680    }
681    let mut groups = [0u16; 8];
682    // Groups before `::` (or all of them, when there is no `::`).
683    let front = groups_into(head, &mut groups, 0, !compressed)?;
684    if !compressed {
685        return (front == 8).then(|| Ipv6Addr::from(groups));
686    }
687    let mut back = [0u16; 8];
688    let n_back = groups_into(tail, &mut back, 0, true)?;
689    if front + n_back > 7 {
690        return None;
691    }
692    groups[8 - n_back..].copy_from_slice(&back[..n_back]);
693    Some(Ipv6Addr::from(groups))
694}
695
696fn find_double_colon(text: &[u8]) -> Option<usize> {
697    text.windows(2).position(|w| w == b"::")
698}
699
700/// Parses `:`-separated groups of `text` into `out` from index `at`; an IPv4
701/// tail (two groups) is allowed when `last` says this part ends the address.
702/// Returns the next free index.
703fn groups_into(text: &[u8], out: &mut [u16; 8], mut at: usize, last: bool) -> Option<usize> {
704    if text.is_empty() {
705        return Some(at);
706    }
707    let mut parts = text.split(|&b| b == b':').peekable();
708    while let Some(part) = parts.next() {
709        let is_last = parts.peek().is_none();
710        if is_last && last && part.contains(&b'.') {
711            let v4 = parse_ipv4(part)?.octets();
712            if at + 2 > 8 {
713                return None;
714            }
715            out[at] = u16::from_be_bytes([v4[0], v4[1]]);
716            out[at + 1] = u16::from_be_bytes([v4[2], v4[3]]);
717            at += 2;
718            continue;
719        }
720        if part.is_empty() || part.len() > 4 || at >= 8 {
721            return None;
722        }
723        let mut v = 0u16;
724        for &b in part {
725            let d = (b as char).to_digit(16)?;
726            v = (v << 4) | u16::try_from(d).ok()?;
727        }
728        out[at] = v;
729        at += 1;
730    }
731    Some(at)
732}
733
734/// Writes a v1 header for a proxied TCP connection; returns its length (at most 107).
735/// For a proxy that speaks PROXY to its backends.
736///
737/// ```
738/// let mut out = [0u8; 107];
739/// let n = net_io::encode_v1(
740///     "192.0.2.1:5000".parse().unwrap(),
741///     "192.0.2.2:80".parse().unwrap(),
742///     &mut out,
743/// )?;
744/// assert_eq!(&out[..n], b"PROXY TCP4 192.0.2.1 192.0.2.2 5000 80\r\n");
745/// # Ok::<(), net_io::ProxyError>(())
746/// ```
747///
748/// # Errors
749///
750/// `FamilyMismatch` when the two addresses differ in family, `OutputTooSmall`.
751pub fn encode_v1(
752    source: SocketAddr,
753    destination: SocketAddr,
754    out: &mut [u8],
755) -> Result<usize, ProxyError> {
756    let family = match (source, destination) {
757        (SocketAddr::V4(_), SocketAddr::V4(_)) => "TCP4",
758        (SocketAddr::V6(_), SocketAddr::V6(_)) => "TCP6",
759        _ => return Err(ProxyError::FamilyMismatch),
760    };
761    let line = format!(
762        "PROXY {family} {} {} {} {}\r\n",
763        source.ip(),
764        destination.ip(),
765        source.port(),
766        destination.port()
767    );
768    let need = line.len();
769    let target = out
770        .get_mut(..need)
771        .ok_or(ProxyError::OutputTooSmall { need })?;
772    target.copy_from_slice(line.as_bytes());
773    Ok(need)
774}
775
776/// Writes a v2 header; returns its length. `None` for either address sends `UNSPEC`,
777/// which is what `ProxyCommand::Local` means. `with_crc` adds a CRC32C TLV.
778///
779/// ```
780/// use net_io::{ProxyCommand, ProxyParser, ProxyProgress, ProxyVersions};
781/// let mut out = [0u8; 64];
782/// let n = net_io::encode_v2(
783///     ProxyCommand::Proxy,
784///     Some("192.0.2.1:5000".parse().unwrap()),
785///     Some("192.0.2.2:80".parse().unwrap()),
786///     &[],
787///     true,
788///     &mut out,
789/// )?;
790/// assert!(n > 16);
791/// # Ok::<(), net_io::ProxyError>(())
792/// ```
793///
794/// # Errors
795///
796/// `FamilyMismatch`, `OutputTooSmall`, `V2LengthTooLarge` when it cannot fit 65,535 bytes.
797pub fn encode_v2(
798    command: ProxyCommand,
799    source: Option<SocketAddr>,
800    destination: Option<SocketAddr>,
801    tlvs: &[Tlv<'_>],
802    with_crc: bool,
803    out: &mut [u8],
804) -> Result<usize, ProxyError> {
805    const STREAM: u8 = 1;
806    let (family, address_len) = match (source, destination) {
807        (Some(SocketAddr::V4(_)), Some(SocketAddr::V4(_))) => (0x10 | STREAM, 12),
808        (Some(SocketAddr::V6(_)), Some(SocketAddr::V6(_))) => (0x20 | STREAM, 36),
809        (None, None) => (0, 0),
810        _ => return Err(ProxyError::FamilyMismatch),
811    };
812    let tlv_len: usize = tlvs.iter().map(|t| 3 + t.value.len()).sum();
813    let crc_len = if with_crc { 7 } else { 0 };
814    let body = address_len + tlv_len + crc_len;
815    let declared = u16::try_from(body).map_err(|_| ProxyError::V2LengthTooLarge {
816        declared: u16::MAX,
817        max: u16::MAX,
818    })?;
819    let need = V2_FIXED + body;
820    let frame = out
821        .get_mut(..need)
822        .ok_or(ProxyError::OutputTooSmall { need })?;
823    frame[..12].copy_from_slice(&V2_SIGNATURE);
824    frame[12] = match command {
825        ProxyCommand::Proxy => 0x21,
826        ProxyCommand::Local => 0x20,
827    };
828    frame[13] = family;
829    frame[14..16].copy_from_slice(&declared.to_be_bytes());
830    let mut at = V2_FIXED;
831    match (source, destination) {
832        (Some(SocketAddr::V4(s)), Some(SocketAddr::V4(d))) => {
833            frame[at..at + 4].copy_from_slice(&s.ip().octets());
834            frame[at + 4..at + 8].copy_from_slice(&d.ip().octets());
835            frame[at + 8..at + 10].copy_from_slice(&s.port().to_be_bytes());
836            frame[at + 10..at + 12].copy_from_slice(&d.port().to_be_bytes());
837            at += 12;
838        }
839        (Some(SocketAddr::V6(s)), Some(SocketAddr::V6(d))) => {
840            frame[at..at + 16].copy_from_slice(&s.ip().octets());
841            frame[at + 16..at + 32].copy_from_slice(&d.ip().octets());
842            frame[at + 32..at + 34].copy_from_slice(&s.port().to_be_bytes());
843            frame[at + 34..at + 36].copy_from_slice(&d.port().to_be_bytes());
844            at += 36;
845        }
846        _ => {}
847    }
848    for t in tlvs {
849        let len = t.value.len() as u16;
850        frame[at] = t.kind;
851        frame[at + 1..at + 3].copy_from_slice(&len.to_be_bytes());
852        frame[at + 3..at + 3 + t.value.len()].copy_from_slice(t.value);
853        at += 3 + t.value.len();
854    }
855    if with_crc {
856        frame[at] = TLV_CRC32C;
857        frame[at + 1..at + 3].copy_from_slice(&4u16.to_be_bytes());
858        frame[at + 3..at + 7].fill(0);
859        let mut crc = Crc32c::new();
860        crc.update(frame);
861        let value = crc.finish().to_be_bytes();
862        frame[at + 3..at + 7].copy_from_slice(&value);
863    }
864    Ok(need)
865}
866
867#[cfg(test)]
868mod tests {
869    use super::*;
870
871    fn done(p: &mut ProxyParser, bytes: &[u8]) -> (ProxyHeader<'static>, usize) {
872        let bytes: &'static [u8] = Box::leak(bytes.to_vec().into_boxed_slice());
873        match p.feed(bytes).unwrap() {
874            ProxyProgress::Done { header, consumed } => (header, consumed),
875            ProxyProgress::NeedMore { at_least } => panic!("need {at_least} more"),
876        }
877    }
878
879    fn v1(line: &str) -> Result<ProxyHeader<'static>, ProxyError> {
880        let bytes: &'static [u8] = Box::leak(line.as_bytes().to_vec().into_boxed_slice());
881        match ProxyParser::new(ProxyVersions::Both, 1024).feed(bytes)? {
882            ProxyProgress::Done { header, .. } => Ok(header),
883            ProxyProgress::NeedMore { .. } => panic!("incomplete: {line:?}"),
884        }
885    }
886
887    /// Builds a v2 header: command, family, address block, TLVs; optionally a CRC.
888    fn v2(command: u8, family: u8, block: &[u8], tlvs: &[(u8, &[u8])], crc: bool) -> Vec<u8> {
889        let mut body = block.to_vec();
890        for (kind, value) in tlvs {
891            body.push(*kind);
892            body.extend_from_slice(&u16::try_from(value.len()).unwrap().to_be_bytes());
893            body.extend_from_slice(value);
894        }
895        let crc_at = if crc {
896            body.extend_from_slice(&[TLV_CRC32C, 0, 4, 0, 0, 0, 0]);
897            Some(V2_FIXED + body.len() - 4)
898        } else {
899            None
900        };
901        let mut h = V2_SIGNATURE.to_vec();
902        h.push(0x20 | command);
903        h.push(family);
904        h.extend_from_slice(&u16::try_from(body.len()).unwrap().to_be_bytes());
905        h.extend_from_slice(&body);
906        if let Some(at) = crc_at {
907            let sum = crate::crc32c::crc32c(&h);
908            h[at..at + 4].copy_from_slice(&sum.to_be_bytes());
909        }
910        h
911    }
912
913    fn ipv4_block() -> Vec<u8> {
914        let mut b = vec![192, 0, 2, 1, 198, 51, 100, 2];
915        b.extend_from_slice(&51000u16.to_be_bytes());
916        b.extend_from_slice(&443u16.to_be_bytes());
917        b
918    }
919
920    #[test]
921    fn test_v1_tcp4_and_rest_is_data() {
922        let mut p = ProxyParser::new(ProxyVersions::Both, 1024);
923        let (h, consumed) = done(
924            &mut p,
925            b"PROXY TCP4 192.0.2.1 198.51.100.2 51000 443\r\nGET",
926        );
927        assert_eq!(h.version, 1);
928        assert_eq!(
929            h.source,
930            Some(ProxyAddress::Ip("192.0.2.1:51000".parse().unwrap()))
931        );
932        assert_eq!(
933            h.destination,
934            Some(ProxyAddress::Ip("198.51.100.2:443".parse().unwrap()))
935        );
936        assert_eq!(consumed, 45);
937    }
938
939    #[test]
940    fn test_v1_tcp6_unknown_and_mapped() {
941        let h = v1("PROXY TCP6 2001:db8::1 ::ffff:192.0.2.1 1 65535\r\n").unwrap();
942        assert_eq!(h.source.unwrap().to_string(), "[2001:db8::1]:1");
943        let h = v1("PROXY UNKNOWN\r\n").unwrap();
944        assert!(h.source.is_none());
945        let h = v1("PROXY UNKNOWN anything at all 1 2\r\n").unwrap();
946        assert_eq!(h.transport, ProxyTransport::Unspecified);
947    }
948
949    #[test]
950    fn test_v1_strict_grammar() {
951        use ProxyError::*;
952        let bad = [
953            ("PROXY TCP4  192.0.2.1 198.51.100.2 1 2\r\n", "double space"),
954            (
955                "PROXY TCP4 192.0.2.1 198.51.100.2 1 2 \r\n",
956                "trailing space",
957            ),
958            ("PROXY TCP4 192.0.2.1 198.51.100.2 1\r\n", "missing port"),
959            ("PROXY TCP5 192.0.2.1 198.51.100.2 1 2\r\n", "protocol"),
960            ("PROXY UNKNOWNX\r\n", "unknown suffix"),
961        ];
962        for (line, why) in bad {
963            assert!(
964                matches!(v1(line), Err(V1Syntax { .. })),
965                "{why}: {:?}",
966                v1(line)
967            );
968        }
969        assert_eq!(
970            v1("PROXY TCP4 192.0.2.01 198.51.100.2 1 2\r\n").unwrap_err(),
971            V1BadAddress
972        );
973        assert_eq!(
974            v1("PROXY TCP4 256.0.2.1 198.51.100.2 1 2\r\n").unwrap_err(),
975            V1BadAddress
976        );
977        assert_eq!(
978            v1("PROXY TCP4 192.0.2.1 198.51.100.2 01 2\r\n").unwrap_err(),
979            V1BadPort
980        );
981        assert_eq!(
982            v1("PROXY TCP4 192.0.2.1 198.51.100.2 +1 2\r\n").unwrap_err(),
983            V1BadPort
984        );
985        assert_eq!(
986            v1("PROXY TCP4 192.0.2.1 198.51.100.2 65536 2\r\n").unwrap_err(),
987            V1BadPort
988        );
989        assert_eq!(
990            v1("PROXY TCP4 2001:db8::1 198.51.100.2 1 2\r\n").unwrap_err(),
991            FamilyMismatch
992        );
993        assert_eq!(
994            v1("PROXY TCP6 192.0.2.1 ::1 1 2\r\n").unwrap_err(),
995            FamilyMismatch
996        );
997        assert!(matches!(
998            ProxyParser::new(ProxyVersions::Both, 1024).feed(b"PROXY TCP4 1.2.3.4 1.2.3.4 1 2\n"),
999            Err(V1Syntax { .. })
1000        ));
1001    }
1002
1003    /// Edge case 13: 107 bytes without a line end.
1004    #[test]
1005    fn test_v1_too_long() {
1006        let mut line = b"PROXY UNKNOWN ".to_vec();
1007        line.resize(107, b'x');
1008        let r = ProxyParser::new(ProxyVersions::V1, 1024).feed(&line);
1009        assert_eq!(r.unwrap_err(), ProxyError::V1TooLong);
1010        let mut ok = b"PROXY UNKNOWN ".to_vec();
1011        ok.resize(105, b'x');
1012        ok.extend_from_slice(b"\r\n");
1013        assert!(matches!(
1014            ProxyParser::new(ProxyVersions::V1, 1024).feed(&ok),
1015            Ok(ProxyProgress::Done { consumed: 107, .. })
1016        ));
1017    }
1018
1019    #[test]
1020    fn test_not_proxy_and_version_filters() {
1021        let mut p = ProxyParser::new(ProxyVersions::Both, 1024);
1022        assert_eq!(p.feed(b"GET / HTTP/1.1").unwrap_err(), ProxyError::NotProxy);
1023        assert_eq!(
1024            ProxyParser::new(ProxyVersions::Both, 1024)
1025                .feed(b"PROXX")
1026                .unwrap_err(),
1027            ProxyError::NotProxy
1028        );
1029        let v2h = v2(1, 0x11, &ipv4_block(), &[], false);
1030        assert_eq!(
1031            ProxyParser::new(ProxyVersions::V1, 1024)
1032                .feed(&v2h)
1033                .unwrap_err(),
1034            ProxyError::NotProxy
1035        );
1036        assert_eq!(
1037            ProxyParser::new(ProxyVersions::V2, 1024)
1038                .feed(b"PROXY TCP4")
1039                .unwrap_err(),
1040            ProxyError::NotProxy
1041        );
1042    }
1043
1044    #[test]
1045    fn test_v2_ipv4_tlvs_and_crc() {
1046        let h = v2(
1047            1,
1048            0x11,
1049            &ipv4_block(),
1050            &[
1051                (TLV_ALPN, b"h2"),
1052                (TLV_NOOP, b"pad"),
1053                (TLV_AUTHORITY, b"example.com"),
1054                (TLV_UNIQUE_ID, b"id-1"),
1055                (
1056                    TLV_SSL,
1057                    &[
1058                        0x07,
1059                        0,
1060                        0,
1061                        0,
1062                        0,
1063                        SSL_VERSION,
1064                        0,
1065                        7,
1066                        b'T',
1067                        b'L',
1068                        b'S',
1069                        b'v',
1070                        b'1',
1071                        b'.',
1072                        b'3',
1073                        SSL_CN,
1074                        0,
1075                        3,
1076                        b'b',
1077                        b'o',
1078                        b'b',
1079                    ],
1080                ),
1081                (0xE0, b"custom"),
1082            ],
1083            true,
1084        );
1085        let mut p = ProxyParser::new(ProxyVersions::Both, 1024);
1086        let (header, consumed) = done(&mut p, &h);
1087        assert_eq!(consumed, h.len());
1088        assert_eq!(header.command, ProxyCommand::Proxy);
1089        assert_eq!(header.source.unwrap().to_string(), "192.0.2.1:51000");
1090        assert_eq!(header.alpn(), Some(&b"h2"[..]));
1091        assert_eq!(header.authority(), Some("example.com"));
1092        assert_eq!(header.unique_id(), Some(&b"id-1"[..]));
1093        assert!(header.crc_checked());
1094        let ssl = header.ssl().unwrap();
1095        assert_eq!(
1096            (ssl.client, ssl.verified, ssl.version, ssl.common_name),
1097            (7, true, Some("TLSv1.3"), Some("bob"))
1098        );
1099        assert!({ header.tlvs }.all(|t| t.kind != TLV_NOOP), "NOOP skipped");
1100        assert!({ header.tlvs }.any(|t| t.kind == 0xE0 && t.value == b"custom"));
1101        let facts = header.to_facts();
1102        assert_eq!(facts.alpn(), Some(&b"h2"[..]));
1103        assert_eq!(facts.authority(), Some("example.com"));
1104        assert_eq!(facts.ssl_client(), Some(7));
1105    }
1106
1107    #[test]
1108    fn test_v2_ipv6_unix_local_unspec() {
1109        let mut block = vec![0u8; 36];
1110        block[15] = 1;
1111        block[31] = 2;
1112        block[32..34].copy_from_slice(&80u16.to_be_bytes());
1113        let h = v2(1, 0x21, &block, &[], false);
1114        let (hd, _) = done(&mut ProxyParser::new(ProxyVersions::V2, 1024), &h);
1115        assert_eq!(hd.source.unwrap().to_string(), "[::1]:80");
1116        let mut unix = vec![0u8; 216];
1117        unix[..9].copy_from_slice(b"/run/a.sk");
1118        let h = v2(1, 0x31, &unix, &[], false);
1119        let (hd, _) = done(&mut ProxyParser::new(ProxyVersions::V2, 1024), &h);
1120        assert_eq!(hd.source, Some(ProxyAddress::Unix(b"/run/a.sk")));
1121        let h = v2(0, 0x11, &ipv4_block(), &[], false);
1122        let (hd, _) = done(&mut ProxyParser::new(ProxyVersions::V2, 1024), &h);
1123        assert_eq!((hd.command, hd.source), (ProxyCommand::Local, None));
1124        let h = v2(1, 0x00, &[], &[], false);
1125        let (hd, _) = done(&mut ProxyParser::new(ProxyVersions::V2, 1024), &h);
1126        assert_eq!(
1127            (hd.transport, hd.source),
1128            (ProxyTransport::Unspecified, None)
1129        );
1130    }
1131
1132    /// A LOCAL header is accepted whatever its family byte and however short its
1133    /// address block: the receiver uses the real endpoints and ignores both.
1134    #[test]
1135    fn test_v2_local_ignores_the_family_and_the_address_block() {
1136        for (family, body) in [
1137            (0x11, &[][..]),
1138            (0x13, &[][..]),
1139            (0x21, &[0u8; 5][..]),
1140            (0xFF, &[1, 2, 3][..]),
1141        ] {
1142            let h = v2(0, family, body, &[], false);
1143            let (hd, consumed) = done(&mut ProxyParser::new(ProxyVersions::V2, 1024), &h);
1144            assert_eq!((hd.command, hd.source), (ProxyCommand::Local, None));
1145            assert_eq!(hd.destination, None);
1146            assert_eq!(consumed, h.len());
1147            assert_eq!(hd.tlvs.count(), 0, "family {family:#x}");
1148        }
1149        // A whole address block of a known family: its TLVs are still read.
1150        let h = v2(0, 0x11, &ipv4_block(), &[(TLV_ALPN, b"h2")], false);
1151        let (hd, _) = done(&mut ProxyParser::new(ProxyVersions::V2, 1024), &h);
1152        assert_eq!(hd.tlvs.count(), 1);
1153        // PROXY keeps every check.
1154        let feed = |h: &[u8]| ProxyParser::new(ProxyVersions::V2, 64).feed(h).map(|_| ());
1155        assert_eq!(
1156            feed(&v2(1, 0x13, &[], &[], false)).unwrap_err(),
1157            ProxyError::V2BadFamily
1158        );
1159        assert_eq!(
1160            feed(&v2(1, 0x11, &[], &[], false)).unwrap_err(),
1161            ProxyError::V2AddressTooShort
1162        );
1163    }
1164
1165    #[test]
1166    fn test_v2_errors() {
1167        use ProxyError::*;
1168        let feed = |h: &[u8]| ProxyParser::new(ProxyVersions::V2, 64).feed(h).map(|_| ());
1169        let mut h = v2(1, 0x11, &ipv4_block(), &[], false);
1170        h[12] = 0x11;
1171        assert_eq!(feed(&h).unwrap_err(), V2BadVersion);
1172        let mut h = v2(1, 0x11, &ipv4_block(), &[], false);
1173        h[12] = 0x22;
1174        assert_eq!(feed(&h).unwrap_err(), V2BadCommand);
1175        let mut h = v2(1, 0x11, &ipv4_block(), &[], false);
1176        h[13] = 0x13;
1177        assert_eq!(feed(&h).unwrap_err(), V2BadFamily);
1178        let big = v2(1, 0x11, &ipv4_block(), &[(0xE0, &[0u8; 100])], false);
1179        assert_eq!(
1180            feed(&big).unwrap_err(),
1181            V2LengthTooLarge {
1182                declared: 115,
1183                max: 64
1184            }
1185        );
1186        let short = v2(1, 0x21, &[0u8; 20], &[], false);
1187        assert_eq!(feed(&short).unwrap_err(), V2AddressTooShort);
1188        let mut over = v2(1, 0x11, &ipv4_block(), &[(0xE0, b"abc")], false);
1189        let n = over.len();
1190        over[n - 4] = 9; // TLV length runs past the end
1191        assert_eq!(feed(&over).unwrap_err(), V2TlvOverrun);
1192        let mut crc = v2(1, 0x11, &ipv4_block(), &[(TLV_ALPN, b"h2")], true);
1193        let n = crc.len();
1194        crc[n - 1] ^= 1;
1195        assert_eq!(feed(&crc).unwrap_err(), V2CrcMismatch);
1196        let long_id = vec![b'i'; 129];
1197        let h = v2(1, 0x11, &ipv4_block(), &[(TLV_UNIQUE_ID, &long_id)], false);
1198        assert_eq!(
1199            ProxyParser::new(ProxyVersions::V2, 1024)
1200                .feed(&h)
1201                .map(|_| ())
1202                .unwrap_err(),
1203            V2UniqueIdTooLong
1204        );
1205        let h = v2(1, 0x11, &ipv4_block(), &[(TLV_SSL, &[1, 0, 0])], false);
1206        assert_eq!(feed(&h).unwrap_err(), V2SslMalformed);
1207    }
1208
1209    /// Edge case 14: a v2 header split across 12 segments.
1210    #[test]
1211    fn test_v2_split_into_segments_waits_then_succeeds() {
1212        let mut h = v2(
1213            1,
1214            0x11,
1215            &ipv4_block(),
1216            &[(TLV_AUTHORITY, b"a.example")],
1217            true,
1218        );
1219        h.extend_from_slice(b"DATA");
1220        let total = h.len() - 4;
1221        let mut p = ProxyParser::new(ProxyVersions::Both, 1024);
1222        let step = h.len().div_ceil(12);
1223        let mut have = 0;
1224        loop {
1225            have = (have + step).min(h.len());
1226            match p.feed(&h[..have]).unwrap() {
1227                ProxyProgress::NeedMore { at_least } => assert!(at_least > 0 && have < h.len()),
1228                ProxyProgress::Done { consumed, .. } => {
1229                    assert_eq!(consumed, total);
1230                    break;
1231                }
1232            }
1233        }
1234    }
1235
1236    /// Edge cases 15 and 16: the header and data in one segment, and a second
1237    /// header is application data.
1238    #[test]
1239    fn test_second_header_is_data() {
1240        let two = b"PROXY UNKNOWN\r\nPROXY UNKNOWN\r\n";
1241        let mut p = ProxyParser::new(ProxyVersions::V1, 1024);
1242        let (_, consumed) = done(&mut p, two);
1243        assert_eq!(&two[consumed..], b"PROXY UNKNOWN\r\n");
1244    }
1245
1246    /// Property: every split of a valid header gives the same result as the whole.
1247    #[test]
1248    fn prop_every_split_point_agrees() {
1249        let headers: Vec<Vec<u8>> = vec![
1250            b"PROXY TCP6 2001:db8:0:0:1:0:0:1 ::ffff:10.0.0.1 1024 8080\r\n".to_vec(),
1251            v2(
1252                1,
1253                0x11,
1254                &ipv4_block(),
1255                &[(TLV_ALPN, b"http/1.1"), (TLV_UNIQUE_ID, b"u")],
1256                true,
1257            ),
1258        ];
1259        for h in headers {
1260            for split in 0..h.len() {
1261                let mut p = ProxyParser::new(ProxyVersions::Both, 1024);
1262                if split > 0 {
1263                    assert!(
1264                        matches!(p.feed(&h[..split]).unwrap(), ProxyProgress::NeedMore { .. }),
1265                        "split {split}"
1266                    );
1267                }
1268                match p.feed(&h).unwrap() {
1269                    ProxyProgress::Done { consumed, .. } => assert_eq!(consumed, h.len()),
1270                    ProxyProgress::NeedMore { .. } => {
1271                        panic!("whole header incomplete at split {split}")
1272                    }
1273                }
1274            }
1275        }
1276    }
1277
1278    /// Property: random bytes never panic, and a header is never longer than the input.
1279    #[test]
1280    fn prop_random_input_never_panics() {
1281        use crate::testing::Gen;
1282        let mut g = Gen::new(0x9F0C_7E11);
1283        for _ in 0..if cfg!(miri) { 200 } else { 50_000 } {
1284            let len = g.below(300) as usize;
1285            let mut bytes: Vec<u8> = (0..len).map(|_| g.next_u64() as u8).collect();
1286            match g.below(3) {
1287                0 if len >= 12 => bytes[..12].copy_from_slice(&V2_SIGNATURE),
1288                1 if len >= 6 => bytes[..6].copy_from_slice(V1_PREFIX),
1289                _ => {}
1290            }
1291            let mut p = ProxyParser::new(ProxyVersions::Both, u16::MAX);
1292            if let Ok(ProxyProgress::Done { consumed, header }) = p.feed(&bytes) {
1293                assert!(consumed <= bytes.len());
1294                let _ = (header.alpn(), header.ssl(), header.tlvs.count());
1295            }
1296        }
1297    }
1298
1299    /// Property: the IPv6 grammar accepts only what std accepts, with the same value,
1300    /// and accepts every address std prints.
1301    #[test]
1302    fn prop_ipv6_grammar_matches_std() {
1303        use crate::testing::Gen;
1304        let mut g = Gen::new(0x1FE6_0001);
1305        let alphabet = b"0123456789abcdefABCDEF:.";
1306        for _ in 0..if cfg!(miri) { 200 } else { 100_000 } {
1307            let len = 1 + g.below(40) as usize;
1308            let text: Vec<u8> = (0..len)
1309                .map(|_| alphabet[g.below(alphabet.len() as u64) as usize])
1310                .collect();
1311            if let Some(ours) = parse_ipv6(&text) {
1312                let s = str::from_utf8(&text).unwrap();
1313                assert_eq!(s.parse::<Ipv6Addr>().ok(), Some(ours), "{s}");
1314            }
1315        }
1316        for _ in 0..if cfg!(miri) { 200 } else { 20_000 } {
1317            let mut b = [0u8; 16];
1318            for x in &mut b {
1319                // Runs of zeros, so `::` forms appear.
1320                *x = if g.chance(2) { 0 } else { g.next_u64() as u8 };
1321            }
1322            let a = Ipv6Addr::from(b);
1323            assert_eq!(parse_ipv6(a.to_string().as_bytes()), Some(a), "{a}");
1324        }
1325        for (s, ok) in [
1326            ("::", true),
1327            ("::1", true),
1328            ("1::", true),
1329            ("1:2:3:4:5:6:7:8", true),
1330            ("1:2:3:4:5:6:7::", true),
1331            ("1:2:3:4:5:6:1.2.3.4", true),
1332            (":1", false),
1333            ("1:", false),
1334            ("1:::2", false),
1335            ("1::2::3", false),
1336            ("1:2:3:4:5:6:7:8:9", false),
1337            ("12345::", false),
1338            ("::1.2.3", false),
1339            ("fe80::1%eth0", false),
1340        ] {
1341            assert_eq!(parse_ipv6(s.as_bytes()).is_some(), ok, "{s}");
1342        }
1343    }
1344
1345    #[test]
1346    fn test_ipv4_grammar() {
1347        for (s, ok) in [
1348            ("0.0.0.0", true),
1349            ("255.255.255.255", true),
1350            ("1.2.3.04", false),
1351            ("1.2.3", false),
1352            ("1.2.3.4.5", false),
1353            ("1.2.3.256", false),
1354            ("1..3.4", false),
1355            (" 1.2.3.4", false),
1356        ] {
1357            assert_eq!(parse_ipv4(s.as_bytes()).is_some(), ok, "{s}");
1358        }
1359    }
1360
1361    #[test]
1362    fn test_encoders_round_trip_through_the_parser() {
1363        let s: SocketAddr = "[2001:db8::1]:5000".parse().unwrap();
1364        let d: SocketAddr = "[2001:db8::2]:443".parse().unwrap();
1365        let mut out = [0u8; 256];
1366        let n = encode_v1(s, d, &mut out).unwrap();
1367        let mut p = ProxyParser::new(ProxyVersions::Both, 1024);
1368        match p.feed(&out[..n]).unwrap() {
1369            ProxyProgress::Done { header, consumed } => {
1370                assert_eq!(consumed, n);
1371                assert_eq!(header.source.and_then(|a| a.socket_addr()), Some(s));
1372            }
1373            other => panic!("{other:?}"),
1374        }
1375        let tlv = Tlv {
1376            kind: 0x02,
1377            value: b"example.com",
1378        };
1379        let n = encode_v2(
1380            ProxyCommand::Proxy,
1381            Some(s),
1382            Some(d),
1383            &[tlv],
1384            true,
1385            &mut out,
1386        )
1387        .unwrap();
1388        let mut p = ProxyParser::new(ProxyVersions::Both, 1024);
1389        match p.feed(&out[..n]).unwrap() {
1390            ProxyProgress::Done { header, consumed } => {
1391                assert_eq!(consumed, n);
1392                assert_eq!(header.source.and_then(|a| a.socket_addr()), Some(s));
1393                assert!(header.crc_checked());
1394            }
1395            other => panic!("{other:?}"),
1396        }
1397    }
1398
1399    #[test]
1400    fn test_encoders_refuse_what_they_cannot_write() {
1401        let v4: SocketAddr = "192.0.2.1:1".parse().unwrap();
1402        let v6: SocketAddr = "[::1]:1".parse().unwrap();
1403        let mut small = [0u8; 8];
1404        assert_eq!(
1405            encode_v1(v4, v6, &mut small),
1406            Err(ProxyError::FamilyMismatch)
1407        );
1408        assert!(matches!(
1409            encode_v1(v4, v4, &mut small),
1410            Err(ProxyError::OutputTooSmall { .. })
1411        ));
1412        assert!(matches!(
1413            encode_v2(ProxyCommand::Local, None, None, &[], false, &mut small),
1414            Err(ProxyError::OutputTooSmall { need: 16 })
1415        ));
1416        let mut out = [0u8; 16];
1417        assert_eq!(
1418            encode_v2(ProxyCommand::Local, None, None, &[], false, &mut out),
1419            Ok(16)
1420        );
1421    }
1422}