kasesiki-netstack 0.1.3

A netstack for the special purpose of turning packets from/to a TUN interface into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
Documentation
use std::{
    io::{Error, ErrorKind::InvalidInput},
    net::IpAddr,
    ops::Range,
    pin::Pin,
    sync::Arc,
    task::{Poll::Ready, ready},
};

use bytes::Bytes;
use futures::{
    Sink, Stream,
    channel::mpsc::{self, UnboundedReceiver},
};
use futures::{channel::mpsc::UnboundedSender, task::AtomicWaker};
use smoltcp::wire::{IpProtocol, IpVersion, Ipv4Packet, Ipv6Packet};

use crate::{
    Duration, device::VirtualDevice, tcp::{TcpListener, Timer},
};

pub struct StackBuilder {
    // bandwidth = buffer_window / rtt
    tcp_buffer_window: usize,
    _udp_buffer_window: usize,
    // Concurrent TCP Connections
    tcp_buffer_max: usize,
    timeout: Option<Duration>,
    mtu: u16,
    filter: Option<Box<dyn Fn(IpAddr, u16) -> bool + Send>>,
}

impl StackBuilder {
    pub fn new(
        tcp_buffer_max: usize,
        tcp_buffer_window: usize,
        _udp_buffer_window: usize,
        mtu: u16,
    ) -> Self {
        Self {
            tcp_buffer_max,
            tcp_buffer_window,
            _udp_buffer_window,
            timeout: None,
            mtu,
            filter: None,
        }
    }

    pub fn timeout(mut self, duration: Option<Duration>) -> StackBuilder {
        self.timeout = duration;
        self
    }

    pub fn filter_fn(mut self, f: Option<Box<dyn Fn(IpAddr, u16) -> bool + Send>>) -> StackBuilder {
        self.filter = f;
        self
    }

    pub fn build<T: Future + Timer + Unpin>(
        self,
        ref_waker: Arc<AtomicWaker>,
        timer: T,
    ) -> std::io::Result<(Stack, TcpListener<T>)> {
        // 传入frame
        let (stack_tx, stack_rx) = mpsc::unbounded();

        let (tcp_tx, tcp_rx) = mpsc::unbounded();
        let (udp_tx, _udp_rx) = mpsc::unbounded();

        let (device, handle_tx) = VirtualDevice::new(stack_tx, self.mtu.into());

        Ok((
            Stack {
                sink_buf: None,
                stack_rx: Box::pin(stack_rx),
                tcp_tx,
                _udp_tx: udp_tx,
            },
            TcpListener::new(
                device,
                tcp_rx,
                self.tcp_buffer_max,
                self.tcp_buffer_window,
                handle_tx,
                ref_waker,
                self.timeout,
                timer,
                self.filter
            )?,
        ))
    }
}

impl Default for StackBuilder {
    fn default() -> Self {
        Self {
            tcp_buffer_max: 128,
            tcp_buffer_window: 0x3FFF * 10,
            _udp_buffer_window: 0x3FFF * 10,
            timeout: None,
            mtu: 1500,
            filter: None,
        }
    }
}

pub enum IpPacket<T: AsRef<[u8]>> {
    Ipv4(Ipv4Packet<T>),
    Ipv6(Ipv6Packet<T>),
}

impl<T> IpPacket<T>
where
    T: AsRef<[u8]>,
{
    pub fn protocol(&self) -> IpProtocol {
        match *self {
            IpPacket::Ipv4(ref packet) => packet.next_header(),
            IpPacket::Ipv6(ref packet) => packet.next_header(),
        }
    }

    pub fn take(self) -> T {
        match self {
            IpPacket::Ipv4(packet) => packet.into_inner(),
            IpPacket::Ipv6(packet) => packet.into_inner(),
        }
    }

    pub fn src_addr(&self) -> IpAddr {
        match *self {
            IpPacket::Ipv4(ref packet) => IpAddr::from(packet.src_addr()),
            IpPacket::Ipv6(ref packet) => IpAddr::from(packet.src_addr()),
        }
    }

    pub fn dst_addr(&self) -> IpAddr {
        match *self {
            IpPacket::Ipv4(ref packet) => IpAddr::from(packet.dst_addr()),
            IpPacket::Ipv6(ref packet) => IpAddr::from(packet.dst_addr()),
        }
    }

    pub fn size(&self) -> Range<usize> {
        match *self {
            IpPacket::Ipv4(ref packet) => packet.header_len() as usize..packet.total_len() as usize,
            IpPacket::Ipv6(ref packet) => packet.header_len() as usize..packet.total_len() as usize,
        }
    }
}

pub struct Stack {
    sink_buf: Option<IpPacket<Bytes>>,
    stack_rx: Pin<Box<UnboundedReceiver<Bytes>>>,
    tcp_tx: UnboundedSender<IpPacket<bytes::Bytes>>,
    _udp_tx: UnboundedSender<IpPacket<bytes::Bytes>>,
}

impl Stack {
    fn poll_send(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), std::io::Error>> {
        let proto = match unsafe { Pin::get_unchecked_mut(self.as_mut()).sink_buf.take() } {
            Some(val) => val,
            None => return Ready(Ok(())),
        };
        let tx = match proto.protocol() {
            IpProtocol::Tcp => &mut self.tcp_tx,
            //IpProtocol::Udp => &mut self.udp_tx,
            _ => {
                //println!("ignore unknown protocol: {a}");
                return std::task::Poll::Ready(Ok(()));
            }
        };
        if let Err(e) = ready!(tx.poll_ready(cx)) {
            unsafe { Pin::get_unchecked_mut(self).sink_buf.replace(proto) };
            return Ready(Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, e)));
        };
        let _ = tx.start_send(proto);
        let _ = Box::pin(tx).as_mut().poll_flush(cx);
        Ready(Ok(()))
    }
}

impl Sink<Bytes> for Stack {
    type Error = std::io::Error;

    fn poll_ready(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        if self.sink_buf.is_some() {
            ready!(self.poll_send(cx))?;
        }
        Ready(Ok(()))
    }

    fn start_send(self: std::pin::Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
        let packet = match IpVersion::of_packet(&item)
            .map_err(|err| Error::new(InvalidInput, format!("invalid IP packet: {err}")))?
        {
            IpVersion::Ipv4 => {
                IpPacket::Ipv4(Ipv4Packet::new_checked(item).map_err(|err| {
                    Error::new(InvalidInput, format!("invalid IPv4 packet: {err}"))
                })?)
            }
            IpVersion::Ipv6 => {
                IpPacket::Ipv6(Ipv6Packet::new_checked(item).map_err(|err| {
                    Error::new(InvalidInput, format!("invalid IPv6 packet: {err}"))
                })?)
            }
        };
        unsafe { Pin::get_unchecked_mut(self).sink_buf.replace(packet) };
        Ok(())
    }

    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.poll_send(cx)
    }

    fn poll_close(
        mut self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.stack_rx.close();
        Ready(Ok(()))
    }
}

impl Stream for Stack {
    type Item = Bytes;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        Ready(ready!(self.stack_rx.as_mut().poll_next(cx)))
    }
}