haprox-rs 0.3.2

A HaProxy v1/v2 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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
/*-
 * haprox-rs - a HaProxy protocol parser.
 * 
 * Copyright 2025 (c) 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. The MIT License (MIT)
 *                     
 *   3. 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, protocol_raw, error::{HaProxErr, HaProxRes}, return_error};

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

/// A [ProxyV2OpCode] opcode which is used in [ProxyHdrV2]
/// 
/// 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.
/// 
/// ## Example
/// 
/// ```ignore
/// let mut comp = 
///     ProxyHdrV2::<HdrV2OpLocal>::new().unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct HdrV2OpLocal;

/// A [ProxyV2OpCode] opcode which is used in [ProxyHdrV2]
/// 
/// 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.
/// 
/// ## Example 
/// 
/// ```ignore
/// let mut comp = 
///     ProxyHdrV2::<HdrV2OpProxy>::new(ProxyTransportFam::STREAM, addr)
///         .unwrap();
/// ```
#[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.
    /// 
    /// > US-ASCII string representation of the TLS version (format?)
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `ver` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_version(&mut self, ver: impl Into<String>) -> HaProxRes<()>
    {
        let version = ver.into();

        common::is_printable_ascii_nowp(&version, "version")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslVersion(Cow::Owned(version)), Some(self.constraints));
    }

    /// Sets borrowed the version of the SSL i,e TLSv1.2.
    /// 
    /// > US-ASCII string representation of the TLS version (format?)
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `ver` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_version_borrow<'a>(&mut self, ver: &'a str) -> HaProxRes<()>
    {
        common::is_printable_ascii_nowp(ver, "ssl_version")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslVersion(Cow::Borrowed(ver)), Some(self.constraints));
    }

    /// Sets the Common Name field.
    /// 
    /// > 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".
    /// 
    /// Does not perform validation. ToDo?
    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 borrowed Common Name field.
    /// 
    /// > 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".
    /// 
    /// Does not perform validation. ToDo?
    pub 
    fn add_ssl_sub_cn_borrow<'a>(&mut self, cn: &'a str) -> HaProxRes<()>
    {
        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslCn(Cow::Borrowed(cn)), Some(self.constraints));
    }

    /// Sets the Cipher type i.e "ECDHE-RSA-AES128-GCM-SHA256"
    /// 
    /// > US-ASCII string name of the used cipher, for example "ECDHE-RSA-AES128-GCM-SHA256".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `ver` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_cipher(&mut self, cip: impl Into<String>) -> HaProxRes<()>
    {
        let cipher = cip.into();

        common::is_printable_ascii_nowp(&cipher, "ssl_cipher")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslCipher(Cow::Owned(cipher)), Some(self.constraints));
    }

    /// Sets the borrowed Cipher type i.e "ECDHE-RSA-AES128-GCM-SHA256"
    /// 
    /// > US-ASCII string name of the used cipher, for example "ECDHE-RSA-AES128-GCM-SHA256".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `cip` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_cipher_borrow<'a>(&mut self, cip: &'a str) -> HaProxRes<()>
    {
        common::is_printable_ascii_nowp(cip, "ssl_cipher")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslCipher(Cow::Borrowed(cip)), Some(self.constraints));
    }
    
    /// Sets the signature algorithm i.e "SHA256"
    /// 
    /// > 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".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `sigalg` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_sigalg(&mut self, sigalg: impl Into<String>) -> HaProxRes<()>
    {
        let sig_alg = sigalg.into();

        common::is_printable_ascii_nowp(&sig_alg, "sig_alg")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslSigAlg(Cow::Owned(sig_alg)), Some(self.constraints));
    }

    /// Sets the signature algorithm i.e "SHA256"
    /// 
    /// > 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".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `sigalg` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_sigalg_borrow<'a>(&mut self, sigalg: &'a str) -> HaProxRes<()>
    {
        common::is_printable_ascii_nowp(sigalg, "ssl_sigalg")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslSigAlg(Cow::Borrowed(sigalg)), Some(self.constraints));
    }

    /// Sets the key algorithm i.e "RSA2048"
    /// 
    /// > 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".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `key` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_keyalg(&mut self, key: impl Into<String>) -> HaProxRes<()>
    {
        let key_alg = key.into();

        common::is_printable_ascii_nowp(&key_alg, "sig_alg")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslKeyAlg(Cow::Owned(key_alg)), Some(self.constraints));
    }

    /// Sets the borrowed key algorithm i.e "RSA2048"
    /// 
    /// > 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".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `key` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sub_keyalg_borrow<'a>(&mut self, key: &'a str) -> HaProxRes<()>
    {
        common::is_printable_ascii_nowp(key, "ssl_sigalg")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubtypeSslKeyAlg(Cow::Borrowed(key)), Some(self.constraints));
    }

    /// Sets the ssl group.
    /// 
    /// > US-ASCII string name of the key exchange algorithm used for the frontend TLS 
    /// > connection, for example "secp256r1".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `group` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_group(&mut self, group: impl Into<String>) -> HaProxRes<()>
    {
        let group_str = group.into();

        common::is_printable_ascii_nowp(&group_str, "ssl_group")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubTypeSslGroup(group_str.into()), Some(self.constraints));
    }

    /// Sets the borrowed ssl group.
    /// 
    /// > US-ASCII string name of the key exchange algorithm used for the frontend TLS 
    /// > connection, for example "secp256r1".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `group` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_group_group<'a>(&mut self, group: &'a str) -> HaProxRes<()>
    {
        common::is_printable_ascii_nowp(group, "ssl_group")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubTypeSslGroup(Cow::Borrowed(group)), Some(self.constraints));
    }

    /// Sets the SSL signature scheme.
    /// 
    /// > US-ASCII string name of the algorithm the frontend used to sign the ServerKeyExchange or
    /// > CertificateVerify message, for example "rsa_pss_rsae_sha256".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `sig_schm` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sig_scheme(&mut self, sig_schm: impl Into<String>) -> HaProxRes<()>
    {
        let sig_schm_str = sig_schm.into();

        common::is_printable_ascii_nowp(&sig_schm_str, "ssl_sig_schm")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubTypeSslSigScheme(sig_schm_str.into()), Some(self.constraints));
    }

    /// Sets the borrowed SSL signature scheme.
    /// 
    /// > US-ASCII string name of the algorithm the frontend used to sign the ServerKeyExchange or
    /// > CertificateVerify message, for example "rsa_pss_rsae_sha256".
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `sig_schm` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too.
    pub 
    fn add_ssl_sig_scheme_borrow<'a>(&mut self, sig_schm: &'a str) -> HaProxRes<()>
    {
        common::is_printable_ascii_nowp(sig_schm, "sig_schm")?;

        return self.hdr.add_tlv(PP2Tlvs::TypeSubTypeSslSigScheme(Cow::Borrowed(sig_schm)), 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)
    /// 
    /// The input is not validated! ToDo?
    pub 
    fn add_alpn<'a>(&mut self, alpns: impl Iterator<Item = &'a [u8]>) -> HaProxRes<()>
    {
        return 
            self
                .add_tlv(
                    PP2Tlvs::TypeAlpn( 
                        alpns
                            .map(|v| Cow::Borrowed(v))
                            .collect::<Vec<Cow<'a, [u8]>>>()
                            .into() 
                    ), 
                    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
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `ns` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too. 
    pub 
    fn add_netns(&mut self, ns: impl Into<String>) -> HaProxRes<()>
    {
        let ns_str = ns.into();

        common::is_printable_ascii_nowp(&ns_str, "net_ns")?;

        return self.add_tlv(PP2Tlvs::TypeNetNs(ns_str.into()), None);
    }

    /// Adds (borrowed) US-ASCII string representation of the namespace's name
    /// 
    /// # Returns
    /// 
    /// An error will be returned if `ns` contains non-ascii, non-printable and
    /// whitespace.
    /// 
    /// Other error maybe returned too. 
    pub 
    fn add_netns_borrowed<'a>(&mut self, ns: &'a str) -> HaProxRes<()>
    {
        common::is_printable_ascii_nowp(ns, "net_ns")?;

        return self.add_tlv(PP2Tlvs::TypeNetNs(Cow::Borrowed(ns)), None);
    }

    /// Adds a 32-bit number storing the CRC32c checksum of the PROXY protocol header
    /// 
    /// It will be calculated later 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.
    /// 
    /// The input is not validated! ToDo?
    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.into()), None);
    }

    /// Adds a uniqID as slice borrow. See [PP2TlvUniqId]. 128 bytes max.
    /// 
    /// The input is not validated! ToDo?
    pub 
    fn add_uniq_id_borrow<ID: PP2TlvUniqId>(&mut self, au: ID) -> HaProxRes<()>
    {
        let uniq_id = au.as_slice();

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

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

    /// Adds "SNI" borrow i.e the "server_name" extension as defined by RFC3546.
    pub 
    fn add_authority_borrrow<'a>(&mut self, authority: &'a str) -> HaProxRes<()>
    {
        return self.add_tlv(PP2Tlvs::TypeAuthority(Cow::Borrowed(authority)), 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. A [PP2TlvDump] should be implemeted by the `tlv`.
    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, "duplicate 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.
/// 
/// # Example
/// 
/// ```ignore
/// // creating new instance
/// let mut comp = 
///     ProxyHdrV2::<HdrV2OpProxy>::new(ProxyTransportFam::STREAM, addr).unwrap();
/// 
/// // aquiring the plts to set fields
/// let plts = comp.set_plts();
/// 
/// // adding ssl info
/// let mut ssl = plts.add_ssl(PP2TlvClient::PP2_CLIENT_SSL, 0).unwrap();
/// ssl.add_ssl_sub_version("TLSv1.2").unwrap();
///     
/// // done writing ssl, returning the plts
/// let mut plts = ssl.done().unwrap();
/// 
/// // a custom TLV
/// let cust_plt = ProxyV2Dummy2::SomeTlvName(0x01020304, 0x05060708);
/// 
/// plts.add_tlv(cust_plt, Some(&[0xE0..=0xE0])).unwrap();
/// 
/// drop(plts);
/// 
/// // convert to vec of bytes
/// let pkt: Vec<u8> = comp.try_into().unwrap();
/// ```
/// 
#[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<'sz> PP2TlvDump for PP2Tlvs<'sz>
{
    fn get_type(&self) -> u8 
    {
        return self.into();
    }

    fn dump(&self, cur: &mut Cursor<Vec<u8>>) -> HaProxRes<()> 
    {
        match self
        {
            Self::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)?;
                }
            },
            Self::TypeAuthority(auth) => 
            {
                // authority
                cur.write_all(auth.as_bytes()).map_err(common::map_io_err)?;
            },
            Self::TypeCrc32c(crc) => 
            {
                cur.write_u32::<BigEndian>(*crc).map_err(common::map_io_err)?;
            },
            Self::TypeNoop => 
            {

            },
            Self::TypeUniqId(items) =>
            {
                cur.write_all(items).map_err(common::map_io_err)?;
            },
            Self::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)?;
            },
            Self::TypeSubtypeSslVersion(v) => 
            {
                cur.write_all(v.as_bytes()).map_err(common::map_io_err)?;
            },
            Self::TypeSubtypeSslCn(cn) => 
            {
                cur.write_all(cn.as_bytes()).map_err(common::map_io_err)?;
            },
            Self::TypeSubtypeSslCipher(c) => 
            {
                cur.write_all(c.as_bytes()).map_err(common::map_io_err)?;
            },
            Self::TypeSubtypeSslSigAlg(sa) => 
            {
                cur.write_all(sa.as_bytes()).map_err(common::map_io_err)?;
            },
            Self::TypeSubtypeSslKeyAlg(ka) => 
            {
                cur.write_all(ka.as_bytes()).map_err(common::map_io_err)?;
            },
            Self::TypeSubTypeSslGroup(group) => 
            {
                cur.write_all(group.as_bytes()).map_err(common::map_io_err)?;
            },
            Self::TypeSubTypeSslSigScheme(sig) => 
            {
                cur.write_all(sig.as_bytes()).map_err(common::map_io_err)?;
            }
            Self::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_v2::{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 
            {
                #[allow(irrefutable_let_patterns)]
                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().into()].into());

        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());
    }
}