summaryrefslogtreecommitdiff
path: root/src/codec_eth.rs
blob: 31772680ba3e2e5304400bad3c3e305ab5daeec1 (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
74
75
76
77
78
79
80
81
82
use bytes::Buf;
use bytes::BytesMut;
use std::io;
use tokio_util::codec::Decoder;
use tokio_util::codec::Encoder;

use crate::protocol::ethernet::{self};

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

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

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

impl<C> Decoder for EthCodec<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!("EthCodec -> decode(), handle data len: {}", data.len());

        if data.len() < 14 {
            println!("EthCodec decode: no enough data");
            return Ok(None);
        } else {
            let parsed_eth_frame = ethernet::parse_ethernet(data);
            if let Ok((eth_payload, eth_header)) = parsed_eth_frame {
                println!("{:?}, Payload: {}", eth_header, eth_payload.len());

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

                /*
                match proto {
                    IPv4 => ipv4.decoder();
                    IPv6 => IPv6.decoder();
                }
                */

                let decoded = self.0.decode(data)?;
                match decoded {
                    None => {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            format!("xxxxxx."),
                        ));
                    }
                    Some(inner) => Ok(Some(inner)),
                }
            } else {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Invalid ethernet frame"),
                ));
            }
        }
    }
}

impl<C, T> Encoder<T> for EthCodec<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(())
    }
}