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                self.filter
90            )?,
91        ))
92    }
93}
94
95impl Default for StackBuilder {
96    fn default() -> Self {
97        Self {
98            tcp_buffer_max: 128,
99            tcp_buffer_window: 0x3FFF * 10,
100            _udp_buffer_window: 0x3FFF * 10,
101            timeout: None,
102            mtu: 1500,
103            filter: None,
104        }
105    }
106}
107
108pub enum IpPacket<T: AsRef<[u8]>> {
109    Ipv4(Ipv4Packet<T>),
110    Ipv6(Ipv6Packet<T>),
111}
112
113impl<T> IpPacket<T>
114where
115    T: AsRef<[u8]>,
116{
117    pub fn protocol(&self) -> IpProtocol {
118        match *self {
119            IpPacket::Ipv4(ref packet) => packet.next_header(),
120            IpPacket::Ipv6(ref packet) => packet.next_header(),
121        }
122    }
123
124    pub fn take(self) -> T {
125        match self {
126            IpPacket::Ipv4(packet) => packet.into_inner(),
127            IpPacket::Ipv6(packet) => packet.into_inner(),
128        }
129    }
130
131    pub fn src_addr(&self) -> IpAddr {
132        match *self {
133            IpPacket::Ipv4(ref packet) => IpAddr::from(packet.src_addr()),
134            IpPacket::Ipv6(ref packet) => IpAddr::from(packet.src_addr()),
135        }
136    }
137
138    pub fn dst_addr(&self) -> IpAddr {
139        match *self {
140            IpPacket::Ipv4(ref packet) => IpAddr::from(packet.dst_addr()),
141            IpPacket::Ipv6(ref packet) => IpAddr::from(packet.dst_addr()),
142        }
143    }
144
145    pub fn size(&self) -> Range<usize> {
146        match *self {
147            IpPacket::Ipv4(ref packet) => packet.header_len() as usize..packet.total_len() as usize,
148            IpPacket::Ipv6(ref packet) => packet.header_len() as usize..packet.total_len() as usize,
149        }
150    }
151}
152
153pub struct Stack {
154    sink_buf: Option<IpPacket<Bytes>>,
155    stack_rx: Pin<Box<UnboundedReceiver<Bytes>>>,
156    tcp_tx: UnboundedSender<IpPacket<bytes::Bytes>>,
157    _udp_tx: UnboundedSender<IpPacket<bytes::Bytes>>,
158}
159
160impl Stack {
161    fn poll_send(
162        mut self: std::pin::Pin<&mut Self>,
163        cx: &mut std::task::Context<'_>,
164    ) -> std::task::Poll<Result<(), std::io::Error>> {
165        let proto = match unsafe { Pin::get_unchecked_mut(self.as_mut()).sink_buf.take() } {
166            Some(val) => val,
167            None => return Ready(Ok(())),
168        };
169        let tx = match proto.protocol() {
170            IpProtocol::Tcp => &mut self.tcp_tx,
171            //IpProtocol::Udp => &mut self.udp_tx,
172            _ => {
173                //println!("ignore unknown protocol: {a}");
174                return std::task::Poll::Ready(Ok(()));
175            }
176        };
177        if let Err(e) = ready!(tx.poll_ready(cx)) {
178            unsafe { Pin::get_unchecked_mut(self).sink_buf.replace(proto) };
179            return Ready(Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, e)));
180        };
181        let _ = tx.start_send(proto);
182        let _ = Box::pin(tx).as_mut().poll_flush(cx);
183        Ready(Ok(()))
184    }
185}
186
187impl Sink<Bytes> for Stack {
188    type Error = std::io::Error;
189
190    fn poll_ready(
191        self: std::pin::Pin<&mut Self>,
192        cx: &mut std::task::Context<'_>,
193    ) -> std::task::Poll<Result<(), Self::Error>> {
194        if self.sink_buf.is_some() {
195            ready!(self.poll_send(cx))?;
196        }
197        Ready(Ok(()))
198    }
199
200    fn start_send(self: std::pin::Pin<&mut Self>, item: Bytes) -> Result<(), Self::Error> {
201        let packet = match IpVersion::of_packet(&item)
202            .map_err(|err| Error::new(InvalidInput, format!("invalid IP packet: {err}")))?
203        {
204            IpVersion::Ipv4 => {
205                IpPacket::Ipv4(Ipv4Packet::new_checked(item).map_err(|err| {
206                    Error::new(InvalidInput, format!("invalid IPv4 packet: {err}"))
207                })?)
208            }
209            IpVersion::Ipv6 => {
210                IpPacket::Ipv6(Ipv6Packet::new_checked(item).map_err(|err| {
211                    Error::new(InvalidInput, format!("invalid IPv6 packet: {err}"))
212                })?)
213            }
214        };
215        unsafe { Pin::get_unchecked_mut(self).sink_buf.replace(packet) };
216        Ok(())
217    }
218
219    fn poll_flush(
220        self: std::pin::Pin<&mut Self>,
221        cx: &mut std::task::Context<'_>,
222    ) -> std::task::Poll<Result<(), Self::Error>> {
223        self.poll_send(cx)
224    }
225
226    fn poll_close(
227        mut self: std::pin::Pin<&mut Self>,
228        _cx: &mut std::task::Context<'_>,
229    ) -> std::task::Poll<Result<(), Self::Error>> {
230        self.stack_rx.close();
231        Ready(Ok(()))
232    }
233}
234
235impl Stream for Stack {
236    type Item = Bytes;
237
238    fn poll_next(
239        mut self: Pin<&mut Self>,
240        cx: &mut std::task::Context<'_>,
241    ) -> std::task::Poll<Option<Self::Item>> {
242        Ready(ready!(self.stack_rx.as_mut().poll_next(cx)))
243    }
244}