haprox-rs 0.2.2

A HaProxy protocol parser.
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
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/*-
 * haprox-rs - a HaProxy protocol parser.
 * 
 * Copyright 2025 Aleksandr Morozov
 * The scram-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *                     
 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::{borrow::Cow, io::{Cursor, Write}, marker::PhantomData, mem::offset_of};

use byteorder::{BigEndian, WriteBytesExt};
use crc32fast::Hasher;

use crate::{common, error::{HaProxErr, HaProxRes}, return_error};

use super::{protocol::{self, HdrV2Command, PP2TlvClient, PP2Tlvs, ProxyTransportFam, ProxyV2Addr}, protocol_raw, PP2TlvDump, PP2TlvUniqId, ProxyV2OpCode};



/// A quote from original protocol documentation.
/// > the connection was established on purpose by the proxy
/// > without being relayed. The connection endpoints are the sender and the
/// > receiver. Such connections exist when the proxy sends health-checks to the
/// > server. The receiver must accept this connection as valid and must use the
/// > real connection endpoints and discard the protocol block including the
/// > family which is ignored.
#[derive(Clone, Debug)]
pub struct HdrV2OpLocal;

/// A quote from original protocol documentation.
/// > the connection was established on behalf of another node,
/// > and reflects the original connection endpoints. The receiver must then use
/// > the information provided in the protocol block to get original the address.
#[derive(Clone, Debug)]
pub struct HdrV2OpProxy;

impl ProxyV2OpCode for HdrV2OpLocal
{
    /// A 0x00 opcode.
    const OPCODE: u8 = HdrV2Command::LOCAL as u8;
}

impl ProxyV2OpCode for HdrV2OpProxy
{
    /// A 0x01 opcode.
    const OPCODE: u8 = HdrV2Command::PROXY as u8;
}

/// A SSL TLV composer.
#[derive(Debug)]
pub struct TlvSubTypeSsl<'s>
{
    /// Begining of the SSL TLV block.
    start: u64,

    /// A current [TlType] consumed from the root.
    hdr: TlType<'s>,

    /// A TLV ID constraints.
    constraints: &'static [std::ops::RangeInclusive<u8>]
}

impl<'s> TlvSubTypeSsl<'s>
{
    fn new(mut main_tp: TlType<'s>, constraints: &'static [std::ops::RangeInclusive<u8>],
        client: PP2TlvClient, verify: u32) -> HaProxRes<Self>
    {
        let start = main_tp.hdr.buffer.position();

        main_tp.add_tlv(PP2Tlvs::TypeSsl{client, verify}, None)?;

        return Ok(
            Self
            {
                start: start,
                hdr: main_tp,
                constraints: constraints
            }
        );
    }

    #[inline]
    fn done_int(&mut self) -> HaProxRes<()>
    {
        let cur_pos = self.hdr.hdr.buffer.position();

        self.hdr.hdr.buffer.set_position(self.start + offset_of!(protocol_raw::PP2Tlv, length_hi) as u64);//1);

        self.hdr.hdr.buffer.write_u16::<BigEndian>((cur_pos - self.start - 3) as u16).map_err(common::map_io_err)?;

        self.hdr.hdr.buffer.set_position(cur_pos);

        return Ok(());
    }

    /// When all necessary SSL sub TLVs are added, this function calculates the 
    /// length of SSL TLV and writes the size.
    /// 
    /// # Returns
    /// 
    /// A [HaProxRes] is returned. On success the previous (root) [TlType] (which
    /// was consumed previously) will be returned.
    #[inline]
    pub 
    fn done(mut self) -> HaProxRes<TlType<'s>>
    {
        self.done_int()?;
        

        return Ok(self.hdr);
    }

    /// Sets the version of the SSL i,e TLSv1.2.
    pub 
    fn add_ssl_sub_version(&mut self, ver: impl Into<String>) -> HaProxRes<()>
    {
        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslVersion(Cow::Owned(ver.into())), Some(self.constraints));
    }

    /// Sets the Common Name field.
    pub 
    fn add_ssl_sub_cn(&mut self, cn: impl Into<String>) -> HaProxRes<()>
    {
        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslCn(Cow::Owned(cn.into())), Some(self.constraints));
    }

    /// Sets the Cipher type i.e "ECDHE-RSA-AES128-GCM-SHA256"
    pub 
    fn add_ssl_sub_cipher(&mut self, ver: impl Into<String>) -> HaProxRes<()>
    {
        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslCipher(Cow::Owned(ver.into())), Some(self.constraints));
    }
    
    /// Sets the signature algorithm i.e "SHA256"
    pub 
    fn add_ssl_sub_sigalg(&mut self, ver: impl Into<String>) -> HaProxRes<()>
    {
        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslSigAlg(Cow::Owned(ver.into())), Some(self.constraints));
    }

    /// Sets the key algorithm i.e "RSA2048"
    pub 
    fn add_ssl_sub_keyalg(&mut self, ver: impl Into<String>) -> HaProxRes<()>
    {
        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslKeyAlg(Cow::Owned(ver.into())), Some(self.constraints));
    }

    /// Sets the namespace's name.
    pub 
    fn add_ssl_sub_netns(&mut self, ver: impl Into<String>) -> HaProxRes<()>
    {
        return self.hdr.add_tlv(PP2Tlvs::TypeNetNs(ver.into()), Some(self.constraints));
    }
}

/// A root (main) TLV writer.
#[derive(Debug)]
pub struct TlType<'s>
{
    /// A reference to the header.
    hdr: &'s mut ProxyHdrV2<HdrV2OpProxy>,

    /// A TLVs which can be set on root level.
    constraints: &'static [std::ops::RangeInclusive<u8>]
}

impl<'s> TlType<'s>
{
    fn new(hdr: &'s mut ProxyHdrV2<HdrV2OpProxy>, constraints: &'static [std::ops::RangeInclusive<u8>]) -> Self
    {
        return
            Self
            {
                hdr,
                constraints
            };
    }

    /// Adds the Application-Layer Protocol Negotiation (ALPN)
    pub 
    fn add_alpn<'a>(&mut self, alpns: impl Iterator<Item = &'a [u8]>) -> HaProxRes<()>
    {
        return self.add_tlv(PP2Tlvs::TypeAlpn( alpns.map(|v| v.to_vec()).collect()), None);
    }

    /// Adds padding 3 bytes.
    pub 
    fn add_noop(&mut self) -> HaProxRes<()>
    {
        return self.add_tlv(PP2Tlvs::TypeNoop, None);
    }

    /// Adds  US-ASCII string representation of the namespace's name
    pub 
    fn add_netns(&mut self, ns: impl Into<String>) -> HaProxRes<()>
    {
        return self.add_tlv(PP2Tlvs::TypeNetNs(ns.into()), None);
    }

    /// Adds a 32-bit number storing the CRC32c checksum of the PROXY protocol header
    /// 
    /// It will be calculated after finalization.
    pub 
    fn add_crc32(&mut self) -> HaProxRes<()>
    {
        return self.add_tlv(PP2Tlvs::TypeCrc32c(0), None);
    }

    /// Adds a uniqID. See [PP2TlvUniqId]. 128 bytes max.
    pub 
    fn add_uniq_id<ID: PP2TlvUniqId>(&mut self, au: ID) -> HaProxRes<()>
    {
        let uniq_id = au.into_bytes();

        return self.add_tlv(PP2Tlvs::TypeUniqId(uniq_id), None);
    }

    /// Adds "SNI" i.e the "server_name" extension as defined by RFC3546.
    pub 
    fn add_authority(&mut self, authority: impl Into<String>) -> HaProxRes<()>
    {
        return self.add_tlv(PP2Tlvs::TypeAuthority(authority.into()), None);
    }

    // --- SSL and subtypes ---

    /// Adds SSL properties.
    pub 
    fn add_ssl(self, client: PP2TlvClient, verify: u32) -> HaProxRes<TlvSubTypeSsl<'s>>
    {
        return TlvSubTypeSsl::new(self, PP2Tlvs::TLV_TYPE_SSL_SUB_RANGE, client, verify);
    }

    /// Adding external TLV. The adding instance should implement [PP2TlvDump].
    pub 
    fn add_tlv<TLV: PP2TlvDump>(&mut self, tlv: TLV, 
        opt_constr: Option<&'static [std::ops::RangeInclusive<u8>]>) -> HaProxRes<()>
    {
        let tlv_id: u8 = tlv.get_type();

        let constr = opt_constr.unwrap_or(self.constraints);

        if constr.iter().any(|idr| idr.contains(&tlv_id)) == false
        {
            return_error!(ArgumentEinval, "TLV: {} is subtype of other type or type!", tlv);
        }

        if tlv_id == PP2Tlvs::TypeCrc32c(0).into()
        {
            if self.hdr.crc_tlv_offset != 0
            {
                return_error!(ArgumentEinval, "diplicate PLT CRC!");
            }

            self.hdr.crc_tlv_offset = self.hdr.buffer.position();
        }

        // write type
        self.hdr.buffer.write_u8(tlv_id).map_err(common::map_io_err)?;

        // store size_position
        let size_pos = self.hdr.buffer.position();

        // write fake size
        self.hdr.buffer.write_u16::<BigEndian>(0).map_err(common::map_io_err)?;   

        // write TLV's content
        tlv.dump(&mut self.hdr.buffer)?;

        // write size
        let cur_pos = self.hdr.buffer.position();
        self.hdr.buffer.set_position(size_pos);

        // size
        self.hdr.buffer.write_u16::<BigEndian>((cur_pos - size_pos - 2) as u16).map_err(common::map_io_err)?;

        // restore cursor
        self.hdr.buffer.set_position(cur_pos);

        return Ok(());
    }
}

/// A Proxy Network packet composer.
/// 
/// Depending on the type of the generic `OPC` a different composing options
/// are available.
/// 
/// OPC:
/// 
/// * `HdrV2OpLocal` - a local operation as described in the proxy documentation.
/// 
/// * `HdrV2OpProxy` - a proxy operation as described in the proxy documentation.
/// 
/// # Arguments
/// 
/// * `OPC` - [ProxyV2OpCode] a proxy opcode. It is intentionally made as a generic
///     to separate the options which are availabe for each type of HaProxy message.
/// 
#[derive(Clone, Debug)]
pub struct ProxyHdrV2<OPC: ProxyV2OpCode>
{
    /// Preallocard space for header.
    buffer: Cursor<Vec<u8>>,

    /// Offset to the location of the TLV CRC
    crc_tlv_offset: u64,

    /// Phantom for the [ProxyV2OpCode]
    _p: PhantomData<OPC>,
}

impl<OPC: ProxyV2OpCode> ProxyHdrV2<OPC>
{
    /// Offset to the message length field.
    pub const HDR_MSG_LEN_OFFSET: u64 = offset_of!(protocol_raw::ProxyHdrV2, len) as u64;
}

/// All functionality available for the opcode LOCAL.
impl ProxyHdrV2<HdrV2OpLocal>
{
    /// Creates a new message of type LOCAL [HdrV2Command::LOCAL].
    pub 
    fn new() -> Vec<u8>
    {
        return protocol_raw::MSG_HEADER_LOCAL_V2.to_vec();
    }
}

/// All functionality available for the opcode PROXY.
impl ProxyHdrV2<HdrV2OpProxy>
{
    /// Creates new message of type PROXY [HdrV2Command::PROXY]. A program should provide the
    /// type of the transport and address of the source and destination. The message compose instance 
    /// is returned which already contains a prepared header.
    /// 
    /// # Arguments
    /// 
    /// * `transport` - [ProxyTransportFam] a type of the transport.
    /// 
    /// * `address` - a source and destination address encapsulated in [ProxyV2Addr].
    /// 
    /// # Returns
    /// 
    /// A [HaProxRes] is returned:
    /// 
    /// * [Result::Ok] - with the instance
    /// 
    /// * [Result::Err] - error description
    pub 
    fn new(transport: ProxyTransportFam, address: ProxyV2Addr) -> HaProxRes<Self>
    {
        let buf: Vec<u8> = 
            Vec::with_capacity(size_of::<protocol_raw::ProxyHdrV2>());

        let mut cur = Cursor::new(buf);
        // writing header

        // header_magic
        cur.write_all(protocol_raw::HEADER_MAGIC_V2).map_err(common::map_io_err)?;

        // protocol version and command 
        cur.write_u8(0x20 | HdrV2OpProxy::OPCODE).map_err(common::map_io_err)?;

        // addr type and transport
        cur.write_u8(((address.as_addr_family() as u8) << 4) | transport as u8).map_err(common::map_io_err)?;

        // length offset is known, so it will be updated later
        cur.write_u16::<BigEndian>(address.get_len()).map_err(common::map_io_err)?;

        // writing address
        address.write(&mut cur)?;

        return Ok(
            Self
            {
                buffer: cur,
                crc_tlv_offset: 0,
                _p: PhantomData
            }
        );
    }

    /// Provides functionality to add the TLV to the payload of the message.
    pub 
    fn set_plts<'s>(&'s mut self) -> TlType<'s>
    {
        return TlType::new(self, PP2Tlvs::TLV_TYPE_MAIN_RANGES);
    }

    fn finalize(&mut self) -> HaProxRes<()>
    {
        let last_off = self.buffer.position();

        // set position to HEADER LENGTH
        self.buffer.set_position(Self::HDR_MSG_LEN_OFFSET);

        let tlv_len = last_off - size_of::<protocol_raw::ProxyHdrV2>() as u64;

        self.buffer.write_u16::<BigEndian>(tlv_len as u16).map_err(common::map_io_err)?;

        if self.crc_tlv_offset > 0
        {
            // init hasher
            let mut hasher = Hasher::new();

            // calculate crc32
            hasher.update(self.buffer.get_ref());

            // set position to start of the CRC's plt payload
            self.buffer.set_position(self.crc_tlv_offset + protocol::TLV_HEADER_LEN as u64);

            // write back CRC
            self.buffer.write_u32::<BigEndian>(hasher.finalize()).map_err(common::map_io_err)?;
        }
        return Ok(());
    }

    
}

/// Converts the instance to the vector. The message will be finalized i.e
/// length recalculated, CRC updated.
impl TryFrom<ProxyHdrV2<HdrV2OpProxy>> for Vec<u8>
{
    type Error = HaProxErr;

    fn try_from(mut value: ProxyHdrV2<HdrV2OpProxy>) -> Result<Self, Self::Error> 
    {
        value.finalize()?;

        return Ok(value.buffer.into_inner());
    }
}

impl PP2TlvDump for PP2Tlvs
{
    fn get_type(&self) -> u8 
    {
        return self.into();
    }

    fn dump(&self, cur: &mut Cursor<Vec<u8>>) -> HaProxRes<()> 
    {
        match self
        {
            PP2Tlvs::TypeAlpn(items) => 
            {
                // payload
                for alpn in items.iter()//.map(|v| v.as_bytes())
                {
                    // length u16
                    cur.write_u16::<BigEndian>(alpn.len() as u16).map_err(common::map_io_err)?;

                    // alpn bytes
                    cur.write_all(alpn).map_err(common::map_io_err)?;
                }
            },
            PP2Tlvs::TypeAuthority(auth) => 
            {
                // authority
                cur.write_all(auth.as_bytes()).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeCrc32c(crc) => 
            {
                cur.write_u32::<BigEndian>(*crc).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeNoop => 
            {

            },
            PP2Tlvs::TypeUniqId(items) =>
            {
                cur.write_all(items.as_slice()).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeSsl{client, verify} => 
            {
                // client
                cur.write_u8(client.bits()).map_err(common::map_io_err)?;

                // verify
                cur.write_u32::<BigEndian>(*verify).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeSubtypeSslVersion(v) => 
            {
                cur.write_all(v.as_bytes()).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeSubtypeSslCn(cn) => 
            {
                cur.write_all(cn.as_bytes()).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeSubtypeSslCipher(c) => 
            {
                cur.write_all(c.as_bytes()).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeSubtypeSslSigAlg(sa) => 
            {
                cur.write_all(sa.as_bytes()).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeSubtypeSslKeyAlg(ka) => 
            {
                cur.write_all(ka.as_bytes()).map_err(common::map_io_err)?;
            },
            PP2Tlvs::TypeNetNs(ns) => 
            {
                cur.write_all(ns.as_bytes()).map_err(common::map_io_err)?;
            },
        }

        return Ok(());
    }
}

#[cfg(test)]
mod tests
{
    use std::{fmt, io::Cursor};

    use byteorder::{BigEndian, WriteBytesExt};

    use crate::{common::map_io_err, protocol::{protocol::{PP2TlvClient, PP2Tlvs}, PP2TlvDump}, HaProxRes, ProxyTransportFam, ProxyV2Addr};

    use super::{HdrV2OpProxy, ProxyHdrV2};

    #[test]
    fn test_comp0()
    {
        let addr = ProxyV2Addr::try_from(("127.0.0.1:39754", "127.0.0.67:11883")).unwrap();
        
        let mut comp = 
            ProxyHdrV2::<HdrV2OpProxy>::new(ProxyTransportFam::STREAM, addr).unwrap();

        let plts = comp.set_plts();

        let mut ssl = plts.add_ssl(PP2TlvClient::PP2_CLIENT_SSL, 0).unwrap();

        ssl.add_ssl_sub_version("TLSv1.2").unwrap();
        
        ssl.done().unwrap();

        let pkt: Vec<u8> = comp.try_into().unwrap();

        let ctrl = 
b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a\x21\x11\x00\x1e\
\x7f\x00\x00\x01\x7f\x00\x00\x43\x9b\x4a\x2e\x6b\x20\x00\x0f\x01\
\x00\x00\x00\x00\x21\x00\x07\x54\x4c\x53\x76\x31\x2e\x32";

        assert_eq!(pkt.as_slice(), ctrl.as_slice());
    }

    #[test]
    fn test_comp1()
    {
        #[derive(Clone, Debug)]
        pub enum ProxyV2Dummy2 
        {
            SomeTlvName(u32, u32),
        }

        impl fmt::Display for ProxyV2Dummy2
        {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
            {
                write!(f, "DUMMY external reader")
            }
        }

        impl PP2TlvDump for ProxyV2Dummy2
        {
            fn get_type(&self) -> u8 
            {
                let Self::SomeTlvName(..) = self else { panic!("wrong") };

                return 0xE0;
            }

            fn dump(&self, cur: &mut Cursor<Vec<u8>>) -> HaProxRes<()> 
            {
                match self
                {
                    Self::SomeTlvName(arg0, arg1) =>
                    {
                        cur.write_u32::<BigEndian>(*arg0).map_err(map_io_err)?;
                        cur.write_u32::<BigEndian>(*arg1).map_err(map_io_err)?;
                    }
                }

                return Ok(());
            }
        }



        let addr = ProxyV2Addr::try_from(("127.0.0.1:39754", "127.0.0.67:11883")).unwrap();
        
        let mut comp = 
            ProxyHdrV2::<HdrV2OpProxy>::new(ProxyTransportFam::STREAM, addr).unwrap();

        let plts = comp.set_plts();

        let mut ssl = plts.add_ssl(PP2TlvClient::PP2_CLIENT_SSL, 0).unwrap();

        ssl.add_ssl_sub_version("TLSv1.2").unwrap();
        
        let mut plts = ssl.done().unwrap();


        let cust_plt = ProxyV2Dummy2::SomeTlvName(0x01020304, 0x05060708);

        plts.add_tlv(cust_plt, Some(&[0xE0..=0xE0])).unwrap();

        drop(plts);

        let pkt: Vec<u8> = comp.try_into().unwrap();

        let ctrl = 
b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a\x21\x11\x00\x29\
\x7f\x00\x00\x01\x7f\x00\x00\x43\x9b\x4a\x2e\x6b\x20\x00\x0f\x01\
\x00\x00\x00\x00\x21\x00\x07\x54\x4c\x53\x76\x31\x2e\x32\xE0\x00\
\x08\x01\x02\x03\x04\x05\x06\x07\x08";

        assert_eq!(pkt.as_slice(), ctrl.as_slice());
    }

    #[test]
    fn test_alpns()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let alpn = PP2Tlvs::TypeAlpn(vec![b"test".as_slice().to_vec()]);

        alpn.dump(&mut cur).unwrap();

       // let op: u8 = (&alpn).into();

        let reference = b"\x00\x04test";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_authority()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let alpn = PP2Tlvs::TypeAuthority("tset".into());

        alpn.dump(&mut cur).unwrap();

        //let op: u8 = (&alpn).into();

        let reference = b"tset";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_crc32()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let alpn = PP2Tlvs::TypeCrc32c(0xABCDEF01);

        alpn.dump(&mut cur).unwrap();

        //let op: u8 = (&alpn).into();

        let reference = b"\xab\xcd\xef\x01";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_netns()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let alpn = PP2Tlvs::TypeNetNs("tstt".into());

        alpn.dump(&mut cur).unwrap();

        //let op: u8 = (&alpn).into();

        let reference = b"tstt";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_noop()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let alpn = PP2Tlvs::TypeNoop;

        alpn.dump(&mut cur).unwrap();

        let reference = b"";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_ssl()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let alpn = PP2Tlvs::TypeSsl{ client: PP2TlvClient::PP2_CLIENT_SSL, verify: 0x00003210};

        alpn.dump(&mut cur).unwrap();

        //let op: u8 = (&alpn).into();

        let reference = b"\x01\x00\x00\x32\x10";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_uniqid()
    {
        const ID: &'static [u8] = b"ABCD12345678901234567890";

        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let alpn = PP2Tlvs::TypeUniqId(ID.into());

        alpn.dump(&mut cur).unwrap();

        let reference = ID;

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference);
    }

    #[test]
    fn test_ssl_cipher()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let ciph = PP2Tlvs::TypeSubtypeSslCipher("ECDHE-RSA-AES128-GCM-SHA256".into());

        ciph.dump(&mut cur).unwrap();

       // let op: u8 = (&ciph).into();

        let reference = b"ECDHE-RSA-AES128-GCM-SHA256";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_ssl_cn()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let cn = PP2Tlvs::TypeSubtypeSslCn("example.com".into());

        cn.dump(&mut cur).unwrap();

        //let op: u8 = (&cn).into();

        let reference = b"example.com";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_ssl_keyalg()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let keyalg = PP2Tlvs::TypeSubtypeSslKeyAlg("RSA2048".into());

        keyalg.dump(&mut cur).unwrap();

       // let op: u8 = (&keyalg).into();

        let reference = b"RSA2048";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_ssl_sigalg()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let sigalg = PP2Tlvs::TypeSubtypeSslSigAlg("SHA256".into());

        sigalg.dump(&mut cur).unwrap();

       // let op: u8 = (&sigalg).into();

        let reference = b"SHA256";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }

    #[test]
    fn test_ssl_version()
    {
        let mut cur = Cursor::new(Vec::<u8>::with_capacity(64));

        let vers = PP2Tlvs::TypeSubtypeSslVersion("TLSv1_3".into());

        vers.dump(&mut cur).unwrap();

        //let op: u8 = (&vers).into();

        let reference = b"TLSv1_3";

        let generated = cur.into_inner();

        assert_eq!(generated.as_slice(), reference.as_slice());
    }
}