haprox-rs 0.2.3

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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
/*-
 * 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;
use std::ffi::CStr;
use std::fmt;
use std::io::{Cursor, Read, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::ops::RangeInclusive;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net;
use std::str::FromStr;

use bitflags::bitflags;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};

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

use super::protocol_raw::{self, HEADER_UNIX_ADDR_LEN};

// -----
// The following range of 16 type values is reserved for application-specific
// data and will be never used by the PROXY Protocol. If you need more values
// consider extending the range with a type field in your TLVs.

/// values is reserved for application-specific data and will be never 
/// used by the PROXY Protocol (minimal type)
pub const PP2_TYPE_MIN_CUSTOM: u8 = 0xE0;

/// values is reserved for application-specific data and will be never 
/// used by the PROXY Protocol (max type)
pub const PP2_TYPE_MAX_CUSTOM: u8 = 0xEF;

// ----
// The following range of 8 values is reserved for future use, potentially to
// extend the protocol with multibyte type values.

/// reserved for temporary experimental use by application developers and protocol 
/// designers (min range)
pub const PP2_TYPE_MIN_EXPERIMENT: u8 = 0xF0;

/// reserved for temporary experimental use by application developers and protocol 
/// designers (max range)
pub const PP2_TYPE_MAX_EXPERIMENT: u8 = 0xF7;

// ----
// The following range of 8 values is reserved for future use, potentially to
// extend the protocol with multibyte type values.

/// reserved for future use (min range)
pub const PP2_TYPE_MIN_FUTURE: u8 = 0xF8;

/// reserved for future use (max range)
pub const PP2_TYPE_MAX_FUTURE: u8 = 0xFF;


//----
/// Max length of the TLV's payload uniq ID.
pub const MAX_UNIQ_ID_LEN_BYTES: u16 = 128;

/// Header length of TLV
pub const TLV_HEADER_LEN: u16 = 3;



// https://www.haproxy.org/download/3.2/doc/proxy-protocol.txt
// https://datatracker.ietf.org/doc/html/rfc7301

/// An OP codes definotions.
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum HdrV2Command
{
    LOCAL = 0,
    PROXY = 1,
    UNKNOWN,
}

impl From<HdrV2Command> for u8
{
    fn from(value: HdrV2Command) -> Self 
    {
        if value == HdrV2Command::UNKNOWN
        {
            panic!("can not encode the unknown command");
        }

        return value as u8;
    }
}

impl HdrV2Command
{
    pub(crate)
    fn decode(raw: u8) -> Self
    {
        match raw & protocol_raw::ProxyHdrV2::COMMAND_MASK
        {
            r if r == HdrV2Command::LOCAL.into() => return Self::LOCAL,
            r if r == HdrV2Command::PROXY.into() => return Self::PROXY,
            _ => return Self::UNKNOWN,
        }
    }
}

/// Defines the protocol versions.
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ProtocolVersion
{
    V1 = 1,
    V2 = 2,
    UNKNOWN,
}

impl From<ProtocolVersion> for u8
{
    fn from(value: ProtocolVersion) -> Self 
    {
        if value == ProtocolVersion::UNKNOWN
        {
            panic!("can not encode the unknown version");
        }

        return (value as u8) << 4;
    }
}

impl ProtocolVersion
{
    pub(crate)
    fn decode(raw: u8) -> Self
    {
        match raw >> 4
        {
            1 => return Self::V1,
            2 => return Self::V2,
            _ => return Self::UNKNOWN,
        }
    }
}

bitflags! {
    /// A client flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct PP2TlvClient: u8 
    {
        /// client connected over SSL/TLS
        const PP2_CLIENT_SSL = 0x01;
        
        /// client provided a certificate over the current connection
        const PP2_CLIENT_CERT_CONN = 0x02;

        /// client provided a certificate at least once over the TLS session this 
        /// connection belongs to
        const PP2_CLIENT_CERT_SESS = 0x04;
    }
}

/// A specific for PP2Tlv SSL.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PP2TlvsTypeSsl
{
    /// client came with something
    pub(crate) client: PP2TlvClient, 
                
    /// field will be zero if the client presented a certificate
    /// and it was successfully verified, and non-zero otherwise.
    pub(crate) verify: u32, 

    /// included sub TLVs
    pub(crate) sub_tlv: Vec<PP2Tlvs>
}

impl fmt::Display for PP2TlvsTypeSsl
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "CLIENT: {:?}, VERIFY: {}, TLVs: {}", 
            self.client, self.verify, 
            self.sub_tlv.iter().map(|t| t.to_string()).collect::<Vec<String>>().join(", "))
    }
}

/*
impl From<PP2TlvsTypeSsl> for PP2Tlvs
{
    fn from(value: PP2TlvsTypeSsl) -> Self where Self: PP2TlvDump
    {
        return Self::TypeSsl(value);
    }
}*/

/// Can be used for testing.
#[repr(u8)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PP2Tlvs
{
    /// Application-Layer Protocol Negotiation (ALPN).
    TypeAlpn(Vec<Vec<u8>>) = Self::TYPE_ALPN,

    /// "SNI" i.e the "server_name" extension as defined by RFC3546
    /// UTF8-encoded string
    TypeAuthority(String) = Self::TYPE_AUTHORITY,

    /// 32-bit number storing the CRC32c checksum of the PROXY protocol header
    TypeCrc32c(u32) = Self::TYPE_CRC32C,

    /// The TLV of this type should be ignored when parsed. The value is zero or more
    /// bytes. Can be used for data padding or alignment. Note that it can be used
    /// to align only by 3 or more bytes because a TLV can not be smaller than that.
    TypeNoop = Self::TYPE_NOOP,

    /// opaque byte sequence of up to 128 bytes generated by the upstream proxy 
    /// that uniquely identifies the connection.
    TypeUniqId(Vec<u8>) = Self::TYPE_UNIQID,

    /// SSL properties
    TypeSsl
    {
        client: PP2TlvClient,
        verify: u32,
    } = Self::TYPE_SSL,

    /// US-ASCII string representation of the TLS version (format?)
    TypeSubtypeSslVersion(Cow<'static, str>) = Self::TYPE_SUBTYPE_SSL_VERSION,

    /// In all cases, the string representation (in UTF8) of the Common Name field
    /// (OID: 2.5.4.3) of the client certificate's Distinguished Name, is appended
    /// using the TLV format and the type PP2_SUBTYPE_SSL_CN. E.g. "example.com".
    TypeSubtypeSslCn(Cow<'static, str>) = Self::TYPE_SUBTYPE_SSL_CN,
    
    /// US-ASCII string name of the used cipher, for example "ECDHE-RSA-AES128-GCM-SHA256".
    TypeSubtypeSslCipher(Cow<'static, str>) = Self::TYPE_SUBTYPE_SSL_CIPHER,

    /// US-ASCII string name of the algorithm used to sign the certificate presented by the 
    /// frontend when the incoming connection was made over an SSL/TLS transport layer, for example
    /// "SHA256".
    TypeSubtypeSslSigAlg(Cow<'static, str>) = Self::TYPE_SUBTYPE_SSL_SIGALG,

    /// US-ASCII string name of the algorithm used to generate the key of the certificate 
    /// presented by the frontend when the incoming connection was made over an SSL/TLS 
    /// transport layer, for example "RSA2048".
    TypeSubtypeSslKeyAlg(Cow<'static, str>) = Self::TYPE_SUBTYPE_SSL_KEYALG,

    /// US-ASCII string representation of the namespace's name
    TypeNetNs(String) = Self::TYPE_NETNS,
}

impl fmt::Display for PP2Tlvs
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        let id : u8= self.into();

        match self
        {
            PP2Tlvs::TypeAlpn(alpns) => 
            {
                let alpns_dec = 
                    alpns
                        .iter()
                        .map(
                            |a| 
                            std
                                ::str
                                ::from_utf8(a)
                                    .map_err(|e| map_error!(MalformedData, "{}", e))
                        )
                        .collect::<HaProxRes<Vec<&str>>>()
                        .map_err(|_e| fmt::Error)?
                        .join(",");

                write!(f, "ALPNS({:02X}): {}", id, alpns_dec)
            },
            PP2Tlvs::TypeAuthority(sni) => 
                write!(f, "SNI({:02X}): {}", id, sni),
            PP2Tlvs::TypeCrc32c(crc) => 
                write!(f, "CRC({:02X}): {}", id, crc),
            PP2Tlvs::TypeNoop => 
                write!(f, "NOOP({:02X})", id),
            PP2Tlvs::TypeUniqId(items) => 
                write!(f, "UNIQID({:02X}): {:02X?}", id, items),
            PP2Tlvs::TypeSsl{client, verify} => 
                write!(f, "SSL({:02X}): client: {:?}, verify: {}", id, client, verify),
            PP2Tlvs::TypeSubtypeSslVersion(ver) => 
                write!(f, "SSL VERSION({:02X}): {}", id, ver),
            PP2Tlvs::TypeSubtypeSslCn(cn) => 
                write!(f, "SSL CN({:02X}): {}", id, cn),
            PP2Tlvs::TypeSubtypeSslCipher(c) => 
                write!(f, "SSL CIPHER({:02X}): {}", id, c),
            PP2Tlvs::TypeSubtypeSslSigAlg(sa) => 
                write!(f, "SSL SIGALG({:02X}): {}", id, sa),
            PP2Tlvs::TypeSubtypeSslKeyAlg(ka) => 
                write!(f, "SSL KEYALG({:02X}): {}", id, ka),
            PP2Tlvs::TypeNetNs(ns) => 
                write!(f, "NETNS({:02X}): {}", id, ns),
        }
    }
}

impl From<PP2Tlvs> for u8
{
    fn from(value: PP2Tlvs) -> Self 
    {
        return (&value).into();
    }
}

impl From<&PP2Tlvs> for u8
{
    fn from(value: &PP2Tlvs) -> Self 
    {
        return unsafe { *<*const _>::from(value).cast::<Self>() };
    }
}



impl PP2Tlvs
{
    /// A constraints by range of all types.
    pub const TLV_TYPE_MAIN_RANGES: &'static [RangeInclusive<u8>] = 
        &[
            Self::TYPE_ALPN..=Self::TYPE_SSL,  
            Self::TYPE_NETNS ..= Self::TYPE_NETNS
        ];

    /// A constraints for the SSL subtypes.
    pub const TLV_TYPE_SSL_SUB_RANGE: &'static [RangeInclusive<u8>] = 
        &[Self::TYPE_SUBTYPE_SSL_VERSION ..= Self::TYPE_SUBTYPE_SSL_KEYALG];

    pub const TYPE_ALPN: u8 = 0x01;

    pub const TYPE_AUTHORITY: u8 = 0x02;

    pub const TYPE_CRC32C: u8 = 0x03;

    pub const TYPE_NOOP: u8 = 0x04;

    pub const TYPE_UNIQID: u8 = 0x05;

    pub const TYPE_SSL: u8 = 0x20;

    pub const TYPE_SUBTYPE_SSL_VERSION: u8 = 0x21;

    pub const TYPE_SUBTYPE_SSL_CN: u8 = 0x22;
    
    pub const TYPE_SUBTYPE_SSL_CIPHER: u8 = 0x23;

    pub const TYPE_SUBTYPE_SSL_SIGALG: u8 = 0x24;

    pub const TYPE_SUBTYPE_SSL_KEYALG: u8 = 0x25;

    pub const TYPE_NETNS: u8 = 0x30;

    pub 
    fn contains_subtype(&self) -> bool
    {
        let Self::TypeSsl{ .. } = self else { return false };

        return true;
    }

    pub 
    fn conntains_subtype_discr(discr: u8) -> bool
    {
        return discr == Self::TYPE_SSL;
    }
}

/// A quote from protocol descr:
/// > other values are unspecified and must not be emitted in version 2 of this
/// > protocol and must be rejected as invalid by receivers.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProxyV2AddrType
{
    /// A quote from protocol descr:
    /// > the connection is forwarded for an unknown, unspecified
    /// > or unsupported protocol. The sender should use this family when sending
    /// > LOCAL commands or when dealing with unsupported protocol families. The
    /// > receiver is free to accept the connection anyway and use the real endpoint
    /// > addresses or to reject it. The receiver should ignore address information.
    AfUnspec = 0x00,

    /// A quote from protocol descr:
    /// > the forwarded connection uses the AF_INET address family
    /// > (IPv4). The addresses are exactly 4 bytes each in network byte order,
    /// > followed by transport protocol information (typically ports).
    AfInet = 0x01,

    /// A quote from protocol descr:
    /// > the forwarded connection uses the AF_INET6 address family
    /// > (IPv6). The addresses are exactly 16 bytes each in network byte order,
    /// > followed by transport protocol information (typically ports).
    AfInet6 = 0x02,

    /// A quote from protocol descr:
    /// > the forwarded connection uses the AF_UNIX address family
    /// > (UNIX). The addresses are exactly 108 bytes each.
    AfUnix = 0x03,
}

impl From<ProxyV2AddrType> for u8
{
    fn from(value: ProxyV2AddrType) -> Self 
    {
        return value as u8;
    }
}

impl ProxyV2AddrType
{
    pub const DEF_IPV4_ADDR_LEN: u16 = 12;
    pub const DEF_IPV6_ADDR_LEN: u16 = 36;
    pub const DEF_UNIX_ADDR_LEN: u16 = 216;

    pub(crate) 
    fn decode(raw: u8) -> HaProxRes<Self>
    {
        match raw >> 4
        {
            r if r == ProxyV2AddrType::AfUnspec.into() => 
                return Ok(Self::AfUnspec),
            r if r == ProxyV2AddrType::AfInet.into() => 
                return Ok(Self::AfInet),
            r if r == ProxyV2AddrType::AfInet6.into() => 
                return Ok(Self::AfInet6),
            r if r == ProxyV2AddrType::AfUnix.into() => 
                return Ok(Self::AfUnix),
            r => 
                return_error!(ProtocolUnknownData, "can not decode address type: '{:02X}'", r),
        }
    }

    pub 
    fn get_size_by_addr_family(&self) -> Option<u16>
    {
        match self
        {
            Self::AfUnspec => 
                return None,
            Self::AfInet => 
                return Some(Self::DEF_IPV4_ADDR_LEN),
            Self::AfInet6 => 
                return Some(Self::DEF_IPV6_ADDR_LEN),
            Self::AfUnix => 
                return Some(Self::DEF_UNIX_ADDR_LEN),
        }
    }
}


/// An address re-representation. Can be initialized using `TryFrom` 
/// implementations.
/// 
/// TryFrom("ip:port", "ip:port")
/// TryFrom(IpAddr, u16, IpAddr, u16)
/// TryFrom(net::SocketAddr, net::SocketAddr)
/// TryFrom(SocketAddr, SocketAddr)
/// 
/// The type will be determined automatically.
#[derive(Clone, Debug)]
pub enum ProxyV2Addr
{
    /// AF_INET, AF_INET6
    Ip
    {
        src: SocketAddr,
        dst: SocketAddr,
    },

    /// AF_UNIX
    Unix
    {
        src: net::SocketAddr,
        dst: net::SocketAddr,
    }
}

impl Eq for ProxyV2Addr {}

impl PartialEq for ProxyV2Addr
{
    fn eq(&self, other: &Self) -> bool 
    {
        match (self, other) 
        {
            (
                Self::Ip { src: l_src, dst: l_dst }, 
                Self::Ip { src: r_src, dst: r_dst }
            ) => 
                l_src == r_src && l_dst == r_dst,

            (
                Self::Unix { src: l_src, dst: l_dst }, 
                Self::Unix { src: r_src, dst: r_dst }
            ) => 
                l_src.as_pathname() == r_src.as_pathname() && l_dst.as_pathname() == r_dst.as_pathname(),
            _ => false,
        }
    }
}

impl fmt::Display for ProxyV2Addr
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            ProxyV2Addr::Ip{ src, dst } => 
                write!(f, "SRC: {}, DST: {}", src, dst),
            ProxyV2Addr::Unix{ src, dst } => 
                write!(f, "SRC: {:?}, DST: {:?}", src, dst)
        }
    }
}

impl TryFrom<(IpAddr, u16, IpAddr, u16)> for ProxyV2Addr
{
    type Error = HaProxErr;

    /// # Arguments
    /// 
    /// * `value.0` - source IP address [IpAddr]
    /// 
    /// * `value.1` - source port [u16]
    /// 
    /// * `value.2` - destination IP address [IpAddr]
    /// 
    /// * `value.3` - destination port [u16]
    fn try_from(value: (IpAddr, u16, IpAddr, u16)) -> Result<Self, Self::Error> 
    {
        let src = SocketAddr::new(value.0, value.1);
        let dst = SocketAddr::new(value.2, value.3);

        return Ok(Self::Ip{ src: src, dst: dst });
    }
}

impl TryFrom<(SocketAddr, SocketAddr)> for ProxyV2Addr
{
    type Error = HaProxErr;

    /// # Arguments
    /// 
    /// * `value.0` - source address [SocketAddr]
    /// 
    /// * `value.1` - destination address [SocketAddr]
    fn try_from(value: (SocketAddr, SocketAddr)) -> Result<Self, Self::Error> 
    {
        return Ok(Self::Ip{ src: value.0, dst: value.1 });
    }
}

/// Attempts to convert from tuple (source, dst) from [net::SocketAddr] into [ProxyV2Addr].  
impl TryFrom<(net::SocketAddr, net::SocketAddr)> for ProxyV2Addr
{
    type Error = HaProxErr;

    /// # Arguments
    /// 
    /// * `value.0` - source address [net::SocketAddr]
    /// 
    /// * `value.1` - destination address [net::SocketAddr]
    fn try_from(value: (net::SocketAddr, net::SocketAddr)) -> Result<Self, Self::Error> 
    {
        return Ok(Self::Unix{ src: value.0, dst: value.1 });
    }
}

/// Attempts to convert tuple (source, destination) from [str] into [ProxyV2Addr].
impl TryFrom<(&str, &str)> for ProxyV2Addr
{
    type Error = HaProxErr;

    /// # Arguments
    /// 
    /// * `value.0` - source address [str]
    /// 
    /// * `value.1` - destination address [str]
    fn try_from(value: (&str, &str)) -> Result<Self, Self::Error> 
    {
        if let Ok(src) = SocketAddr::from_str(value.0)
        {
            let Ok(dst) = SocketAddr::from_str(value.1)
            else 
            {
                return_error!(ArgumentEinval, "can not convert '{}' to SocketAddr", 
                    common::sanitize_str_unicode(value.1));
            };

            return Ok(Self::Ip{ src: src, dst: dst });
        }
        else if let Ok(src) = net::SocketAddr::from_pathname(value.0)
        {
            let Ok(dst) = net::SocketAddr::from_pathname(value.1)
            else 
            {
                return_error!(ArgumentEinval, "can not convert '{}' to net::SocketAddr", 
                    common::sanitize_str_unicode(value.1));
            };

            return Ok(Self::Unix{ src: src, dst: dst });
        }
        else
        {
            return_error!(ArgumentEinval, "can not convert '{}' to either SocketAddr or net::SocketAddr", 
                common::sanitize_str_unicode(value.0));
        }
    }
}

impl ProxyV2Addr
{
    /// Returns the length in bytes for the current address. It returns full size, but not
    /// the actual ocupied length (for unix addresses).
    #[inline]
    pub 
    fn get_len(&self) -> u16
    {
        return self.as_addr_family().get_size_by_addr_family().unwrap();
    }

    /// Returns the address type.
    #[inline]
    pub 
    fn as_addr_family(&self) -> ProxyV2AddrType
    {
        match self
        {
            ProxyV2Addr::Ip{ src, .. } => 
            {
                if src.is_ipv4() == true
                {
                    return ProxyV2AddrType::AfInet;
                }
                else
                {
                    return ProxyV2AddrType::AfInet6;
                }
            }
            ProxyV2Addr::Unix{ .. } => 
                return ProxyV2AddrType::AfUnix
        }
    }

    /// Reads the address section of the HaProxy. The address family should be 
    /// obtained from the same packet before. The `cur` must point to the beginning
    /// of the address block.
    /// 
    /// # Returns
    /// 
    /// The [Result] is returned. The [Option::None] will be returned only if the
    /// `addr_fam` is [ProxyV2AddrType::AfUnspec].
    pub 
    fn read(addr_fam: ProxyV2AddrType, cur: &mut Cursor<&[u8]>) -> HaProxRes<Option<Self>>
    {
        match addr_fam
        {
            ProxyV2AddrType::AfUnspec => Ok(None),
            ProxyV2AddrType::AfInet => 
            {
                let src = IpAddr::from(Ipv4Addr::from_bits(cur.read_u32::<BigEndian>().map_err(common::map_io_err)?));
                let dst = IpAddr::from(Ipv4Addr::from_bits(cur.read_u32::<BigEndian>().map_err(common::map_io_err)?));
                let src_port = cur.read_u16::<BigEndian>().map_err(common::map_io_err)?;
                let dst_port = cur.read_u16::<BigEndian>().map_err(common::map_io_err)?;

                return Ok(Some(Self::try_from((src, src_port, dst, dst_port))?));
            },
            ProxyV2AddrType::AfInet6 => 
            {
                let src = IpAddr::from(Ipv6Addr::from_bits(cur.read_u128::<BigEndian>().map_err(common::map_io_err)?));
                let dst = IpAddr::from(Ipv6Addr::from_bits(cur.read_u128::<BigEndian>().map_err(common::map_io_err)?));
                let src_port = cur.read_u16::<BigEndian>().map_err(common::map_io_err)?;
                let dst_port = cur.read_u16::<BigEndian>().map_err(common::map_io_err)?;

                return Ok(Some(Self::try_from((src, src_port, dst, dst_port))?));
            },
            ProxyV2AddrType::AfUnix => 
            {
                let mut n_src: [u8; HEADER_UNIX_ADDR_LEN] = [0_u8; HEADER_UNIX_ADDR_LEN];
                cur.read(&mut n_src).map_err(common::map_io_err)?;

                let mut n_dst: [u8; HEADER_UNIX_ADDR_LEN] = [0_u8; HEADER_UNIX_ADDR_LEN];
                cur.read(&mut n_dst).map_err(common::map_io_err)?;

                let src_s = 
                    net::SocketAddr::from_pathname(
                        CStr::from_bytes_until_nul(&n_src)
                            .map_err(|e| 
                                map_error!(MalformedData, "cannot read unix path, error: {}", e)
                            )?
                            .to_str()
                            .map_err(|e|
                                map_error!(MalformedData, "cannot read unix path, error: {}", e)
                            )?
                    )
                    .map_err(|e|
                        map_error!(MalformedData, "cannot read unix path, error: {}", e)
                    )?;

                let dst_s = 
                    net::SocketAddr::from_pathname(
                        CStr::from_bytes_until_nul(&n_dst)
                            .map_err(|e| 
                                map_error!(MalformedData, "cannot read unix path, error: {}", e)
                            )?
                            .to_str()
                            .map_err(|e|
                                map_error!(MalformedData, "cannot read unix path, error: {}", e)
                            )?
                    )
                    .map_err(|e|
                        map_error!(MalformedData, "cannot read unix path, error: {}", e)
                    )?;

                return Ok(Some(Self::try_from((src_s, dst_s))?));
            },
        }
    }

    /// Writes the content of the current instance to packet in format of 
    /// the HaProxy address. The `cur` [Cursor] should point to the
    /// beginning of the address block.
    pub  
    fn write(&self, cur: &mut Cursor<Vec<u8>>) -> HaProxRes<()>
    {
        match self
        {
            ProxyV2Addr::Ip{ src, dst } => 
            {
                match src.ip()
                {
                    IpAddr::V4(ipv4_addr) => 
                        cur.write_u32::<BigEndian>(ipv4_addr.to_bits()).map_err(common::map_io_err)?,
                    IpAddr::V6(ipv6_addr) => 
                        cur.write_u128::<BigEndian>(ipv6_addr.to_bits()).map_err(common::map_io_err)?,
                }

                match dst.ip()
                {
                    IpAddr::V4(ipv4_addr) => 
                        cur.write_u32::<BigEndian>(ipv4_addr.to_bits()).map_err(common::map_io_err)?,
                    IpAddr::V6(ipv6_addr) => 
                        cur.write_u128::<BigEndian>(ipv6_addr.to_bits()).map_err(common::map_io_err)?,
                }

                cur.write_u16::<BigEndian>(src.port()).map_err(common::map_io_err)?;
                cur.write_u16::<BigEndian>(dst.port()).map_err(common::map_io_err)?;
            },
            ProxyV2Addr::Unix { src, dst } => 
            {
                let src_p = 
                    src.as_pathname().ok_or_else(|| map_error!(ArgumentEinval, "UNIX src socket addr is not path"))?;
                let dst_p = 
                    dst.as_pathname().ok_or_else(|| map_error!(ArgumentEinval, "UNIX src socket addr is not path"))?;

                let src_b = src_p.as_os_str().as_bytes();
                let dst_b = dst_p.as_os_str().as_bytes();

                if src_b.len() > HEADER_UNIX_ADDR_LEN
                {
                    return_error!(ArgumentEinval, "socket path: '{}' longer than: '{}'", 
                        src_p.display(), HEADER_UNIX_ADDR_LEN);
                }
                else if dst_b.len() > HEADER_UNIX_ADDR_LEN
                {
                    return_error!(ArgumentEinval, "socket path: '{}' longer than: '{}'", 
                        dst_p.display(), HEADER_UNIX_ADDR_LEN);
                }

                
                let mut n_src: [u8; HEADER_UNIX_ADDR_LEN] = [0_u8; HEADER_UNIX_ADDR_LEN];
                n_src[0..src_b.len()].copy_from_slice(src_b);

                cur.write_all(&n_src).map_err(common::map_io_err)?;

                let mut n_dst: [u8; HEADER_UNIX_ADDR_LEN] = [0_u8; HEADER_UNIX_ADDR_LEN];
                n_dst[0..dst_b.len()].copy_from_slice(dst_b);

                cur.write_all(&n_dst).map_err(common::map_io_err)?;
            }
        }

        return Ok(());
    }
}

/// A transport family.
/// > Other values are unspecified and must not be emitted in version 2 of this
/// > protocol and must be rejected as invalid by receivers.`
#[repr(u8)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProxyTransportFam
{
    /// > the connection is forwarded for an unknown, unspecified
    /// > or unsupported protocol. The sender should use this family when sending
    /// > LOCAL commands or when dealing with unsupported protocol families. The
    /// > receiver is free to accept the connection anyway and use the real endpoint
    /// > addresses or to reject it. The receiver should ignore address information.
    UNSPEC = 0x00,

    /// > the forwarded connection uses a SOCK_STREAM protocol (eg:
    /// > TCP or UNIX_STREAM). When used with AF_INET/AF_INET6 (TCP), the addresses
    /// > are followed by the source and destination ports represented on 2 bytes
    /// > each in network byte order.
    STREAM,

    /// > the forwarded connection uses a SOCK_DGRAM protocol (eg:
    /// > UDP or UNIX_DGRAM). When used with AF_INET/AF_INET6 (UDP), the addresses
    /// > are followed by the source and destination ports represented on 2 bytes
    /// > each in network byte order.
    DGRAM,
}

impl fmt::Display for ProxyTransportFam
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            Self::UNSPEC => write!(f, "UNSPEC"),
            Self::STREAM => write!(f, "STREAM"),
            Self::DGRAM => write!(f, "DGRAM"),
        }
    }
}

impl From<ProxyTransportFam> for u8
{
    fn from(value: ProxyTransportFam) -> Self 
    {
        return value as u8;
    }
}

impl From<&ProxyTransportFam> for u8
{
    fn from(value: &ProxyTransportFam) -> Self 
    {
        return unsafe { *<*const _>::from(value).cast::<Self>() };
    }
}

impl ProxyTransportFam
{
    pub(crate) 
    fn decode(value: u8) -> HaProxRes<Self>
    {
        match value & protocol_raw::ProxyHdrV2::TRANSPT_MASK
        {
            v if ProxyTransportFam::UNSPEC as u8 == v => 
                return Ok(Self::UNSPEC),
            v if ProxyTransportFam::STREAM as u8 == v => 
                return Ok(Self::STREAM),
            v if ProxyTransportFam::DGRAM as u8 == v => 
                return Ok(Self::DGRAM),
            _ => 
                return_error!(ProtocolUnknownData, "unknown transport {:02X}", value)
        }
    }
}

#[cfg(test)]
mod tests
{
    use core::fmt;
    use std::{slice, time::Instant};

    use crate::protocol::{protocol::{PP2TlvClient, ProxyTransportFam, ProxyV2Addr}, protocol_composer::{HdrV2OpLocal, HdrV2OpProxy, ProxyHdrV2}, protocol_raw::{self, HEADER_MAGIC_V2, HEADER_MAGINC_LEN}, PP2TlvUniqId};
    #[test]
    fn test_hdr1()
    {
        
        for _ in 0..10
        {
            let s = Instant::now();
            let _local = ProxyHdrV2::<HdrV2OpLocal>::new();

            let e = s.elapsed();

            println!("{:?}", e);
        }

        let buf = ProxyHdrV2::<HdrV2OpLocal>::new();


        
        let mut sign: [u8; HEADER_MAGINC_LEN] = [0_u8; HEADER_MAGINC_LEN];
        sign.copy_from_slice(HEADER_MAGIC_V2);
        let ctrl =
            vec![
                protocol_raw::ProxyHdrV2
                {
                    signature: sign,
                    ver_cmd: 0x20,
                    fam: 0,
                    len: 0,
                    address: [],
                }
            ];

            println!("{} {}", buf.len(), size_of::<protocol_raw::ProxyHdrV2>());
        let ctrl_buf = unsafe { slice::from_raw_parts(ctrl.as_ptr() as *const _ as *const u8, size_of::<protocol_raw::ProxyHdrV2>()) };

        assert_eq!(buf.as_slice(), ctrl_buf);
    }

    #[test]
    fn test_proxy_compose()
    {
        struct UniqIdHolder;
        impl UniqIdHolder
        {
            const ID: &'static [u8] = b"ABCD12345678901234567890";
        }
        impl fmt::Display for UniqIdHolder
        {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result 
            {
                write!(f, "")
            }
        }
        impl PP2TlvUniqId for UniqIdHolder
        {
            fn into_bytes(&self) -> Vec<u8> 
            {
                Self::ID.to_vec()
            }
        
            fn get_len(&self) -> u16 
            {
                Self::ID.len() as u16
            }
        }
        for _ in 0..10
        {
            let addr: ProxyV2Addr = ProxyV2Addr::try_from(("127.0.0.1:4567", "127.0.0.1:443")).unwrap();
            let id = UniqIdHolder;

            let s = Instant::now();
            let mut proxy = 
                ProxyHdrV2::<HdrV2OpProxy>::new(ProxyTransportFam::STREAM, addr).unwrap();

            let mut plts = proxy.set_plts();
            plts.add_crc32().unwrap();
            plts.add_authority("www.example.com").unwrap();
            plts.add_uniq_id(id).unwrap();
            drop(plts);

            let e = s.elapsed();

            println!("prep: {:?}", e);
        
            let s = Instant::now();
            let _buf: Vec<u8> = proxy.try_into().unwrap();
            let e = s.elapsed();

            println!("{:?}", e);
        }

       // assert_eq!(buf.as_slice(), ctrl_buf);
       return;
    }

    #[test]
    fn test_hdr2()
    {
        let addr: ProxyV2Addr = ProxyV2Addr::try_from(("127.0.0.1:39754", "127.0.0.67:11883")).unwrap();

        let s = Instant::now();
        let mut proxy = 
            ProxyHdrV2::<HdrV2OpProxy>::new(ProxyTransportFam::STREAM, addr).unwrap();
      
        let plts = proxy.set_plts();

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

        sub_ssl.add_ssl_sub_version("TLSv1.2").unwrap();

        sub_ssl.done().unwrap();


        let e = s.elapsed();

        println!("prep: {:?}", e);

        let s = Instant::now();
        let buf: Vec<u8> = proxy.try_into().unwrap();
        let e = s.elapsed();

        println!("{:?}", e);
        
        
        let reference = 
            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";

        //println!("{:02X?}\n{:02X?}", buf.as_slice(), reference.as_slice());

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