rama_haproxy/protocol/v2/
builder.rs

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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Builder pattern to generate both valid and invalid PROXY protocol v2 headers.

use crate::protocol::v2::{
    Addresses, Protocol, Type, TypeLengthValue, TypeLengthValues, LENGTH, MINIMUM_LENGTH,
    MINIMUM_TLV_LENGTH, PROTOCOL_PREFIX,
};
use std::io::{self, Write};

/// `Write` interface for the builder's internal buffer.
/// Can be used to turn header parts into bytes.
///
/// ## Examples
/// ```rust
/// use rama_haproxy::protocol::v2::{Addresses, Writer, WriteToHeader};
/// use std::net::SocketAddr;
///
/// let addresses: Addresses = ("127.0.0.1:80".parse::<SocketAddr>().unwrap(), "192.168.1.1:443".parse::<SocketAddr>().unwrap()).into();
/// let mut writer = Writer::default();
///
/// addresses.write_to(&mut writer).unwrap();
///
/// assert_eq!(addresses.to_bytes().unwrap(), writer.finish());
/// ```
#[derive(Debug, Default)]
pub struct Writer {
    bytes: Vec<u8>,
}

/// Implementation of the builder pattern for PROXY protocol v2 headers.
/// Supports both valid and invalid headers via the `write_payload` and `write_payloads` functions.
///
/// ## Examples
/// ```rust
/// use rama_haproxy::protocol::v2::{Addresses, AddressFamily, Builder, Command, IPv4, Protocol, PROTOCOL_PREFIX, Type, Version};
/// let mut expected = Vec::from(PROTOCOL_PREFIX);
/// expected.extend([
///    0x21, 0x12, 0, 16, 127, 0, 0, 1, 192, 168, 1, 1, 0, 80, 1, 187, 4, 0, 1, 42
/// ]);
///
/// let addresses: Addresses = IPv4::new([127, 0, 0, 1], [192, 168, 1, 1], 80, 443).into();
/// let header = Builder::with_addresses(
///     Version::Two | Command::Proxy,
///     Protocol::Datagram,
///     addresses
/// )
/// .write_tlv(Type::NoOp, [42].as_slice())
/// .unwrap()
/// .build()
/// .unwrap();
///
/// assert_eq!(header, expected);
/// ```
#[derive(Debug)]
pub struct Builder {
    header: Option<Vec<u8>>,
    version_command: u8,
    address_family_protocol: u8,
    addresses: Addresses,
    length: Option<u16>,
    additional_capacity: usize,
}

impl Writer {
    /// Consumes this `Writer` and returns the buffer holding the proxy protocol header payloads.
    /// The returned bytes are not guaranteed to be a valid proxy protocol header.
    pub fn finish(self) -> Vec<u8> {
        self.bytes
    }
}

impl From<Vec<u8>> for Writer {
    fn from(bytes: Vec<u8>) -> Self {
        Writer { bytes }
    }
}

impl Write for Writer {
    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        if self.bytes.len() > (u16::MAX as usize) + MINIMUM_LENGTH {
            Err(io::ErrorKind::WriteZero.into())
        } else {
            self.bytes.extend_from_slice(buffer);
            Ok(buffer.len())
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Defines how to write a type as part of a binary PROXY protocol header.
pub trait WriteToHeader {
    /// Write this instance to the given `Writer`.
    /// The `Writer` returns an IO error when an individual byte slice is longer than `u16::MAX`.
    /// However, the total length of the buffer may exceed `u16::MAX`.
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize>;

    /// Writes this instance to a temporary buffer and returns the buffer.
    fn to_bytes(&self) -> io::Result<Vec<u8>> {
        let mut writer = Writer::default();

        self.write_to(&mut writer)?;

        Ok(writer.finish())
    }
}

impl WriteToHeader for Addresses {
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
        match self {
            Addresses::Unspecified => (),
            Addresses::IPv4(a) => {
                writer.write_all(a.source_address.octets().as_slice())?;
                writer.write_all(a.destination_address.octets().as_slice())?;
                writer.write_all(a.source_port.to_be_bytes().as_slice())?;
                writer.write_all(a.destination_port.to_be_bytes().as_slice())?;
            }
            Addresses::IPv6(a) => {
                writer.write_all(a.source_address.octets().as_slice())?;
                writer.write_all(a.destination_address.octets().as_slice())?;
                writer.write_all(a.source_port.to_be_bytes().as_slice())?;
                writer.write_all(a.destination_port.to_be_bytes().as_slice())?;
            }
            Addresses::Unix(a) => {
                writer.write_all(a.source.as_slice())?;
                writer.write_all(a.destination.as_slice())?;
            }
        };

        Ok(self.len())
    }
}

impl WriteToHeader for TypeLengthValue<'_> {
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
        if self.value.len() > u16::MAX as usize {
            return Err(io::ErrorKind::WriteZero.into());
        }

        writer.write_all([self.kind].as_slice())?;
        writer.write_all((self.value.len() as u16).to_be_bytes().as_slice())?;
        writer.write_all(self.value.as_ref())?;

        Ok(MINIMUM_TLV_LENGTH + self.value.len())
    }
}

impl<T: Copy + Into<u8>> WriteToHeader for (T, &[u8]) {
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
        let kind = self.0.into();
        let value = self.1;

        if value.len() > u16::MAX as usize {
            return Err(io::ErrorKind::WriteZero.into());
        }

        writer.write_all([kind].as_slice())?;
        writer.write_all((value.len() as u16).to_be_bytes().as_slice())?;
        writer.write_all(value)?;

        Ok(MINIMUM_TLV_LENGTH + value.len())
    }
}

impl WriteToHeader for TypeLengthValues<'_> {
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
        let bytes = self.as_bytes();

        writer.write_all(bytes)?;

        Ok(bytes.len())
    }
}

impl WriteToHeader for [u8] {
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
        let slice = self;

        if slice.len() > u16::MAX as usize {
            return Err(io::ErrorKind::WriteZero.into());
        }

        writer.write_all(slice)?;

        Ok(slice.len())
    }
}

impl<T: ?Sized + WriteToHeader> WriteToHeader for &T {
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
        (*self).write_to(writer)
    }
}

impl WriteToHeader for Type {
    fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
        writer.write([(*self).into()].as_slice())
    }
}

macro_rules! impl_write_to_header {
    ($t:ident) => {
        impl WriteToHeader for $t {
            fn write_to(&self, writer: &mut Writer) -> io::Result<usize> {
                let bytes = self.to_be_bytes();

                writer.write_all(bytes.as_slice())?;

                Ok(bytes.len())
            }
        }
    };
}

impl_write_to_header!(u8);
impl_write_to_header!(u16);
impl_write_to_header!(u32);
impl_write_to_header!(u64);
impl_write_to_header!(u128);
impl_write_to_header!(usize);

impl_write_to_header!(i8);
impl_write_to_header!(i16);
impl_write_to_header!(i32);
impl_write_to_header!(i64);
impl_write_to_header!(i128);
impl_write_to_header!(isize);

impl Builder {
    /// Creates an instance of a `Builder` with the given header bytes.
    /// No guarantee is made that any address bytes written as a payload will match the header's address family.
    /// The length is determined on `build` unless `set_length` is called to set an explicit value.
    pub const fn new(version_command: u8, address_family_protocol: u8) -> Self {
        Builder {
            header: None,
            version_command,
            address_family_protocol,
            addresses: Addresses::Unspecified,
            length: None,
            additional_capacity: 0,
        }
    }

    /// Creates an instance of a `Builder` with the given header bytes and `Addresses`.
    /// The address family is determined from the variant of the `Addresses` given.
    /// The length is determined on `build` unless `set_length` is called to set an explicit value.
    pub fn with_addresses<T: Into<Addresses>>(
        version_command: u8,
        protocol: Protocol,
        addresses: T,
    ) -> Self {
        let addresses = addresses.into();

        Builder {
            header: None,
            version_command,
            address_family_protocol: addresses.address_family() | protocol,
            addresses,
            length: None,
            additional_capacity: 0,
        }
    }

    /// Reserves the requested additional capacity in the underlying buffer.
    /// Helps to prevent resizing the underlying buffer when called before `write_payload`, `write_payloads`.
    /// When called after `write_payload`, `write_payloads`, useful as a hint on how to resize the buffer.
    pub fn reserve_capacity(mut self, capacity: usize) -> Self {
        match self.header {
            None => self.additional_capacity += capacity,
            Some(ref mut header) => header.reserve(capacity),
        }

        self
    }

    /// Reserves the requested additional capacity in the underlying buffer.
    /// Helps to prevent resizing the underlying buffer when called before `write_payload`, `write_payloads`.
    /// When called after `write_payload`, `write_payloads`, useful as a hint on how to resize the buffer.
    pub fn set_reserve_capacity(&mut self, capacity: usize) -> &mut Self {
        match self.header {
            None => self.additional_capacity += capacity,
            Some(ref mut header) => header.reserve(capacity),
        }

        self
    }

    /// Overrides the length in the header.
    /// When set to `Some` value, the length may be smaller or larger than the actual payload in the buffer.
    pub fn set_length<T: Into<Option<u16>>>(mut self, length: T) -> Self {
        self.length = length.into();
        self
    }

    /// Writes a iterable set of payloads in order to the buffer.
    /// No bytes are added by this `Builder` as a delimiter.
    pub fn write_payloads<T, I, II>(mut self, payloads: II) -> io::Result<Self>
    where
        T: WriteToHeader,
        I: Iterator<Item = T>,
        II: IntoIterator<IntoIter = I, Item = T>,
    {
        self.write_header()?;

        let mut writer = Writer::from(self.header.take().unwrap_or_default());

        for item in payloads {
            item.write_to(&mut writer)?;
        }

        self.header = Some(writer.finish());

        Ok(self)
    }

    /// Writes a single payload to the buffer.
    /// No surrounding bytes (terminal or otherwise) are added by this `Builder`.
    pub fn write_payload<T: WriteToHeader>(mut self, payload: T) -> io::Result<Self> {
        self.write_header()?;
        self.write_internal(payload)?;

        Ok(self)
    }

    /// Writes a Type-Length-Value as a payload.
    /// No surrounding bytes (terminal or otherwise) are added by this `Builder`.
    /// The length is determined by the length of the slice.
    /// An error is returned when the length of the slice exceeds `u16::MAX`.
    pub fn write_tlv(self, kind: impl Into<u8>, value: &[u8]) -> io::Result<Self> {
        self.write_payload(TypeLengthValue::new(kind, value))
    }

    /// Writes to the underlying buffer without first writing the header bytes.
    fn write_internal<T: WriteToHeader>(&mut self, payload: T) -> io::Result<()> {
        let mut writer = Writer::from(self.header.take().unwrap_or_default());

        payload.write_to(&mut writer)?;

        self.header = Some(writer.finish());

        Ok(())
    }

    /// Writes the protocol prefix, version, command, address family, protocol, and optional addresses to the buffer.
    /// Does nothing if the buffer is not empty.
    fn write_header(&mut self) -> io::Result<()> {
        if self.header.is_some() {
            return Ok(());
        }

        let mut header =
            Vec::with_capacity(MINIMUM_LENGTH + self.addresses.len() + self.additional_capacity);

        let length = self.length.unwrap_or_default();

        header.extend_from_slice(PROTOCOL_PREFIX);
        header.push(self.version_command);
        header.push(self.address_family_protocol);
        header.extend_from_slice(length.to_be_bytes().as_slice());

        let mut writer = Writer::from(header);

        self.addresses.write_to(&mut writer)?;
        self.header = Some(writer.finish());

        Ok(())
    }

    /// Builds the header and returns the underlying buffer.
    /// If no length was explicitly set, returns an error when the length of the payload portion exceeds `u16::MAX`.
    pub fn build(mut self) -> io::Result<Vec<u8>> {
        self.write_header()?;

        let mut header = self.header.take().unwrap_or_default();

        if self.length.is_some() {
            return Ok(header);
        }

        if let Ok(payload_length) = u16::try_from(header[MINIMUM_LENGTH..].len()) {
            let length = payload_length.to_be_bytes();
            header[LENGTH..LENGTH + length.len()].copy_from_slice(length.as_slice());
            Ok(header)
        } else {
            Err(io::ErrorKind::WriteZero.into())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::v2::{AddressFamily, Command, IPv4, IPv6, Protocol, Type, Unix, Version};

    #[test]
    fn build_length_too_small() {
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([0x21, 0x12, 0, 1, 0, 0, 0, 1]);

        let actual = Builder::new(
            Version::Two | Command::Proxy,
            AddressFamily::IPv4 | Protocol::Datagram,
        )
        .set_length(1)
        .write_payload(1u32)
        .unwrap()
        .build()
        .unwrap();

        assert_eq!(actual, expected);
    }

    #[test]
    fn build_payload_too_long() {
        let error = Builder::new(
            Version::Two | Command::Proxy,
            AddressFamily::IPv4 | Protocol::Datagram,
        )
        .write_payload(vec![0u8; (u16::MAX as usize) + 1].as_slice())
        .unwrap_err();

        assert_eq!(error.kind(), io::ErrorKind::WriteZero);
    }

    #[test]
    fn build_no_payload() {
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([0x21, 0x01, 0, 0]);

        let header = Builder::new(
            Version::Two | Command::Proxy,
            AddressFamily::Unspecified | Protocol::Stream,
        )
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_arbitrary_payload() {
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([0x21, 0x01, 0, 1, 42]);

        let header = Builder::new(
            Version::Two | Command::Proxy,
            AddressFamily::Unspecified | Protocol::Stream,
        )
        .write_payload(42u8)
        .unwrap()
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_ipv4() {
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([
            0x21, 0x12, 0, 12, 127, 0, 0, 1, 192, 168, 1, 1, 0, 80, 1, 187,
        ]);

        let addresses: Addresses = IPv4::new([127, 0, 0, 1], [192, 168, 1, 1], 80, 443).into();
        let header = Builder::new(
            Version::Two | Command::Proxy,
            AddressFamily::IPv4 | Protocol::Datagram,
        )
        .set_length(addresses.len() as u16)
        .write_payload(addresses)
        .unwrap()
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_ipv6() {
        let source_address = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xF2,
        ];
        let destination_address = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xF1,
        ];
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([0x20, 0x20, 0, 36]);
        expected.extend(source_address);
        expected.extend(destination_address);
        expected.extend([0, 80, 1, 187]);

        let header = Builder::with_addresses(
            Version::Two | Command::Local,
            Protocol::Unspecified,
            IPv6::new(source_address, destination_address, 80, 443),
        )
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_unix() {
        let source_address = [0xFFu8; 108];
        let destination_address = [0xAAu8; 108];

        let addresses: Addresses = Unix::new(source_address, destination_address).into();
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([0x20, 0x31, 0, 216]);
        expected.extend(source_address);
        expected.extend(destination_address);

        let header = Builder::new(
            Version::Two | Command::Local,
            AddressFamily::Unix | Protocol::Stream,
        )
        .reserve_capacity(addresses.len())
        .write_payload(addresses)
        .unwrap()
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_ipv4_with_tlv() {
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([
            0x21, 0x12, 0, 17, 127, 0, 0, 1, 192, 168, 1, 1, 0, 80, 1, 187, 4, 0, 2, 0, 42,
        ]);

        let addresses: Addresses = IPv4::new([127, 0, 0, 1], [192, 168, 1, 1], 80, 443).into();
        let header =
            Builder::with_addresses(Version::Two | Command::Proxy, Protocol::Datagram, addresses)
                .reserve_capacity(5)
                .write_tlv(Type::NoOp, [0, 42].as_slice())
                .unwrap()
                .build()
                .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_ipv4_with_nested_tlv() {
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([
            0x21, 0x12, 0, 20, 127, 0, 0, 1, 192, 168, 1, 1, 0, 80, 1, 187, 0x20, 0, 5, 0, 0, 0, 0,
            0,
        ]);

        let addresses: Addresses = IPv4::new([127, 0, 0, 1], [192, 168, 1, 1], 80, 443).into();
        let header = Builder::new(
            Version::Two | Command::Proxy,
            AddressFamily::IPv4 | Protocol::Datagram,
        )
        .write_payload(addresses)
        .unwrap()
        .write_payload(Type::SSL)
        .unwrap()
        .write_payload(5u16)
        .unwrap()
        .write_payload([0u8; 5].as_slice())
        .unwrap()
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_ipv6_with_tlvs() {
        let source_address = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xF2,
        ];
        let destination_address = [
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
            0xFF, 0xF1,
        ];
        let addresses: Addresses = IPv6::new(source_address, destination_address, 80, 443).into();
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([0x20, 0x20, 0, 48]);
        expected.extend(source_address);
        expected.extend(destination_address);
        expected.extend([0, 80, 1, 187]);
        expected.extend([4, 0, 1, 0, 4, 0, 1, 0, 4, 0, 1, 42]);

        let header = Builder::new(
            Version::Two | Command::Local,
            AddressFamily::IPv6 | Protocol::Unspecified,
        )
        .write_payload(addresses)
        .unwrap()
        .write_payloads([
            (Type::NoOp, [0].as_slice()),
            (Type::NoOp, [0].as_slice()),
            (Type::NoOp, [42].as_slice()),
        ])
        .unwrap()
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }

    #[test]
    fn build_unix_with_tlv() {
        let source_address = [0xFFu8; 108];
        let destination_address = [0xAAu8; 108];

        let addresses: Addresses = Unix::new(source_address, destination_address).into();
        let mut expected = Vec::from(PROTOCOL_PREFIX);
        expected.extend([0x20, 0x31, 0, 216]);
        expected.extend(source_address);
        expected.extend(destination_address);
        expected.extend([0x20, 0, 0]);

        let header = Builder::new(
            Version::Two | Command::Local,
            AddressFamily::Unix | Protocol::Stream,
        )
        .set_length(216)
        .write_payload(addresses)
        .unwrap()
        .write_tlv(Type::SSL, &[])
        .unwrap()
        .build()
        .unwrap();

        assert_eq!(header, expected);
    }
}