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