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
/*-
 * 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 crate::{HaProxRes, HapProtoV1, common, map_error, protocol_raw, return_error};


/// A HaProxy protocol V1 parser. 
/// 
/// It is assumed that the upstream has received the packet and splitted each header
/// line. Input funtions expects that the input complies with the HaProxy protocl 
/// specs i.e 
/// 
/// * the message starts from identifier
/// 
/// * separated with exactly one ASCII space 
/// 
/// * consists from ASCII printable chars only 
/// 
/// * ends with `\r\n` sequence and does not contain anything else.
/// 
/// > Human-readable header format (Version 1)
/// > 
/// > This is the format specified in version 1 of the protocol. It consists in one
/// > line of US-ASCII text matching exactly the following block
/// > 
/// > So a 108-byte buffer is always enough to store all the line and a trailing zero
/// > for string processing.
/// > The receiver must wait for the CRLF sequence before starting to decode the
/// > addresses in order to ensure they are complete and properly parsed. If the CRLF
/// > sequence is not found in the first 107 characters, the receiver should declare
/// > the line invalid.
/// 
/// ## Example
/// 
/// ```ignore
/// let pv1 = 
///     ProxyV1Parser
///         ::try_from_slice(b"PROXY TCP6 0acf:5d35:b4c4:731c:2442:2f17:c6f9:5b7f 4d7f:8980:38d6:e0c3:7301:70e9:f8ef:e393 23456 12345\r\n", false)
///            .unwrap();
/// ```
#[derive(Debug)]
pub struct ProxyV1Parser;

impl ProxyV1Parser
{
    /// Attempts to parse the `value` which was already converted to [str].
    /// 
    /// It is assumed that a caller has verified that the `value` provided
    /// to function contains valid UTF8 char sequences and the message ends 
    /// with `\r\n` and this string does not contain any other data after EOM.
    /// 
    /// # Arguments
    /// 
    /// * `value` - a message to parse
    /// 
    /// * `skip_strict_size_check` - if set to `true`, the max message length 
    ///     verification will be disabled.
    /// 
    /// # Returns
    /// 
    /// A [HapProtoV1] is returned which contains parsed data.
    /// 
    /// The following error codes are returned:
    /// 
    /// * [crate::error::HaProxErrType::IncorrectBanner] - incorrect header
    /// 
    /// * [crate::error::HaProxErrType::ProtocolMsgIncomplete] - `value` does not end
    ///     with `\r\n` seq.
    pub 
    fn try_from_str(value: &str, skip_strict_size_check: bool) -> HaProxRes<HapProtoV1>
    {
        if value.starts_with(protocol_raw::HEADER_MAGIC_V1_STR) == false
        {
            return_error!(IncorrectBanner, "unknown proto identifier '{:02X?}'", 
                &value[0..protocol_raw::HEADER_MAGIC_V1.len()]);
        }
        else if skip_strict_size_check == false && value.as_bytes().len() >= protocol_raw::HEADER_V1_MAX_LEN
        {
            return_error!(IncorrectBanner, "size of the messagge: '{}' larger '{}' for '{:02X?}'", 
                value.len(), protocol_raw::HEADER_V1_MAX_LEN, value);
        }

        // chech that it is ASCII only
        let Some(res_value) = common::check_printable_ascii_single_wp(value, "HEADER")?
            else
            {
                // incomplete message
                return_error!(ProtocolMsgIncomplete, "protocol message is incomplite '{}'", value);
            };

        return Self::parse(res_value);
    }

    /// Attempts to parse the `value` from a slice which contails a HaProxy
    /// related field.
    /// 
    /// It is assumed that a caller has split the header and provides a slice
    /// with the header only which  ends with `\r\n` and this string does not 
    /// contain any other data after EOM.
    /// 
    /// # Arguments
    /// 
    /// * `value` - a message to parse
    /// 
    /// * `skip_strict_size_check` - if set to `true`, the max message length 
    ///     verification will be disabled.
    /// 
    /// # Returns
    /// 
    /// # Returns
    /// 
    /// A [HapProtoV1] is returned which contains parsed data.
    /// 
    /// The following error codes are returned:
    /// 
    /// * [crate::error::HaProxErrType::IncorrectBanner] - incorrect header
    /// 
    /// * [crate::error::HaProxErrType::MalformedData] - contains non UTF-8 seq or
    ///     not ASCII or non printable ASCII.
    /// 
    /// * [crate::error::HaProxErrType::ProtocolMsgIncomplete] - `value` does not end
    ///     with `\r\n` seq.
    pub 
    fn try_from_slice(value: &[u8], skip_strict_size_check: bool) -> HaProxRes<HapProtoV1>
    {
        let pre_parsed_msg = Self::new_from(value, skip_strict_size_check)?;

        return Self::parse(pre_parsed_msg);
    }

    /// 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.
    /// 
    /// Eliminates the header and trailing \r\n.
    /// 
    /// # Returns
    /// 
    /// Error ProtocolMsgIncomplete if msg is incomplete
    fn new_from(value: &[u8], skip_strict_size_check: bool) -> HaProxRes<&str>
    {
        if value.len() <= protocol_raw::HEADER_MAGIC_V1.len()
        {
            return_error!(IncorrectBanner, "protocol with footprint '{:02X?}' unknown", 
                value);
        }
        else if skip_strict_size_check == false && value.len() >= protocol_raw::HEADER_V1_MAX_LEN
        {
            return_error!(IncorrectBanner, "size of the messagge: '{}' larger '{}' for '{:02X?}'", 
                value.len(), protocol_raw::HEADER_V1_MAX_LEN, value);
        }
        else if &value[0..protocol_raw::HEADER_MAGIC_V1.len()] != protocol_raw::HEADER_MAGIC_V1
        {
            return_error!(IncorrectBanner, "unknown proto identifier '{:02X?}'", 
                &value[0..protocol_raw::HEADER_MAGIC_V1.len()]);
        }
        
        // try to convert into UTF8, skipping the header
        let str_val = 
            str::from_utf8(value)
                .map_err(|e|
                    map_error!(MalformedData, "UTF8 decode error {}", e)
                )?;

        // chech that it is ASCII only
        let Some(res_value) = common::check_printable_ascii_single_wp(str_val, "HEADER")?
            else
            {
                // incomplete message
                return_error!(ProtocolMsgIncomplete, "protocol message is incomplite '{}'", 
                    str_val);
            };
        
        return Ok(res_value);
    }

    fn parse(pre_parsed_msg: &str) -> HaProxRes<HapProtoV1>
    {
        let mut parsed_iter = pre_parsed_msg.split(protocol_raw::HEADER_V1_WSPACE);

        // skip header version
        let _ = 
            parsed_iter.next().ok_or_else(||
                    map_error!(MalformedData, "no INET exists in '{}'", pre_parsed_msg)
                )?;

        // inet
        let inet = 
            parsed_iter
                .next()
                .ok_or_else(||
                    map_error!(MalformedData, "no INET exists in '{}'", pre_parsed_msg)
                )?;

        // src ip
        let src_ip= parsed_iter.next();
        let dst_ip = parsed_iter.next();
        let src_port = parsed_iter.next();
        let dst_port = parsed_iter.next();

        return HapProtoV1::from_raw(inet, src_ip, dst_ip, src_port, dst_port);
    }
}

#[cfg(test)]
mod tests_parser
{
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

    use crate::{ProtocolV1Inet, ProxyV1Parser};

    #[test]
    fn test_v1_parser_0()
    {
        let pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP4 192.168.2.1 10.8.0.1 4567 1234\r\n", false)
                    .unwrap();

        assert_eq!(pv1.get_inet(), ProtocolV1Inet::Tcp4);
        assert_eq!(pv1.get_src_addr(), Some("192.168.2.1".parse().unwrap()));
        assert_eq!(pv1.get_src_port(), Some(4567));
        assert_eq!(pv1.get_dst_addr(), Some("10.8.0.1".parse().unwrap()));
        assert_eq!(pv1.get_dst_port(), Some(1234));
    }

    #[test]
    fn test_v1_parser_1()
    {
        let pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP6 0acf:5d35:b4c4:731c:2442:2f17:c6f9:5b7f 4d7f:8980:38d6:e0c3:7301:70e9:f8ef:e393 23456 12345\r\n", false)
                    .unwrap();

        assert_eq!(pv1.get_inet(), ProtocolV1Inet::Tcp6);
        assert_eq!(pv1.get_src_addr(), Some(IpAddr::V6("0acf:5d35:b4c4:731c:2442:2f17:c6f9:5b7f".parse::<Ipv6Addr>().unwrap())));
        assert_eq!(pv1.get_src_port(), Some(23456));
        assert_eq!(pv1.get_dst_addr(), Some(IpAddr::V6("4d7f:8980:38d6:e0c3:7301:70e9:f8ef:e393".parse::<Ipv6Addr>().unwrap())));
        assert_eq!(pv1.get_dst_port(), Some(12345));
    }

    #[test]
    fn test_v1_parser_2()
    {
        let pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY UNKNOWN\r\n", false)
                    .unwrap();

        assert_eq!(pv1.get_inet(), ProtocolV1Inet::None);
        assert_eq!(pv1.get_src_addr(), None);
        assert_eq!(pv1.get_src_port(), None);
        assert_eq!(pv1.get_dst_addr(), None);
        assert_eq!(pv1.get_dst_port(), None);
    }

    #[test]
    fn test_v1_parser_3()
    {
        let pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY UNKNOWN 255.255.255.255 255.255.255.255 65535 65535\r\n", false)
                    .unwrap();

        assert_eq!(pv1.get_inet(), ProtocolV1Inet::None);
        assert_eq!(pv1.get_src_addr(), None);
        assert_eq!(pv1.get_src_port(), None);
        assert_eq!(pv1.get_dst_addr(), None);
        assert_eq!(pv1.get_dst_port(), None);
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_4()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP4  192.168.1.1 10.8.0.1 23456 12345\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_5()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP5 192.168.1.1 10.8.0.1 23456 12345\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_6()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP4 192.168.1.1 10.8.0.1 23456 12345\r\n\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_7()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP6 192.168.1.1 10.8.0.1 23456 12345\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_8()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP4 349.168.1.1 10.8.0.1 23456 12345\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_9()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP4 \0149.168.1.1 10.8.0.1 23456 12345\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_10()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP4 149.168.1.1 10.8.0.1 6787765 12345\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_11()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_slice(b"PROXY TCP4 149.168.1.1 10.8.0.1 1 12345\r", false)
                    .unwrap();          
    }

    #[test]
    fn test_v1_parser_0_str()
    {
        let pv1 = 
            ProxyV1Parser
                ::try_from_str("PROXY TCP4 192.168.1.1 10.8.0.1 23456 12345\r\n", false)
                    .unwrap();

        assert_eq!(pv1.get_inet(), ProtocolV1Inet::Tcp4);
        assert_eq!(pv1.get_src_addr(), Some(IpAddr::V4("192.168.1.1".parse::<Ipv4Addr>().unwrap())));
        assert_eq!(pv1.get_src_port(), Some(23456));
        assert_eq!(pv1.get_dst_addr(), Some(IpAddr::V4("10.8.0.1".parse::<Ipv4Addr>().unwrap())));
        assert_eq!(pv1.get_dst_port(), Some(12345));
    }

    #[test]
    fn test_v1_parser_1_str()
    {
        let pv1 = 
            ProxyV1Parser
                ::try_from_str("PROXY TCP6 0acf:5d35:b4c4:731c:2442:2f17:c6f9:5b7f 4d7f:8980:38d6:e0c3:7301:70e9:f8ef:e393 23456 12345\r\n", false)
                    .unwrap();

        assert_eq!(pv1.get_inet(), ProtocolV1Inet::Tcp6);
        assert_eq!(pv1.get_src_addr(), Some(IpAddr::V6("0acf:5d35:b4c4:731c:2442:2f17:c6f9:5b7f".parse::<Ipv6Addr>().unwrap())));
        assert_eq!(pv1.get_src_port(), Some(23456));
        assert_eq!(pv1.get_dst_addr(), Some(IpAddr::V6("4d7f:8980:38d6:e0c3:7301:70e9:f8ef:e393".parse::<Ipv6Addr>().unwrap())));
        assert_eq!(pv1.get_dst_port(), Some(12345));
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_2_str()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_str("PROXY TCP4 192.168.1.1 10.8.0.1 23456 12345\r\n\r\n", false)
                    .unwrap();          
    }

    #[should_panic]
    #[test]
    fn test_v1_parser_3_str()
    {
        let _pv1 = 
            ProxyV1Parser
                ::try_from_str("PROXY TCP4\0 192.168.1.1 10.8.0.1 23456 12345\r\n\r\n", false)
                    .unwrap();          
    }
}