Skip to main content

kasesiki_netstack/
stack.rs

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