-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathlib.rs
More file actions
234 lines (211 loc) · 7.9 KB
/
lib.rs
File metadata and controls
234 lines (211 loc) · 7.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#![doc = include_str!("../README.md")]
use ahash::AHashMap;
use packet::{NetworkPacket, NetworkTuple, TransportHeader};
use std::{sync::Arc, time::Duration};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
select,
sync::mpsc::{self, UnboundedReceiver, UnboundedSender},
task::JoinHandle,
};
pub(crate) type PacketSender = UnboundedSender<NetworkPacket>;
pub(crate) type PacketReceiver = UnboundedReceiver<NetworkPacket>;
pub(crate) type SessionCollection = std::sync::Arc<tokio::sync::Mutex<AHashMap<NetworkTuple, PacketSender>>>;
mod error;
mod packet;
mod stream;
pub use self::error::{IpStackError, Result};
pub use self::stream::{IpStackStream, IpStackTcpStream, IpStackUdpStream, IpStackUnknownTransport};
pub use self::stream::{TcpConfig, TcpOptions};
pub use etherparse::IpNumber;
#[cfg(unix)]
const TTL: u8 = 64;
#[cfg(windows)]
const TTL: u8 = 128;
#[cfg(unix)]
const TUN_FLAGS: [u8; 2] = [0x00, 0x00];
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
const TUN_PROTO_IP6: [u8; 2] = [0x86, 0xdd];
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
const TUN_PROTO_IP4: [u8; 2] = [0x08, 0x00];
#[cfg(any(target_os = "macos", target_os = "ios"))]
const TUN_PROTO_IP6: [u8; 2] = [0x00, 0x0A];
#[cfg(any(target_os = "macos", target_os = "ios"))]
const TUN_PROTO_IP4: [u8; 2] = [0x00, 0x02];
#[non_exhaustive]
pub struct IpStackConfig {
pub mtu: u16,
pub packet_information: bool,
pub udp_timeout: Duration,
pub tcp_config: Arc<TcpConfig>,
}
impl Default for IpStackConfig {
fn default() -> Self {
IpStackConfig {
mtu: u16::MAX,
packet_information: false,
tcp_config: Arc::new(TcpConfig::default()),
udp_timeout: Duration::from_secs(30),
}
}
}
impl IpStackConfig {
/// Set custom TCP configuration
pub fn with_tcp_config(&mut self, config: TcpConfig) -> &mut Self {
self.tcp_config = Arc::new(config);
self
}
pub fn udp_timeout(&mut self, timeout: Duration) -> &mut Self {
self.udp_timeout = timeout;
self
}
pub fn mtu(&mut self, mtu: u16) -> &mut Self {
self.mtu = mtu;
self
}
pub fn packet_information(&mut self, packet_information: bool) -> &mut Self {
self.packet_information = packet_information;
self
}
}
pub struct IpStack {
accept_receiver: UnboundedReceiver<IpStackStream>,
_handle: JoinHandle<Result<()>>, // Just hold the task handle
}
impl IpStack {
pub fn new<Device>(config: IpStackConfig, device: Device) -> IpStack
where
Device: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
let (accept_sender, accept_receiver) = mpsc::unbounded_channel::<IpStackStream>();
IpStack {
accept_receiver,
_handle: run(config, device, accept_sender),
}
}
pub async fn accept(&mut self) -> Result<IpStackStream, IpStackError> {
self.accept_receiver.recv().await.ok_or(IpStackError::AcceptError)
}
}
fn run<Device: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
config: IpStackConfig,
mut device: Device,
accept_sender: UnboundedSender<IpStackStream>,
) -> JoinHandle<Result<()>> {
let sessions: SessionCollection = std::sync::Arc::new(tokio::sync::Mutex::new(AHashMap::new()));
let pi = config.packet_information;
let offset = if pi && cfg!(unix) { 4 } else { 0 };
let mut buffer = vec![0_u8; u16::MAX as usize + offset];
let (up_pkt_sender, mut up_pkt_receiver) = mpsc::unbounded_channel::<NetworkPacket>();
tokio::spawn(async move {
loop {
select! {
Ok(n) = device.read(&mut buffer) => {
let u = up_pkt_sender.clone();
if let Err(e) = process_device_read(&buffer[offset..n], sessions.clone(), u, &config, &accept_sender).await {
let io_err: std::io::Error = e.into();
if io_err.kind() == std::io::ErrorKind::ConnectionRefused {
log::trace!("Received junk data: {io_err}");
} else {
log::warn!("process_device_read error: {io_err}");
}
}
}
Some(packet) = up_pkt_receiver.recv() => {
process_upstream_recv(packet, &mut device, #[cfg(unix)]pi).await?;
}
}
}
})
}
async fn process_device_read(
data: &[u8],
sessions: SessionCollection,
up_pkt_sender: PacketSender,
config: &IpStackConfig,
accept_sender: &UnboundedSender<IpStackStream>,
) -> Result<()> {
let Ok(packet) = NetworkPacket::parse(data) else {
let stream = IpStackStream::UnknownNetwork(data.to_owned());
accept_sender.send(stream)?;
return Ok(());
};
if let TransportHeader::Unknown = packet.transport_header() {
let stream = IpStackStream::UnknownTransport(IpStackUnknownTransport::new(
packet.src_addr().ip(),
packet.dst_addr().ip(),
packet.payload.unwrap_or_default(),
&packet.ip,
config.mtu,
up_pkt_sender,
));
accept_sender.send(stream)?;
return Ok(());
}
let sessions_clone = sessions.clone();
let network_tuple = packet.network_tuple();
match sessions.lock().await.entry(network_tuple) {
std::collections::hash_map::Entry::Occupied(entry) => {
let len = packet.payload.as_ref().map(|p| p.len()).unwrap_or(0);
log::trace!("packet sent to stream: {network_tuple} len {len}");
entry.get().send(packet).map_err(std::io::Error::other)?;
}
std::collections::hash_map::Entry::Vacant(entry) => {
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let ip_stack_stream = create_stream(packet, config, up_pkt_sender, Some(tx))?;
tokio::spawn(async move {
rx.await.ok();
sessions_clone.lock().await.remove(&network_tuple);
log::debug!("session destroyed: {network_tuple}");
});
let packet_sender = ip_stack_stream.stream_sender()?;
accept_sender.send(ip_stack_stream)?;
entry.insert(packet_sender);
log::debug!("session created: {network_tuple}");
}
}
Ok(())
}
fn create_stream(
packet: NetworkPacket,
cfg: &IpStackConfig,
up_pkt_sender: PacketSender,
msgr: Option<::tokio::sync::oneshot::Sender<()>>,
) -> Result<IpStackStream> {
let src_addr = packet.src_addr();
let dst_addr = packet.dst_addr();
match packet.transport_header() {
TransportHeader::Tcp(h) => {
let stream = IpStackTcpStream::new(src_addr, dst_addr, h.clone(), up_pkt_sender, cfg.mtu, msgr, cfg.tcp_config.clone())?;
Ok(IpStackStream::Tcp(stream))
}
TransportHeader::Udp(_) => {
let payload = packet.payload.unwrap_or_default();
let stream = IpStackUdpStream::new(src_addr, dst_addr, payload, up_pkt_sender, cfg.mtu, cfg.udp_timeout, msgr);
Ok(IpStackStream::Udp(stream))
}
TransportHeader::Unknown => Err(IpStackError::UnsupportedTransportProtocol),
}
}
async fn process_upstream_recv<Device: AsyncWrite + Unpin + 'static>(
up_packet: NetworkPacket,
device: &mut Device,
#[cfg(unix)] packet_information: bool,
) -> Result<()> {
#[allow(unused_mut)]
let Ok(mut packet_bytes) = up_packet.to_bytes() else {
log::warn!("to_bytes error");
return Ok(());
};
#[cfg(unix)]
if packet_information {
if up_packet.src_addr().is_ipv4() {
packet_bytes.splice(0..0, [TUN_FLAGS, TUN_PROTO_IP4].concat());
} else {
packet_bytes.splice(0..0, [TUN_FLAGS, TUN_PROTO_IP6].concat());
}
}
device.write_all(&packet_bytes).await?;
// device.flush().await?;
Ok(())
}