Skip to main content

kasesiki_netstack/
stack.rs

1use std::{
2    io::{Error, ErrorKind::InvalidInput}, net::IpAddr, ops::Range, pin::Pin, sync::Arc, task::{Poll::Ready, ready},
3};
4
5use bytes::Bytes;
6use futures::{channel::mpsc::UnboundedSender, task::AtomicWaker};
7use futures::{
8    Sink, Stream,
9    channel::mpsc::{self, UnboundedReceiver},
10};
11use smoltcp::wire::{IpProtocol, IpVersion::self, Ipv4Packet, Ipv6Packet};
12
13use crate::{device::VirtualDevice, tcp::{TcpListener, Timer}};
14
15pub struct StackBuilder {
16    // bandwidth = buffer_window / rtt
17    tcp_buffer_window: usize,
18    _udp_buffer_window: usize,
19    // Concurrent TCP Connections
20    tcp_buffer_max: usize,
21    mtu: u16,
22}
23
24impl StackBuilder {
25    pub fn new(tcp_buffer_max: usize, tcp_buffer_window: usize, _udp_buffer_window: usize, mtu: u16) -> Self {
26        Self {
27            tcp_buffer_max,
28            tcp_buffer_window,
29            _udp_buffer_window,
30            mtu,
31        }
32    }
33
34    pub fn build<T: Future + Timer + Unpin>(self, ref_waker: Arc<AtomicWaker>, timer: T) -> std::io::Result<(Stack, TcpListener<T>)> {
35        // 传入frame
36        let (stack_tx, stack_rx) = mpsc::unbounded();
37
38        let (tcp_tx, tcp_rx) = mpsc::unbounded();
39        let (udp_tx, _udp_rx) = mpsc::unbounded();
40
41        let (device, handle_tx) = VirtualDevice::new(stack_tx, self.mtu.into());
42
43        Ok((
44            Stack {
45                sink_buf: None,
46                stack_rx: Box::pin(stack_rx),
47                tcp_tx,
48                _udp_tx: udp_tx,
49            },
50            TcpListener::new(device, tcp_rx, self.tcp_buffer_max, self.tcp_buffer_window, handle_tx, ref_waker, timer)?,
51        ))
52    }
53}
54
55impl Default for StackBuilder {
56    fn default() -> Self {
57        Self {
58            tcp_buffer_max: 128,
59            tcp_buffer_window: 0x3FFF * 20,
60            _udp_buffer_window: 0x3FFF * 20,
61            mtu: 1500,
62        }
63    }
64}
65
66pub enum IpPacket<T: AsRef<[u8]>> {
67    Ipv4(Ipv4Packet<T>),
68    Ipv6(Ipv6Packet<T>),
69}
70
71impl<T> IpPacket<T>
72where
73    T: AsRef<[u8]>,
74{
75    pub fn protocol(&self) -> IpProtocol {
76        
77        match *self {
78            IpPacket::Ipv4(ref packet) => packet.next_header(),
79            IpPacket::Ipv6(ref packet) => packet.next_header(),
80        }
81    }
82
83    pub fn take(self) -> T {
84        match self {
85            IpPacket::Ipv4(packet) => packet.into_inner(),
86            IpPacket::Ipv6(packet) => packet.into_inner(),
87        }
88    }
89
90    pub fn src_addr(&self) -> IpAddr {
91        match *self {
92            IpPacket::Ipv4(ref packet) => IpAddr::from(packet.src_addr()),
93            IpPacket::Ipv6(ref packet) => IpAddr::from(packet.src_addr()),
94        }
95    }
96
97    pub fn dst_addr(&self) -> IpAddr {
98        match *self {
99            IpPacket::Ipv4(ref packet) => IpAddr::from(packet.dst_addr()),
100            IpPacket::Ipv6(ref packet) => IpAddr::from(packet.dst_addr()),
101        }
102    }
103
104    pub fn size(&self) -> Range<usize> {
105        match *self {
106            IpPacket::Ipv4(ref packet) => {
107                packet.header_len() as usize..packet.total_len() as usize
108            },
109            IpPacket::Ipv6(ref packet) => {
110                packet.header_len() as usize..packet.total_len() as usize
111            },
112        }
113    }
114}
115
116pub struct Stack {
117    sink_buf: Option<IpPacket<Bytes>>,
118    stack_rx: Pin<Box<UnboundedReceiver<Bytes>>>,
119    tcp_tx: UnboundedSender<IpPacket<bytes::Bytes>>,
120    _udp_tx: UnboundedSender<IpPacket<bytes::Bytes>>,
121}
122
123impl Stack {
124    fn poll_send(
125        mut self: std::pin::Pin<&mut Self>,
126        cx: &mut std::task::Context<'_>,
127    ) -> std::task::Poll<Result<(), std::io::Error>> {
128        let proto = match unsafe { Pin::get_unchecked_mut(self.as_mut()).sink_buf.take() } {
129            Some(val) => val,
130            None => return Ready(Ok(())),
131        };
132        let tx = match proto.protocol() {
133            IpProtocol::Tcp => &mut self.tcp_tx,
134            //IpProtocol::Udp => &mut self.udp_tx,
135            _ => {
136                //println!("ignore unknown protocol: {a}");
137                return std::task::Poll::Ready(Ok(()))
138            },
139        };
140        if let Err(e) = ready!(tx.poll_ready(cx)) {
141            unsafe { Pin::get_unchecked_mut(self).sink_buf.replace(proto) };
142            return Ready(Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, e)));
143        };
144        let _ = tx.start_send(proto);
145        let _ = Box::pin(tx).as_mut().poll_flush(cx);
146        Ready(Ok(()))
147    }
148}
149
150impl Sink<Bytes> for Stack {
151    type Error = std::io::Error;
152
153    fn poll_ready(
154        self: std::pin::Pin<&mut Self>,
155        cx: &mut std::task::Context<'_>,
156    ) -> std::task::Poll<Result<(), Self::Error>> {
157        if self.sink_buf.is_some() {
158            ready!(self.poll_send(cx))?;
159        }
160        Ready(Ok(()))
161    }
162
163    fn start_send(self: std::pin::Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
164        let packet = match IpVersion::of_packet(&item).map_err(|err| {
165                    Error::new(InvalidInput, format!("invalid IP packet: {err}"))
166                })? {
167            IpVersion::Ipv4 => {
168                IpPacket::Ipv4(Ipv4Packet::new_checked(item).map_err(|err| {
169                    Error::new(InvalidInput, format!("invalid IPv4 packet: {err}"))
170                })?)
171            }
172            IpVersion::Ipv6 => {
173                IpPacket::Ipv6(Ipv6Packet::new_checked(item).map_err(|err| {
174                    Error::new(InvalidInput, format!("invalid IPv6 packet: {err}"))
175                })?)
176            }
177        };
178        unsafe { Pin::get_unchecked_mut(self).sink_buf.replace(packet) };
179        Ok(())
180    }
181
182    fn poll_flush(
183        self: std::pin::Pin<&mut Self>,
184        cx: &mut std::task::Context<'_>,
185    ) -> std::task::Poll<Result<(), Self::Error>> {
186        self.poll_send(cx)
187    }
188
189    fn poll_close(
190        mut self: std::pin::Pin<&mut Self>,
191        _cx: &mut std::task::Context<'_>,
192    ) -> std::task::Poll<Result<(), Self::Error>> {
193        self.stack_rx.close();
194        Ready(Ok(()))
195    }
196}
197
198impl Stream for Stack {
199    type Item = Bytes;
200
201    fn poll_next(
202        mut self: Pin<&mut Self>,
203        cx: &mut std::task::Context<'_>,
204    ) -> std::task::Poll<Option<Self::Item>> {
205        Ready(ready!(self.stack_rx.as_mut().poll_next(cx)))
206    }
207}