use std::{
io::{Error, ErrorKind::InvalidInput}, net::IpAddr, ops::Range, pin::Pin, sync::Arc, task::{Poll::Ready, ready},
};
use bytes::Bytes;
use futures::{channel::mpsc::UnboundedSender, task::AtomicWaker};
use futures::{
Sink, Stream,
channel::mpsc::{self, UnboundedReceiver},
};
use smoltcp::wire::{IpProtocol, IpVersion::self, Ipv4Packet, Ipv6Packet};
use crate::{device::VirtualDevice, tcp::{TcpListener, Timer}};
pub struct StackBuilder {
tcp_buffer_window: usize,
_udp_buffer_window: usize,
tcp_buffer_max: usize,
mtu: u16,
}
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,
mtu,
}
}
pub fn build<T: Future + Timer + Unpin>(self, ref_waker: Arc<AtomicWaker>, timer: T) -> std::io::Result<(Stack, TcpListener<T>)> {
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, timer)?,
))
}
}
impl Default for StackBuilder {
fn default() -> Self {
Self {
tcp_buffer_max: 128,
tcp_buffer_window: 0x3FFF * 20,
_udp_buffer_window: 0x3FFF * 20,
mtu: 1500,
}
}
}
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,
_ => {
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)))
}
}