haprox-rs 0.2.0

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
1017
1018
1019
1020
1021
/*-
 * 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::mem::offset_of;
use std::{borrow::Cow, fmt, io::Cursor, marker::PhantomData};
use std::io::Read;
use byteorder::{BigEndian, ReadBytesExt};
use crc32fast::Hasher;

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

use super::
{
    protocol::
    {
        HdrV2Command, 
        PP2TlvClient, 
        PP2Tlvs, 
        ProtocolVersion, 
        ProxyTransportFam, 
        ProxyV2Addr, 
        ProxyV2AddrType
    }, 
    protocol_raw, 
    PP2TlvRestore
};

/// A HaProxy V2 parser main instance.
pub struct ProxyV2Parser<'t, EXT: PP2TlvRestore = ProxyV2Dummy>
{
    /// A received packed which should contain the proxy pkt.
    buffer: &'t [u8],

    /// Phantom for the extension for the protocol.
    _p: PhantomData<EXT>
}

impl<'t> ProxyV2Parser<'t>
{
    /// Constructs the instance from the temporary reference to the buffer. 
    pub 
    fn try_from_slice(value: &'t [u8]) -> HaProxRes<Self>
    {
        let pkt_size = Self::new_from(value)?;

        let tmp = Self{ buffer: &value[0..pkt_size], _p: PhantomData };

        tmp.post_check()?;

        return Ok(tmp);
    }
}

impl<'t, EXT: PP2TlvRestore> ProxyV2Parser<'t, EXT>
{
    /// Constructs the instance from the temporary reference to the buffer
    /// with custom extenal TLV parser for custom TLV extensions.
    pub 
    fn try_from_slice_custom(value: &'t [u8]) -> HaProxRes<Self>
    {
        let pkt_size = Self::new_from(value)?;

        let tmp = Self{ buffer: &value[0..pkt_size], _p: PhantomData };

        tmp.post_check()?;

        return Ok(tmp);
    }
}

impl<'t, EXT: PP2TlvRestore> ProxyV2Parser<'t, EXT>
{
    fn post_check(&self) -> HaProxRes<()>
    {
        let _ = self.get_address_family()?;
        let _ = self.get_transport()?;

        return Ok(());
    }

    /// Internal function.
    /// 
    /// Checks the header for the specific pattern to determine if this is a HaProxy
    /// mesage and if it initial header bits are valid.
    fn new_from(value: &[u8]) -> HaProxRes<usize>
    {
        if value.len() <= protocol_raw::HEADER_MAGIC_V1.len()
        {
            return_error!(IncorrectBanner, "protocol with footprint '{:02X?}' unknown", 
                value);
        }
        else if &value[0..protocol_raw::HEADER_MAGIC_V1.len()] == protocol_raw::HEADER_MAGIC_V1
        {
            return_error!(ProtocolNotSuported, "V1 protocol is not supported");
        }
        else if value.len() < size_of::<protocol_raw::ProxyHdrV2>()
        {
            return_error!(ProtocolMsgIncomplete, "protocol with footprint '{:02X?}' unknown", 
                value);
        }
        else if &value[0..protocol_raw::HEADER_MAGIC_V2.len()] != protocol_raw::HEADER_MAGIC_V2
        {
            return_error!(IncorrectBanner, "protocol with footprint '{:02X?}' unknown", 
                value);
        }
        else if value[offset_of!(protocol_raw::ProxyHdrV2, ver_cmd)] & protocol_raw::ProxyHdrV2::VERSION_MASK != 
            protocol_raw::ProxyHdrV2::VERSION_RAW
        {
            return_error!(MalformedData, "protocol version '{:02X?}' incorrect", 
                value[offset_of!(protocol_raw::ProxyHdrV2, ver_cmd)]);
        }

        let payload_len =  
            [
                value[offset_of!(protocol_raw::ProxyHdrV2, len)],
                value[offset_of!(protocol_raw::ProxyHdrV2, len)+1]
            ];

        let full_size = u16::from_be_bytes(payload_len) + protocol_raw::ProxyHdrV2::HEADER_LEN as u16;

        if value.len() < full_size as usize
        {
            return_error!(ProtocolMsgIncomplete, "fragmented pkt received, declared len + header: {}, received len: {}",
                full_size, value.len());
        }

        return Ok(full_size as usize);
    }

    /// Extracts and decodes the protocol version from the packet.
    pub 
    fn get_proto_version(&self) -> ProtocolVersion
    {
        return ProtocolVersion::decode(self.buffer[offset_of!(protocol_raw::ProxyHdrV2, ver_cmd)]);
    }

    /// Extracts and decodes the protocol command code from the packet.
    pub 
    fn get_proto_command(&self) -> HdrV2Command
    {
        return HdrV2Command::decode(self.buffer[offset_of!(protocol_raw::ProxyHdrV2, ver_cmd)]);
    }

    /// Extracts and decodes the transport type from the packet.
    pub 
    fn get_transport(&self) -> HaProxRes<ProxyTransportFam>
    {
        return ProxyTransportFam::decode(self.buffer[offset_of!(protocol_raw::ProxyHdrV2, fam)]);
    }

    /// Extracts and decodes the address family from the packet. It doesnot extract address. 
    pub 
    fn get_address_family(&self) -> HaProxRes<ProxyV2AddrType>
    {
        return ProxyV2AddrType::decode(self.buffer[offset_of!(protocol_raw::ProxyHdrV2, fam)]);
    }

    /// Returns the size of the packet (without header len).
    pub 
    fn get_palyload_len(&self) -> u16
    {
        let hi =  
            [
                self
                    .buffer[offset_of!(protocol_raw::ProxyHdrV2, len)],
                self
                    .buffer[offset_of!(protocol_raw::ProxyHdrV2, len)+1]
            ];
            

        return u16::from_be_bytes(hi);
    }

    /// Returns the full size of the packet.
    pub 
    fn get_full_len(&self) -> u16
    {
        let hi =  
            [
                self
                    .buffer[offset_of!(protocol_raw::ProxyHdrV2, len)],
                self
                    .buffer[offset_of!(protocol_raw::ProxyHdrV2, len)+1]
            ];
            

        return u16::from_be_bytes(hi) + protocol_raw::ProxyHdrV2::HEADER_LEN as u16;
    }

    /// Extracts the address section from the packet. The address family can be obtained from the 
    /// returned instance.
    /// 
    /// # Returns
    /// 
    /// A [HaProxRes] is returned with:
    /// 
    /// * [Result::Ok] - the  [Option] with:
    /// 
    /// * * [Option::Some] - a parsed address is returned in form of [ProxyV2Addr]
    /// 
    /// * * [Option::None] - if address family is unspecified.
    /// 
    /// * [Result::Err] - an error description.
    pub 
    fn get_address(&self) -> HaProxRes<Option<ProxyV2Addr>>
    {
        let addr_fam = self.get_address_family()?;

        let Some(addr_len) = addr_fam.get_size_by_addr_family()
        else { return Ok(None) };

        let buf_len = self.buffer.len() - size_of::<protocol_raw::ProxyHdrV2>();

        if buf_len < addr_len as usize
        {
            return_error!(ProtocolMsgIncomplete, "cannot read address, msg len: '{}', addr len: '{}'", 
                buf_len, addr_len);
        }

        let mut cur = Cursor::new(&self.buffer.as_ref()[offset_of!(protocol_raw::ProxyHdrV2, address)..]);

        return ProxyV2Addr::read(addr_fam, &mut cur);
    }

    /// Creates an iterator over TLVs which are found in the packet. This is flat iterator i.e if
    /// TLV contains a subcodes, it will be returned as it is just in a 1D array. You should track
    /// if item contains a subcode and a subcode is returned.
    pub 
    fn get_tlvs_iter(&self) -> Option<ProxyV2TlvIter<EXT>>
    {
        let addr_fam = self.get_address_family().ok()?.get_size_by_addr_family()?;

        if self.get_palyload_len() - addr_fam == 0
        {
            return None;
        }

        let addr_size = self.get_address_family().ok()?.get_size_by_addr_family()? as usize;

        let tlv_offset_start = 
            offset_of!(protocol_raw::ProxyHdrV2, address) + addr_size;

        let itr = 
            ProxyV2TlvIter
            {
                curs: 
                    vec![
                        ProxyV2TlvIterTlv
                        {
                            cur: Cursor::new(&self.buffer.as_ref()[tlv_offset_start..]),
                            parent_tlv_idx: None,
                        },
                    ],
                _p: PhantomData
            };

        return Some(itr);
    }

    /// Calculates the CRC of message and returns the result.
    pub 
    fn check_crc(&self) -> HaProxRes<bool>
    {
        /*let PP2Tlvs::TypeCrc32c(crcpkt) = crc 
            else { return_error!(ArgumentEinval, "PP2Tlvs type is not TypeCrc32c") };*/

        let mut crc32: Option<u32> = None;

        // init hasher
        let mut hasher = Hasher::new();

        let addr_fam_len = 
            self
                .get_address_family()?
                .get_size_by_addr_family()
                .ok_or_else(||
                    map_error!(ArgumentEinval, "unknown address family")
                )? as usize;

        
        let full_hdr_len = addr_fam_len + protocol_raw::ProxyHdrV2::HEADER_LEN;
        
        // calculate crc header
        hasher.update(&self.buffer[0..full_hdr_len]);

        let payload_len = self.get_palyload_len() as usize - addr_fam_len;

        let mut cur = Cursor::new(&self.buffer[full_hdr_len..]);

        while cur.position() < payload_len as u64
        {
            let s = cur.position() as usize;

            let op = cur.read_u8().map_err(map_io_err)?;
            let len = cur.read_u16::<BigEndian>().map_err(map_io_err)?;

            if op == PP2Tlvs::TYPE_CRC32C
            {
                crc32 = Some(cur.read_u32::<BigEndian>().map_err(map_io_err)?);

                hasher.update(&[op]);
                hasher.update(len.to_be_bytes().as_slice());
                hasher.update(&[0]);
            }
            else
            {
                let last = s+2+len as usize;

                hasher.update(&self.buffer[s..last]);
                cur.set_position(last as u64);
            }
        }

        if let Some(cr) = crc32
        {
            return Ok(cr == hasher.finalize());
        }
        else
        {
            return_error!(ArgumentEinval, "no CRC TLV found!");
        }
    }
}


/// A dummy implementation of the TVL protocol extension.
#[derive(Clone, Debug)]
pub enum ProxyV2Dummy {}

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

impl PP2TlvRestore for ProxyV2Dummy
{
    fn restore(_tlv_type: u8, _cur: &mut Cursor<&[u8]>) -> HaProxRes<Self> where Self: Sized 
    {
        return_error!(ArgumentEinval, "assertion trap, DUMMY external decoder");
    }
    
    fn is_in_range(_tlv_type: u8, _tlv_parent_type: Option<u8>) -> bool 
    {
        return false;
    }

    fn contains_subtype(&self) -> bool 
    {
        return false;
    }
}

/// Implementation of the [PP2TlvRestore] for the build-in protocol [PP2Tlvs] items.
impl PP2TlvRestore for PP2Tlvs
{
    fn contains_subtype(&self) -> bool 
    {
        return self.contains_subtype();    
    }

    fn is_in_range(tlv_type: u8, tlv_parent_type: Option<u8>) -> bool 
    {
        if let Some(p_tlv) = tlv_parent_type
        {
            if p_tlv == Self::TYPE_SSL
            {
                return Self::TLV_TYPE_SSL_SUB_RANGE.iter().any(|tlv| tlv.contains(&tlv_type));
            }
            else
            {
                return false;
            }
        }

        return Self::TLV_TYPE_MAIN_RANGES.iter().any(|tlv| tlv.contains(&tlv_type));
    }

    fn restore(tlv_type: u8, cur: &mut Cursor<&[u8]>) -> HaProxRes<Self> where Self: Sized 
    {
        let tlv_len = cur.get_ref().len();

        match tlv_type
        {
            Self::TYPE_ALPN =>
            {
                let mut alpns: Vec<Vec<u8>> = Vec::with_capacity(2);

                while let Some(alpn_len) = cur.read_u16::<BigEndian>().ok()
                {
                    let mut alpn: Vec<u8> = vec![0_u8; alpn_len as usize];

                    cur.read_exact(&mut alpn).map_err(common::map_io_err)?;

                    alpns.push(alpn);
                }

                return Ok(Self::TypeAlpn(alpns));
            },
            Self::TYPE_AUTHORITY =>
            {
                let mut authority: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut authority).map_err(common::map_io_err)?;

                return Ok(
                    Self::TypeAuthority(
                        String::from_utf8(authority)
                            .map_err(|e| 
                                map_error!(MalformedData, "TLV TYPE_AUTHORITY restore error: '{}'", e)
                            )?
                    )
                );
            },
            Self::TYPE_CRC32C => 
            {
                let crc = cur.read_u32::<BigEndian>().map_err(common::map_io_err)?;

                return Ok(Self::TypeCrc32c(crc));
            },
            Self::TYPE_NOOP => 
            {
                return Ok(Self::TypeNoop);
            },
            Self::TYPE_UNIQID =>
            {
                let mut authority: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut authority).map_err(common::map_io_err)?;

                return Ok(
                    Self::TypeUniqId(authority)
                );
            },
            Self::TYPE_SSL =>
            {
                let client_bits = cur.read_u8().map_err(common::map_io_err)?;

                let client = 
                    PP2TlvClient::from_bits(client_bits)
                        .ok_or_else(|| map_error!(ProtocolUnknownData, "TLV TYPE_SSL unknown client bits: {}", client_bits))?;

                let verify = cur.read_u32::<BigEndian>().map_err(common::map_io_err)?;

                return Ok(
                    Self::TypeSsl{ client: client, verify: verify }
                );
            },
            Self::TYPE_SUBTYPE_SSL_VERSION => 
            {
                let mut ssl_version: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut ssl_version).map_err(common::map_io_err)?;

                let ssl_version_str = 
                    String::from_utf8(ssl_version)
                        .map_err(|e| 
                            map_error!(MalformedData, "TLV TYPE_SUBTYPE_SSL_VERSION restore error: '{}'", e)
                        )?;

                return Ok(
                    Self::TypeSubtypeSslVersion(Cow::Owned(ssl_version_str))
                );
            },
            Self::TYPE_SUBTYPE_SSL_CN =>
            {
                let mut ssl_cn: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut ssl_cn).map_err(common::map_io_err)?;

                let ssl_cn = 
                    String::from_utf8(ssl_cn)
                        .map_err(|e| 
                            map_error!(MalformedData, "TLV TYPE_SUBTYPE_SSL_VERSION restore error: '{}'", e)
                        )?;

                return Ok(
                    Self::TypeSubtypeSslCn(Cow::Owned(ssl_cn))
                );
            },
            Self::TYPE_SUBTYPE_SSL_CIPHER => 
            {
                let mut ssl_cipher: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut ssl_cipher).map_err(common::map_io_err)?;

                let ssl_cipher = 
                    String::from_utf8(ssl_cipher)
                        .map_err(|e| 
                            map_error!(MalformedData, "TLV TYPE_SUBTYPE_SSL_VERSION restore error: '{}'", e)
                        )?;

                return Ok(
                    Self::TypeSubtypeSslCipher(Cow::Owned(ssl_cipher))
                );
            },
            Self::TYPE_SUBTYPE_SSL_SIGALG =>
            {
                let mut ssl_sigalg: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut ssl_sigalg).map_err(common::map_io_err)?;

                let ssl_sigalg = 
                    String::from_utf8(ssl_sigalg)
                        .map_err(|e| 
                            map_error!(MalformedData, "TLV TYPE_SUBTYPE_SSL_VERSION restore error: '{}'", e)
                        )?;

                return Ok(
                    Self::TypeSubtypeSslSigAlg(Cow::Owned(ssl_sigalg))
                );
            },
            Self::TYPE_SUBTYPE_SSL_KEYALG =>
            {
                let mut ssl_keyalg: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut ssl_keyalg).map_err(common::map_io_err)?;

                let ssl_keyalg = 
                    String::from_utf8(ssl_keyalg)
                        .map_err(|e| 
                            map_error!(MalformedData, "TLV TYPE_SUBTYPE_SSL_VERSION restore error: '{}'", e)
                        )?;

                return Ok(
                    Self::TypeSubtypeSslKeyAlg(Cow::Owned(ssl_keyalg))
                );
            },
            Self::TYPE_NETNS => 
            {
                let mut netns: Vec<u8> = vec![0_u8; tlv_len];

                cur.read_exact(&mut netns).map_err(common::map_io_err)?;

                let netns = 
                    String::from_utf8(netns)
                        .map_err(|e| 
                            map_error!(MalformedData, "TLV TYPE_SUBTYPE_SSL_VERSION restore error: '{}'", e)
                        )?;

                return Ok(
                    Self::TypeNetNs(netns)
                );
            },
            _ => 
                return_error!(ProtocolUnknownData, "unknown TLV type: {}", tlv_type)
        }
    }
}

/// An `enum` which is returned by the TLV iterator. It may contain either parsed TLV or 
/// error description which occured during parsing. Normally, in case of error, the 
/// parsing should be stopped and connection dropped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProxyV2TlvSource<EXT: PP2TlvRestore>
{
    /// A base implementation of the protocl.
    Internal(PP2Tlvs),

    /// A user's extension to the protocol.
    External(EXT),
    
    /// Error during parsing.
    Error(HaProxErr),
}

impl<EXT: PP2TlvRestore> ProxyV2TlvSource<EXT>
{
    fn new_internal(pp2: HaProxRes<PP2Tlvs>) -> Self
    {
        return 
            pp2.map_or_else(|e| Self::Error(e), |f| Self::Internal(f));
    }

    fn new_external(pp2: HaProxRes<EXT>) -> Self
    {
        return 
            pp2.map_or_else(|e| Self::Error(e), |f| Self::External(f));
    }

    fn new_error(err: HaProxErr) -> Self
    {
        return Self::Error(err);
    }

    fn new_io_error(err: std::io::Error) -> Self
    {
        return Self::Error(map_error!(IoError, "while reading TLV, error: {}", err));
    }

    /// Consumes the instance returning the [PP2Tlvs] build-in TLV through [Option]. 
    /// If instance os not `Internal` then instance will be lost.
    pub 
    fn take_internal(self) -> Option<PP2Tlvs>
    {
        let Self::Internal(s) = self else {return None};

        return Some(s);
    }

    /// Consumes the instance returning the [PP2Tlvs] build-in TLV through [Option]. 
    /// If instance os not `External` then instance will be lost.
    pub 
    fn take_external(self) -> Option<EXT>
    {
        let Self::External(s) = self else {return None};

        return Some(s);
    }

    /// Checks if current instance constains the subtype. For `Error` `false` is
    /// always returned.
    pub 
    fn contains_subtype(&self) -> bool
    {
        match self
        {
            Self::Internal(i) => 
                return i.contains_subtype(),
            Self::External(e) => 
                return e.contains_subtype(),
            _ => 
                return false
        }
    }
    
}

/// TLV iterator instance.
#[derive(Debug)]
struct ProxyV2TlvIterTlv<'iter>
{
    /// A cursor to the current data.
    cur: Cursor<&'iter [u8]>,

    /// A parent (previous) TLV's ID.
    parent_tlv_idx: Option<u8>,
}

/// A multilayer iterator instance.
#[derive(Debug)]
pub struct ProxyV2TlvIter<'iter, EXT>
{
    /// A heap of the cursors. If iterator reaches subtype, the
    /// previous cursor will be pushed to heap.
    curs: Vec<ProxyV2TlvIterTlv<'iter>>,

    /// A phantom.
    _p: PhantomData<EXT>
}

impl<'iter, EXT: PP2TlvRestore> ProxyV2TlvIter<'iter, EXT>
{
    fn get_last_cur(&self) -> &Cursor<&'iter [u8]>
    {
        return &self.curs.last().unwrap().cur;
    }

    fn get_last_mut_cur(&mut self) -> &mut Cursor<&'iter [u8]>
    {
        return &mut self.curs.last_mut().unwrap().cur;
    }

    fn get_parent_tlv(&self) -> Option<u8>
    {
        return self.curs.last().unwrap().parent_tlv_idx;
    }

    /*
    fn get_last_cur(&self) -> &ProxyV2TlvIterTlv<'iter>
    {
        return self.curs.last().unwrap();
    }

    fn get_last_mut_cur(&mut self) -> &mut ProxyV2TlvIterTlv<'iter>
    {
        return self.curs.last_mut().unwrap();
    }
     */
}

impl<'iter, EXT: PP2TlvRestore> Iterator for ProxyV2TlvIter<'iter, EXT>
{
    type Item = ProxyV2TlvSource<EXT>;

    fn next(&mut self) -> Option<Self::Item> 
    {
        // check if the end of the section was reached
        if self.get_last_cur().get_ref().len() <= self.get_last_cur().position() as usize
        {
            if self.curs.len() == 1
            {
                // nothing left
                return None;
            }
            else
            {
                // return back on one level
                let _ = self.curs.pop();
                return self.next();
            }
        }

        // read type of the tlv
        let tlv_type = 
            match self.get_last_mut_cur().read_u8()
            {
                Ok(r) => r,
                Err(e) =>
                    return Some(ProxyV2TlvSource::new_io_error(e)),
            };

        // read length of the tlv's payload
        let tlv_len = 
            match self.get_last_mut_cur().read_u16::<BigEndian>()
            {
                Ok(r) => r,
                Err(e) => 
                    return Some(ProxyV2TlvSource::new_io_error(e)),
            };

        let tlv_range = 
            self.get_last_cur().position() as usize .. (self.get_last_cur().position()+ tlv_len as u64) as usize;


        // creating a cursor from slice to prevent parser going out of bounds by the declared size
        let mut cur = 
            Cursor::new(&self.get_last_cur().get_ref()[tlv_range]);

        
        // check in which range it is
        let next_item = 
            if PP2Tlvs::is_in_range(tlv_type, self.get_parent_tlv()) == true
            {
                ProxyV2TlvSource::new_internal(
                    PP2Tlvs::restore(tlv_type, &mut cur)
                )
            }
            else if EXT::is_in_range(tlv_type, self.get_parent_tlv()) == true
            {
                ProxyV2TlvSource::new_external(
                    EXT::restore(tlv_type, &mut cur)
                )
            }
            else
            {
                ProxyV2TlvSource::new_error(
                    map_error!(ProtocolUnknownData, "TLV tpye: '{}' out of int/ext ranges", tlv_type)
                )
            };

        // move cursor position forward
        let new_pos = self.get_last_cur().position()+ tlv_len as u64;
        self.get_last_mut_cur().set_position(new_pos);

        if next_item.contains_subtype() == true
        {
            // push the current cursor
            self.curs.push(
                ProxyV2TlvIterTlv
                {
                    cur: cur,
                    parent_tlv_idx: Some(tlv_type),
                }
            );
        }

        return Some(next_item);
    }
}

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

    use byteorder::{BigEndian, ReadBytesExt};

    use crate::{common, error::HaProxRes, protocol::{protocol::{HdrV2Command, PP2TlvClient, PP2Tlvs, ProtocolVersion, ProxyTransportFam, ProxyV2Addr, ProxyV2AddrType, PP2_TYPE_MIN_CUSTOM}, protocol_raw, PP2TlvDump, PP2TlvRestore}, return_error};

    use super::ProxyV2Parser;

    #[test]
    fn test_0()
    {
        let pkt_ssl = 
b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a\x21\x11\x00\x2a\
\x7f\x00\x00\x01\x7f\x00\x00\x43\x9d\xd2\x2e\x6b\x20\x00\x1b\x07\
\x00\x00\x00\x00\x21\x00\x07\x54\x4c\x53\x76\x31\x2e\x32\x22\x00\
\x09\x6d\x71\x74\x74\x75\x73\x65\x72\x31";

        let dec = ProxyV2Parser::try_from_slice(pkt_ssl.as_slice()).unwrap();

        assert_eq!(dec.get_transport().is_ok(), true);
        assert_eq!(dec.get_transport().unwrap(), ProxyTransportFam::STREAM);

        assert_eq!(dec.get_proto_version(), ProtocolVersion::V2);
        assert_eq!(dec.get_proto_command(), HdrV2Command::PROXY);

        assert_eq!(dec.get_address_family().is_ok(), true);
        assert_eq!(dec.get_address_family().unwrap(), ProxyV2AddrType::AfInet);

        assert_eq!(dec.get_palyload_len() as usize, pkt_ssl.len() - size_of::<protocol_raw::ProxyHdrV2>());
        
        let addr = dec.get_address().unwrap();

        assert_eq!(addr.is_some(), true);

        let addr = addr.unwrap();
        let maddr = ProxyV2Addr::try_from(("127.0.0.1:40402", "127.0.0.67:11883")).unwrap();

        assert_eq!(addr, maddr);

        let tlv_iter = dec.get_tlvs_iter();

        assert_eq!(tlv_iter.is_some(), true);

        let mut tlv_iter = tlv_iter.unwrap();

        let type_ssl = tlv_iter.next().unwrap().take_internal().unwrap();

        assert_eq!(type_ssl.get_type(), PP2Tlvs::TYPE_SSL);
        let PP2Tlvs::TypeSsl { client, verify } = type_ssl else {panic!("wrong")};

        assert_eq!(client, PP2TlvClient::all());
        assert_eq!(verify, 0);

        let type_ssl_version = tlv_iter.next().unwrap().take_internal().unwrap();

        assert_eq!(type_ssl_version.get_type(), PP2Tlvs::TYPE_SUBTYPE_SSL_VERSION);

        let PP2Tlvs::TypeSubtypeSslVersion(ssl_version) = type_ssl_version else { panic!("wrong") };

        assert_eq!(ssl_version, "TLSv1.2");

        let type_ssl_cn = tlv_iter.next().unwrap().take_internal().unwrap();

        assert_eq!(type_ssl_cn.get_type(), PP2Tlvs::TYPE_SUBTYPE_SSL_CN);

        let PP2Tlvs::TypeSubtypeSslCn(ssl_cn) = type_ssl_cn else { panic!("wrong") };

        assert_eq!(ssl_cn, "mqttuser1");
    }

    #[test]
    fn test_1()
    {

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

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

        impl PP2TlvRestore for ProxyV2Dummy2
        {
            fn restore(tlv_type: u8, cur: &mut Cursor<&[u8]>) -> HaProxRes<Self> where Self: Sized 
            {
                match tlv_type
                {
                    0xE0 =>
                    {
                        let arg0 = cur.read_u32::<BigEndian>().map_err(common::map_io_err)?;
                        let arg1 = cur.read_u32::<BigEndian>().map_err(common::map_io_err)?;

                        return Ok(Self::SomeTlvName(arg0, arg1));
                    },
                    _ => 
                        return_error!(ProtocolUnknownData, "unknown tlv_type: {}", tlv_type)
                }
                
            }
            
            fn is_in_range(tlv_type: u8, _tlv_parent_type: Option<u8>) -> bool 
            {
                return tlv_type == PP2_TYPE_MIN_CUSTOM;
            }
            
            fn contains_subtype(&self) -> bool 
            {
                return false;
            }
        }

        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<()> 
            {
                todo!()
            }
        }

        let pkt_ssl = 
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";

        let dec = ProxyV2Parser::<ProxyV2Dummy2>::try_from_slice_custom(pkt_ssl.as_slice()).unwrap();

        assert_eq!(dec.get_transport().is_ok(), true);
        assert_eq!(dec.get_transport().unwrap(), ProxyTransportFam::STREAM);

        assert_eq!(dec.get_proto_version(), ProtocolVersion::V2);
        assert_eq!(dec.get_proto_command(), HdrV2Command::PROXY);

        assert_eq!(dec.get_address_family().is_ok(), true);
        assert_eq!(dec.get_address_family().unwrap(), ProxyV2AddrType::AfInet);
        
        assert_eq!(dec.get_palyload_len() as usize, pkt_ssl.len() - size_of::<protocol_raw::ProxyHdrV2>());

        let addr = dec.get_address().unwrap();

        assert_eq!(addr.is_some(), true);

        let addr = addr.unwrap();
        let maddr = ProxyV2Addr::try_from(("127.0.0.1:39754", "127.0.0.67:11883")).unwrap();

        assert_eq!(addr, maddr);

        let tlv_iter = dec.get_tlvs_iter();

        assert_eq!(tlv_iter.is_some(), true);

        let mut tlv_iter = tlv_iter.unwrap();

        let type_ssl = tlv_iter.next().unwrap().take_internal().unwrap();

        assert_eq!(type_ssl.get_type(), PP2Tlvs::TYPE_SSL);
        let PP2Tlvs::TypeSsl { client, verify } = type_ssl else {panic!("wrong")};

        assert_eq!(client, PP2TlvClient::PP2_CLIENT_SSL);
        assert_eq!(verify, 0);

        // --
        let type_ssl_version = tlv_iter.next().unwrap().take_internal().unwrap();

        assert_eq!(type_ssl_version.get_type(), PP2Tlvs::TYPE_SUBTYPE_SSL_VERSION);

        let PP2Tlvs::TypeSubtypeSslVersion(ssl_version) = type_ssl_version else { panic!("wrong") };

        assert_eq!(ssl_version, "TLSv1.2");

        // ---
        let ext_type_e0 = tlv_iter.next().unwrap().take_external().unwrap();

        assert_eq!(ext_type_e0.get_type(), 0xE0);

        let ProxyV2Dummy2::SomeTlvName(arg0, arg1) = ext_type_e0 else {panic!("wrong")};

        assert_eq!(arg0, 0x01020304);
        assert_eq!(arg1, 0x05060708);


    }

    #[test]
    fn test_3()
    {
        let pkt_ssl = 
b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a\x21\x11\x00\x0c\
\x7f\x00\x00\x01\x7f\x00\x00\x01\x8c\x76\x00\x50";


        let dec = ProxyV2Parser::try_from_slice(pkt_ssl.as_slice()).unwrap();

        assert_eq!(dec.get_transport().is_ok(), true);
        assert_eq!(dec.get_transport().unwrap(), ProxyTransportFam::STREAM);

        assert_eq!(dec.get_proto_version(), ProtocolVersion::V2);
        assert_eq!(dec.get_proto_command(), HdrV2Command::PROXY);

        assert_eq!(dec.get_address_family().is_ok(), true);
        assert_eq!(dec.get_address_family().unwrap(), ProxyV2AddrType::AfInet);

        assert_eq!(dec.get_palyload_len() as usize, pkt_ssl.len() - size_of::<protocol_raw::ProxyHdrV2>());
        
        let addr = dec.get_address().unwrap();

        assert_eq!(addr.is_some(), true);

        let addr = addr.unwrap();
        let maddr = ProxyV2Addr::try_from(("127.0.0.1:35958", "127.0.0.1:80")).unwrap();

        assert_eq!(addr, maddr);

        let tlv_iter = dec.get_tlvs_iter();

        assert_eq!(tlv_iter.is_some(), false);

    }

}