summaryrefslogtreecommitdiff
path: root/src/codec_ipv4.rs
blob: 540f90e3bc5446c56054e115476b75a243eefbb4 (plain)
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
use crate::protocol::ipv4::{self};
use bytes::{Buf, BytesMut};
use std::io;
use tokio_util::codec::Decoder;
use tokio_util::codec::Encoder;

/******************************************************************************
 * Encoder/Decoder trait
 ******************************************************************************/

#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct IPv4Codec<C>(C);

impl<C> IPv4Codec<C> {
    pub fn new(c: C) -> Self {
        IPv4Codec(c)
    }
}

impl<C> Decoder for IPv4Codec<C>
where
    C: Decoder,
    std::io::Error: From<<C as Decoder>::Error>,
{
    type Item = C::Item;
    type Error = io::Error;

    fn decode(&mut self, data: &mut BytesMut) -> Result<Option<Self::Item>, io::Error> {
        println!("IPv4Codec -> decode(), handle data len: {}", data.len());

        if data.len() < 20 {
            println!("IPv4Codec decode: no enough data");
            return Ok(None);
        } else {
            let parsed_ipv4 = ipv4::parse_ipv4(data);
            if let Ok((ipv4_payload, ipv4_header)) = parsed_ipv4 {
                println!("{:?}, Payload: {}", ipv4_header, ipv4_payload.len());

                // Skip the 20-byte length.
                data.advance(20);

                let decoded = self.0.decode(data)?;
                match decoded {
                    None => {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            format!("  IPv4 Frame of length {} is too large.", 111),
                        ));
                    }
                    Some(inner) => Ok(Some(inner)),
                }
            } else {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Invalid ipv4 frame"),
                ));
            }
        }
    }
}

impl<C, T> Encoder<T> for IPv4Codec<C>
where
    C: Encoder<T>,
    std::io::Error: From<C::Error>,
{
    type Error = io::Error;

    fn encode(&mut self, _item: T, _buf: &mut BytesMut) -> Result<(), io::Error> {
        // TODO
        Ok(())
    }
}