1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{
    net::{AddrParseError, Ipv4Addr, Ipv6Addr, SocketAddr},
    num::ParseIntError,
    str::Utf8Error,
};

use bytes::Buf;
use thiserror::Error;

#[derive(Debug, Clone)]
pub enum ProxyProtocolV1Info {
    Tcp {
        source: SocketAddr,
        destination: SocketAddr,
    },
    Udp {
        source: SocketAddr,
        destination: SocketAddr,
    },
    Unknown,
}

#[derive(Error, Debug)]
#[error("Invalid proxy protocol header")]
pub enum ParseError {
    #[error("Not enough bytes provided")]
    NotEnoughBytes,
    NoCrLf,
    NoProxyPreamble,
    NoProtocol,
    InvalidProtocol,
    NoSourceAddress,
    NoDestinationAddress,
    NoSourcePort,
    NoDestinationPort,
    TooManyFields,
    InvalidUtf8(#[from] Utf8Error),
    InvalidAddress(#[from] AddrParseError),
    InvalidPort(#[from] ParseIntError),
}

impl ParseError {
    pub const fn not_enough_bytes(&self) -> bool {
        matches!(self, &Self::NotEnoughBytes)
    }
}

impl ProxyProtocolV1Info {
    #[allow(clippy::too_many_lines)]
    pub(super) fn parse<B>(buf: &mut B) -> Result<Self, ParseError>
    where
        B: Buf + AsRef<[u8]>,
    {
        use ParseError as E;
        // First, check if we *possibly* have enough bytes.
        // Minimum is 15: "PROXY UNKNOWN\r\n"

        if buf.remaining() < 15 {
            return Err(E::NotEnoughBytes);
        }

        // Let's check in the first 108 bytes if we find a CRLF
        let Some(crlf) = buf
            .as_ref()
            .windows(2)
            .take(108)
            .position(|needle| needle == [0x0D, 0x0A])
        else {
            // If not, it might be because we don't have enough bytes
            return if buf.remaining() < 108 {
                Err(E::NotEnoughBytes)
            } else {
                // Else it's just invalid
                Err(E::NoCrLf)
            };
        };

        // Trim to everything before the CRLF
        let bytes = &buf.as_ref()[..crlf];

        let mut it = bytes.splitn(6, |c| c == &b' ');
        // Check for the preamble
        if it.next() != Some(b"PROXY") {
            return Err(E::NoProxyPreamble);
        }

        let result = match it.next() {
            Some(b"TCP4") => {
                let source_address: Ipv4Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoSourceAddress)?)?.parse()?;
                let destination_address: Ipv4Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationAddress)?)?.parse()?;
                let source_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoSourcePort)?)?.parse()?;
                let destination_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationPort)?)?.parse()?;
                if it.next().is_some() {
                    return Err(E::TooManyFields);
                }

                let source = (source_address, source_port).into();
                let destination = (destination_address, destination_port).into();

                Self::Tcp {
                    source,
                    destination,
                }
            }
            Some(b"TCP6") => {
                let source_address: Ipv6Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoSourceAddress)?)?.parse()?;
                let destination_address: Ipv6Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationAddress)?)?.parse()?;
                let source_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoSourcePort)?)?.parse()?;
                let destination_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationPort)?)?.parse()?;
                if it.next().is_some() {
                    return Err(E::TooManyFields);
                }

                let source = (source_address, source_port).into();
                let destination = (destination_address, destination_port).into();

                Self::Tcp {
                    source,
                    destination,
                }
            }
            Some(b"UDP4") => {
                let source_address: Ipv4Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoSourceAddress)?)?.parse()?;
                let destination_address: Ipv4Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationAddress)?)?.parse()?;
                let source_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoSourcePort)?)?.parse()?;
                let destination_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationPort)?)?.parse()?;
                if it.next().is_some() {
                    return Err(E::TooManyFields);
                }

                let source = (source_address, source_port).into();
                let destination = (destination_address, destination_port).into();

                Self::Udp {
                    source,
                    destination,
                }
            }
            Some(b"UDP6") => {
                let source_address: Ipv6Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoSourceAddress)?)?.parse()?;
                let destination_address: Ipv6Addr =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationAddress)?)?.parse()?;
                let source_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoSourcePort)?)?.parse()?;
                let destination_port: u16 =
                    std::str::from_utf8(it.next().ok_or(E::NoDestinationPort)?)?.parse()?;
                if it.next().is_some() {
                    return Err(E::TooManyFields);
                }

                let source = (source_address, source_port).into();
                let destination = (destination_address, destination_port).into();

                Self::Udp {
                    source,
                    destination,
                }
            }
            Some(b"UNKNOWN") => Self::Unknown,
            Some(_) => return Err(E::InvalidProtocol),
            None => return Err(E::NoProtocol),
        };

        buf.advance(crlf + 2);

        Ok(result)
    }

    #[must_use]
    pub fn is_ipv4(&self) -> bool {
        match self {
            Self::Udp {
                source,
                destination,
            }
            | Self::Tcp {
                source,
                destination,
            } => source.is_ipv4() && destination.is_ipv4(),
            Self::Unknown => false,
        }
    }

    #[must_use]
    pub fn is_ipv6(&self) -> bool {
        match self {
            Self::Udp {
                source,
                destination,
            }
            | Self::Tcp {
                source,
                destination,
            } => source.is_ipv6() && destination.is_ipv6(),
            Self::Unknown => false,
        }
    }

    #[must_use]
    pub const fn is_tcp(&self) -> bool {
        matches!(self, Self::Tcp { .. })
    }

    #[must_use]
    pub const fn is_udp(&self) -> bool {
        matches!(self, Self::Udp { .. })
    }

    #[must_use]
    pub const fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown)
    }

    #[must_use]
    pub const fn source(&self) -> Option<&SocketAddr> {
        match self {
            Self::Udp { source, .. } | Self::Tcp { source, .. } => Some(source),
            Self::Unknown => None,
        }
    }

    #[must_use]
    pub const fn destination(&self) -> Option<&SocketAddr> {
        match self {
            Self::Udp { destination, .. } | Self::Tcp { destination, .. } => Some(destination),
            Self::Unknown => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse() {
        let mut buf =
            b"PROXY TCP4 255.255.255.255 255.255.255.255 65535 65535\r\nhello world".as_slice();
        let info = ProxyProtocolV1Info::parse(&mut buf).unwrap();
        assert_eq!(buf, b"hello world");
        assert!(info.is_tcp());
        assert!(!info.is_udp());
        assert!(!info.is_unknown());
        assert!(info.is_ipv4());
        assert!(!info.is_ipv6());

        let mut buf =
            b"PROXY TCP6 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\nhello world"
            .as_slice();
        let info = ProxyProtocolV1Info::parse(&mut buf).unwrap();
        assert_eq!(buf, b"hello world");
        assert!(info.is_tcp());
        assert!(!info.is_udp());
        assert!(!info.is_unknown());
        assert!(!info.is_ipv4());
        assert!(info.is_ipv6());

        let mut buf = b"PROXY UNKNOWN\r\nhello world".as_slice();
        let info = ProxyProtocolV1Info::parse(&mut buf).unwrap();
        assert_eq!(buf, b"hello world");
        assert!(!info.is_tcp());
        assert!(!info.is_udp());
        assert!(info.is_unknown());
        assert!(!info.is_ipv4());
        assert!(!info.is_ipv6());

        let mut buf =
            b"PROXY UNKNOWN ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\nhello world"
            .as_slice();
        let info = ProxyProtocolV1Info::parse(&mut buf).unwrap();
        assert_eq!(buf, b"hello world");
        assert!(!info.is_tcp());
        assert!(!info.is_udp());
        assert!(info.is_unknown());
        assert!(!info.is_ipv4());
        assert!(!info.is_ipv6());
    }
}