haproxy-protocol 0.0.4

HAProxy Protocol
Documentation
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#![deny(warnings)]
#![warn(unused_extern_crates)]
#![deny(clippy::todo)]
#![deny(clippy::unimplemented)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::expect_used)]
#![deny(clippy::panic)]
#![deny(clippy::unreachable)]
#![deny(clippy::await_holding_lock)]
#![deny(clippy::needless_pass_by_value)]
#![deny(clippy::trivially_copy_pass_by_ref)]

use crate::parse::{parse_proxy_hdr_v1, parse_proxy_hdr_v2};
use std::num::NonZeroUsize;

#[cfg(any(test, feature = "tokio"))]
use crate::parse::{V1_MAX_LEN, V1_MIN_LEN};

const NZ_ONE: NonZeroUsize = NonZeroUsize::new(1).expect("Invalid compile time constant");

mod parse;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u8)]
enum Protocol {
    Unspec = 0x00,
    TcpV4 = 0x11,
    UdpV4 = 0x12,
    TcpV6 = 0x21,
    UdpV6 = 0x22,
    // UnixStream = 0x31,
    // UnixDgram = 0x32,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u8)]
enum Command {
    Local = 0x00,
    Proxy = 0x01,
}

#[derive(Debug, PartialEq, Eq, Clone)]
enum Address {
    None,
    V4 {
        src: std::net::SocketAddrV4,
        dst: std::net::SocketAddrV4,
    },
    V6 {
        src: std::net::SocketAddrV6,
        dst: std::net::SocketAddrV6,
    },
    // Unix {
    //     src: PathBuf,
    //     dst: PathBuf,
    // }
}

#[derive(Debug, Clone)]
pub enum RemoteAddress {
    Local,
    Invalid,
    TcpV4 {
        src: std::net::SocketAddrV4,
        dst: std::net::SocketAddrV4,
    },
    UdpV4 {
        src: std::net::SocketAddrV4,
        dst: std::net::SocketAddrV4,
    },
    TcpV6 {
        src: std::net::SocketAddrV6,
        dst: std::net::SocketAddrV6,
    },
    UdpV6 {
        src: std::net::SocketAddrV6,
        dst: std::net::SocketAddrV6,
    },
}

#[derive(Debug)]
pub enum Error {
    Incomplete { need: NonZeroUsize },
    Invalid,
    UnableToComplete,
}

#[derive(Debug, Clone)]
pub struct ProxyHdrV2 {
    command: Command,
    protocol: Protocol,
    // address_family: AddressFamily,
    // length: u16,
    address: Address,
}

impl ProxyHdrV2 {
    pub fn parse(input_data: &[u8]) -> Result<(usize, Self), Error> {
        match parse_proxy_hdr_v2(input_data) {
            Ok((remainder, hdr)) => {
                let took = input_data.len() - remainder.len();
                Ok((took, hdr))
            }
            Err(nom::Err::Incomplete(nom::Needed::Size(need))) => Err(Error::Incomplete { need }),
            // We always know exactly how much is needed for hdr v2
            Err(nom::Err::Incomplete(nom::Needed::Unknown)) => Err(Error::UnableToComplete),

            Err(nom::Err::Error(err)) => {
                tracing::error!(?err);
                Err(Error::Invalid)
            }
            Err(nom::Err::Failure(err)) => {
                tracing::error!(?err, "parser failure handling proxy v2 header");
                Err(Error::Invalid)
            }
        }
    }

    pub fn to_remote_addr(self) -> RemoteAddress {
        match (self.command, self.protocol, self.address) {
            (Command::Local, _, _) => RemoteAddress::Local,
            (Command::Proxy, Protocol::TcpV4, Address::V4 { src, dst }) => {
                RemoteAddress::TcpV4 { src, dst }
            }
            (Command::Proxy, Protocol::UdpV4, Address::V4 { src, dst }) => {
                RemoteAddress::UdpV4 { src, dst }
            }
            (Command::Proxy, Protocol::TcpV6, Address::V6 { src, dst }) => {
                RemoteAddress::TcpV6 { src, dst }
            }
            (Command::Proxy, Protocol::UdpV6, Address::V6 { src, dst }) => {
                RemoteAddress::UdpV6 { src, dst }
            }
            _ => RemoteAddress::Invalid,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ProxyHdrV1 {
    protocol: Protocol,
    address: Address,
}

impl ProxyHdrV1 {
    pub fn parse(input_data: &[u8]) -> Result<(usize, Self), Error> {
        match parse_proxy_hdr_v1(input_data) {
            Ok((remainder, hdr)) => {
                let took = input_data.len() - remainder.len();
                Ok((took, hdr))
            }
            Err(nom::Err::Incomplete(nom::Needed::Size(need))) => Err(Error::Incomplete { need }),
            // We aren't sure how much we need but we need *something*.
            Err(nom::Err::Incomplete(nom::Needed::Unknown)) => {
                Err(Error::Incomplete { need: NZ_ONE })
            }

            Err(nom::Err::Error(err)) => {
                tracing::error!(?err);
                Err(Error::Invalid)
            }
            Err(nom::Err::Failure(err)) => {
                tracing::error!(?err, "parser failure handling proxy v1 header");
                Err(Error::Invalid)
            }
        }
    }

    pub fn to_remote_addr(self) -> RemoteAddress {
        match (self.protocol, self.address) {
            (Protocol::TcpV4, Address::V4 { src, dst }) => RemoteAddress::TcpV4 { src, dst },
            (Protocol::UdpV4, Address::V4 { src, dst }) => RemoteAddress::UdpV4 { src, dst },
            (Protocol::TcpV6, Address::V6 { src, dst }) => RemoteAddress::TcpV6 { src, dst },
            (Protocol::UdpV6, Address::V6 { src, dst }) => RemoteAddress::UdpV6 { src, dst },
            _ => RemoteAddress::Invalid,
        }
    }
}

#[cfg(any(feature = "tokio", test))]
#[derive(Debug)]
pub enum AsyncReadError {
    Io(std::io::Error),
    Invalid,
    UnableToComplete,
    RequestTooLarge,
    InconsistentRead,
}

#[cfg(any(feature = "tokio", test))]
impl ProxyHdrV2 {
    pub async fn parse_from_read<S>(mut stream: S) -> Result<(S, Self), AsyncReadError>
    where
        S: tokio::io::AsyncReadExt + std::marker::Unpin,
    {
        use tracing::{debug, error};

        const HDR_SIZE_LIMIT: usize = 512;

        let mut buf = vec![0; 16];

        // First we need to read the exact amount to get up to the *length* field. This will
        // let us then proceed to parse the early header and return how much we need to continue
        // to read.
        let mut took = stream
            .read_exact(&mut buf)
            .await
            .map_err(AsyncReadError::Io)?;

        match ProxyHdrV2::parse(&buf) {
            // Okay, we got a valid header - this can occur with proxy for local conditions.
            Ok((_, hdr)) => return Ok((stream, hdr)),
            // We need more bytes, this is the precise amount we need.
            Err(Error::Incomplete { need }) => {
                let resize_to = buf.len() + usize::from(need);
                // Limit the amount so that we don't overflow anything or allocate a buffer that
                // is too large. Nice try hackers.
                if resize_to > HDR_SIZE_LIMIT {
                    error!(
                        "proxy v2 header request was larger than {} bytes, refusing to proceed.",
                        HDR_SIZE_LIMIT
                    );
                    return Err(AsyncReadError::RequestTooLarge);
                }
                buf.resize(resize_to, 0);
            }
            Err(Error::Invalid) => {
                debug!(proxy_binary_dump = %hex::encode(&buf));
                error!("proxy v2 header was invalid");
                return Err(AsyncReadError::Invalid);
            }
            Err(Error::UnableToComplete) => {
                debug!(proxy_binary_dump = %hex::encode(&buf));
                error!("proxy v2 header was incomplete");
                return Err(AsyncReadError::UnableToComplete);
            }
        };

        // Now read any remaining bytes into the buffer.
        took += stream
            .read_exact(&mut buf[16..])
            .await
            .map_err(AsyncReadError::Io)?;

        match ProxyHdrV2::parse(&buf) {
            Ok((hdr_took, _)) if hdr_took != took => {
                // We took inconsistent byte amounts, error.
                error!("proxy v2 header read an inconsistent amount from stream.");
                Err(AsyncReadError::InconsistentRead)
            }
            Ok((_, hdr)) =>
            // HAPPY!!!!!
            {
                Ok((stream, hdr))
            }
            Err(Error::Incomplete { need: _ }) => {
                error!("proxy v2 header could not be read to the end.");
                Err(AsyncReadError::UnableToComplete)
            }
            Err(Error::Invalid) => {
                debug!(proxy_binary_dump = %hex::encode(&buf));
                error!("proxy v2 header was invalid");
                Err(AsyncReadError::Invalid)
            }
            Err(Error::UnableToComplete) => {
                debug!(proxy_binary_dump = %hex::encode(&buf));
                error!("proxy v2 header was incomplete");
                Err(AsyncReadError::UnableToComplete)
            }
        }
    }
}

#[cfg(any(feature = "tokio", test))]
impl ProxyHdrV1 {
    pub async fn parse_from_read<S>(mut stream: S) -> Result<(S, Self), AsyncReadError>
    where
        S: tokio::io::AsyncReadExt + std::marker::Unpin,
    {
        use tracing::{debug, error};

        // This is the maximum size of the buffer we could possibly need.
        let mut buf = [0; V1_MAX_LEN + 1];

        // First we need to read the exact amount to get up to the *length* field. This will
        // let us then proceed to parse the early header and return how much we need to continue
        // to read.
        let mut took = stream
            .read_exact(&mut buf[..V1_MIN_LEN])
            .await
            .map_err(AsyncReadError::Io)?;

        // Limit the view window to how many bytes we have.

        loop {
            if took > buf.len() {
                error!("proxy v1 header read over ran the buffer allocation.");
                return Err(AsyncReadError::Invalid);
            }
            match ProxyHdrV1::parse(&buf[..took]) {
                Ok((hdr_took, _)) if hdr_took != took => {
                    // We took inconsistent byte amounts, error.
                    error!("proxy v1 header read an inconsistent amount from stream.");
                    return Err(AsyncReadError::InconsistentRead);
                }
                Ok((_, hdr)) =>
                // HAPPY!!!!!
                {
                    return Ok((stream, hdr));
                }
                Err(Error::Incomplete { need }) => {
                    // We need more data, read it and then continue the loop.
                    // Now read any remaining bytes into the buffer.
                    took += stream
                        .read_exact(&mut buf[took..took + need.get()])
                        .await
                        .map_err(AsyncReadError::Io)?;

                    continue;
                }
                Err(Error::Invalid) => {
                    debug!(proxy_binary_dump = %hex::encode(buf));
                    error!("proxy v1 header was invalid");
                    return Err(AsyncReadError::Invalid);
                }
                Err(Error::UnableToComplete) => {
                    debug!(proxy_binary_dump = %hex::encode(buf));
                    error!("proxy v1 header was incomplete");
                    return Err(AsyncReadError::UnableToComplete);
                }
            }
        } // end loop
    }
}

#[cfg(test)]
mod tests {
    use crate::{Address, Command, Protocol, ProxyHdrV1, ProxyHdrV2};
    use std::net::SocketAddrV4;
    use std::str::FromStr;

    #[tokio::test]
    async fn proxyv1_stream_parse() {
        let _ = tracing_subscriber::fmt::try_init();

        let data = "PROXY TCP4 91.221.138.33 91.221.138.106 47780 636\r\n";

        let (_, hdr) = ProxyHdrV1::parse_from_read(data.as_bytes()).await.unwrap();

        tracing::debug!(?hdr);

        assert_eq!(hdr.protocol, Protocol::TcpV4);
        assert_eq!(
            hdr.address,
            Address::V4 {
                src: SocketAddrV4::from_str("91.221.138.33:47780").unwrap(),
                dst: SocketAddrV4::from_str("91.221.138.106:636").unwrap(),
            }
        );
    }

    #[tokio::test]
    async fn proxyv2_stream_parse() {
        let _ = tracing_subscriber::fmt::try_init();

        let sample = hex::decode("0d0a0d0a000d0a515549540a2111000cac180c76ac180b8fcdcb027d")
            .expect("valid hex");

        let (_, hdr) = ProxyHdrV2::parse_from_read(sample.as_slice())
            .await
            .expect("should parse v4 addr");

        tracing::debug!(?hdr);

        assert_eq!(hdr.command, Command::Proxy);
        assert_eq!(hdr.protocol, Protocol::TcpV4);
        assert_eq!(
            hdr.address,
            Address::V4 {
                src: SocketAddrV4::from_str("172.24.12.118:52683").expect("valid addr"),
                dst: SocketAddrV4::from_str("172.24.11.143:637").expect("valid addr"),
            }
        );
    }

    #[cfg(all(test, feature = "tokio"))]
    mod async_stream_tests {
        use super::*;
        use std::net::{SocketAddrV4, SocketAddrV6};
        use std::str::FromStr;
        use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};

        async fn write_in_chunks<W>(mut writer: W, data: &[u8], chunk_sizes: &[usize])
        where
            W: AsyncWrite + Unpin,
        {
            let mut offset = 0;
            for &size in chunk_sizes {
                if offset >= data.len() {
                    break;
                }
                let end = (offset + size).min(data.len());
                #[allow(clippy::expect_used)] // because test function
                writer
                    .write_all(&data[offset..end])
                    .await
                    .expect("chunk write should succeed");
                tokio::task::yield_now().await;
                offset = end;
            }

            if offset < data.len() {
                #[allow(clippy::expect_used)] // because test function
                writer
                    .write_all(&data[offset..])
                    .await
                    .expect("final write should succeed");
            }
        }

        #[tokio::test]
        async fn tokio_stream_parse_v2_chunks() {
            let _ = tracing_subscriber::fmt::try_init();

            let sample = hex::decode("0d0a0d0a000d0a515549540a2111000cac180c76ac180b8fcdcb027d")
                .expect("valid hex");
            let payload = b"hello";
            let mut full = sample.clone();
            full.extend_from_slice(payload);

            let (client, server) = tokio::io::duplex(32);

            let writer = tokio::spawn(async move {
                write_in_chunks(server, &full, &[5, 3, 1, 7, 2]).await;
            });

            let (mut stream, hdr) = ProxyHdrV2::parse_from_read(client)
                .await
                .expect("should parse v2 from stream");

            let mut extra = vec![0; payload.len()];
            stream
                .read_exact(&mut extra)
                .await
                .expect("should read extra payload");

            writer.await.expect("writer task should finish");

            assert_eq!(extra.as_slice(), payload);
            assert_eq!(hdr.command, Command::Proxy);
            assert_eq!(hdr.protocol, Protocol::TcpV4);
            assert_eq!(
                hdr.address,
                Address::V4 {
                    src: SocketAddrV4::from_str("172.24.12.118:52683").expect("valid addr"),
                    dst: SocketAddrV4::from_str("172.24.11.143:637").expect("valid addr"),
                }
            );
        }

        #[tokio::test]
        async fn tokio_stream_parse_v1_chunks() {
            let _ = tracing_subscriber::fmt::try_init();

            let header = b"PROXY TCP6 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 65535 65535\r\n";
            let payload = b"more_data";
            let mut full = header.to_vec();
            full.extend_from_slice(payload);

            let (client, server) = tokio::io::duplex(64);

            let writer = tokio::spawn(async move {
                write_in_chunks(server, &full, &[4, 1, 8, 2, 3, 5, 1]).await;
            });

            let (mut stream, hdr) = ProxyHdrV1::parse_from_read(client)
                .await
                .expect("should parse v1 from stream");

            let mut extra = vec![0; payload.len()];
            stream
                .read_exact(&mut extra)
                .await
                .expect("should read extra payload");

            writer.await.expect("writer task should finish");

            assert_eq!(extra.as_slice(), payload);
            assert_eq!(hdr.protocol, Protocol::TcpV6);
            assert_eq!(
                hdr.address,
                Address::V6 {
                    src: SocketAddrV6::from_str("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")
                        .expect("valid addr"),
                    dst: SocketAddrV6::from_str("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535")
                        .expect("valid addr"),
                }
            );
        }
    }
}