Skip to content

Commit 1da226b

Browse files
ssrlivecavivie
authored andcommitted
reformat code
1 parent 874d07d commit 1da226b

File tree

8 files changed

+74
-139
lines changed

8 files changed

+74
-139
lines changed

.github/workflows/main.yml

Lines changed: 15 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
name: CI
2-
on: [push, pull_request]
2+
3+
on:
4+
push:
5+
branches:
6+
- '**'
7+
pull_request:
8+
branches:
9+
- '**'
310

411
env:
512
CARGO_INCREMENTAL: 0
@@ -50,59 +57,24 @@ jobs:
5057
shell: bash
5158
- uses: Swatinem/rust-cache@v2
5259
- name: Setup android environment
60+
if: contains(matrix.build, 'android')
5361
uses: ./.github/actions/ndk-dev-rs
5462
with:
5563
rust-target: ${{ matrix.target }}
56-
if: contains(matrix.build, 'android')
5764
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }}
5865
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }} --release
5966

60-
msrv:
61-
name: MSRV
67+
msrv_n_clippy:
68+
name: MSRV & Clippy & Rustfmt
6269
runs-on: ${{ matrix.os }}
63-
env:
64-
MSRV: 1.65.0
6570
strategy:
6671
fail-fast: false
6772
matrix:
6873
os: [ubuntu-latest, macos-latest, windows-latest]
6974
steps:
7075
- uses: actions/checkout@v4
71-
- name: Install Rust
72-
run: |
73-
rustup toolchain install $MSRV --no-self-update --profile minimal
74-
rustup toolchain install nightly --no-self-update --profile minimal
75-
rustup default $MSRV
76-
shell: bash
77-
- name: Create Cargo.lock with minimal version
78-
run: cargo +nightly update -Zminimal-versions
79-
- name: Cache downloaded crates since minimal version is really slow in fetching
80-
uses: Swatinem/rust-cache@v2
81-
- run: cargo check --lib -p netstack-smoltcp --locked
82-
- run: cargo check --lib -p netstack-smoltcp --locked --all-features
83-
84-
clippy:
85-
name: Clippy
86-
runs-on: ubuntu-latest
87-
steps:
88-
- uses: actions/checkout@v4
89-
- name: Install Rust
90-
run: |
91-
rustup toolchain install stable --no-self-update --profile minimal --component rustfmt
92-
rustup default stable
93-
shell: bash
94-
- uses: Swatinem/rust-cache@v2
95-
- run: cargo clippy
96-
97-
rustfmt:
98-
name: Rustfmt
99-
runs-on: ubuntu-latest
100-
steps:
101-
- uses: actions/checkout@v4
102-
- name: Install Rust
103-
run: |
104-
rustup toolchain install stable --no-self-update --profile minimal --component rustfmt
105-
rustup default stable
106-
shell: bash
107-
- uses: Swatinem/rust-cache@v2
76+
- uses: dtolnay/rust-toolchain@stable
10877
- run: cargo fmt -- --check
78+
- run: cargo clippy --all-features -- -D warnings
79+
- run: cargo check --lib -p netstack-smoltcp
80+
- run: cargo check --lib -p netstack-smoltcp --all-features

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
/Cargo.lock
33

44
.idea
5+
.VSCodeCounter/
56
.vscode
67
.DS_Store
78
*.iml

Cargo.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,13 @@ description = """
1313
A netstack for the special purpose of turning packets from/to a TUN interface
1414
into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
1515
"""
16+
rust-version = "1.75.0"
1617

1718
[dependencies]
1819
tracing = { version = "0.1", default-features = false, features = ["std"] }
1920
tokio = { version = "1", features = ["sync", "time", "rt", "macros"] }
2021
tokio-util = "0.7.10"
21-
etherparse = "0.13"
22+
etherparse = "0.16"
2223
futures = "0.3"
2324
rand = "0.8"
2425
spin = "0.9"
@@ -34,7 +35,7 @@ smoltcp = { version = "0.11", default-features = false, features = [
3435
] }
3536

3637
[dev-dependencies]
37-
tun = { package = "tun2", version = "1.0", features = ["async"] }
38+
tun2 = { version = "3", features = ["async"] }
3839
tokio = { version = "1", features = [
3940
"rt",
4041
"macros",

examples/forward.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -86,24 +86,24 @@ async fn main_exec(opt: Opt) {
8686
)
8787
.unwrap();
8888

89-
let mut cfg = tun::Configuration::default();
90-
cfg.layer(tun::Layer::L3);
89+
let mut cfg = tun2::Configuration::default();
90+
cfg.layer(tun2::Layer::L3);
9191
let fd = -1;
9292
if fd >= 0 {
9393
cfg.raw_fd(fd);
9494
} else {
9595
cfg.tun_name("utun8")
9696
.address("10.10.10.2")
9797
.destination("10.10.10.1")
98-
.mtu(tun::DEFAULT_MTU);
98+
.mtu(tun2::DEFAULT_MTU);
9999
#[cfg(not(any(target_arch = "mips", target_arch = "mips64",)))]
100100
{
101101
cfg.netmask("255.255.255.0");
102102
}
103103
cfg.up();
104104
}
105105

106-
let device = tun::create_as_async(&cfg).unwrap();
106+
let device = tun2::create_as_async(&cfg).unwrap();
107107
let mut builder = StackBuilder::default()
108108
.enable_tcp(true)
109109
.enable_udp(true)
@@ -274,20 +274,20 @@ async fn new_udp_packet(addr: SocketAddr, iface: &str) -> std::io::Result<tokio:
274274
socket
275275
}
276276

277-
fn get_device_broadcast(device: &tun::AsyncDevice) -> Option<std::net::Ipv4Addr> {
278-
use tun::AbstractDevice;
277+
fn get_device_broadcast(device: &tun2::AsyncDevice) -> Option<std::net::Ipv4Addr> {
278+
use tun2::AbstractDevice;
279279

280-
let mtu = device.as_ref().mtu().unwrap_or(tun::DEFAULT_MTU);
280+
let mtu = device.mtu().unwrap_or(tun2::DEFAULT_MTU);
281281

282-
let address = match device.as_ref().address() {
282+
let address = match device.address() {
283283
Ok(a) => match a {
284284
IpAddr::V4(v4) => v4,
285285
IpAddr::V6(_) => return None,
286286
},
287287
Err(_) => return None,
288288
};
289289

290-
let netmask = match device.as_ref().netmask() {
290+
let netmask = match device.netmask() {
291291
Ok(n) => match n {
292292
IpAddr::V4(v4) => v4,
293293
IpAddr::V6(_) => return None,

src/device.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use smoltcp::{
99
};
1010
use tokio::sync::mpsc::{unbounded_channel, Permit, Sender, UnboundedReceiver, UnboundedSender};
1111

12-
use super::packet::AnyIpPktFrame;
12+
use crate::packet::AnyIpPktFrame;
1313

1414
pub(super) struct VirtualDevice {
1515
in_buf_avail: Arc<AtomicBool>,

src/stack.rs

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
use std::{
2-
io,
32
net::IpAddr,
43
pin::Pin,
54
task::{Context, Poll},
@@ -92,6 +91,7 @@ impl StackBuilder {
9291
self
9392
}
9493

94+
#[allow(clippy::type_complexity)]
9595
pub fn build(
9696
self,
9797
) -> std::io::Result<(
@@ -125,20 +125,12 @@ impl StackBuilder {
125125
));
126126
}
127127
let icmp_tx = if self.enable_icmp {
128-
if let Some(ref tcp_tx) = tcp_tx {
129-
Some(tcp_tx.clone())
130-
} else {
131-
None
132-
}
128+
tcp_tx.clone()
133129
} else {
134130
None
135131
};
136132

137-
let udp_socket = if let Some(udp_rx) = udp_rx {
138-
Some(UdpSocket::new(udp_rx, stack_tx.clone()))
139-
} else {
140-
None
141-
};
133+
let udp_socket = udp_rx.map(|udp_rx| UdpSocket::new(udp_rx, stack_tx.clone()));
142134

143135
let (tcp_runner, tcp_listener) = if let Some(tcp_rx) = tcp_rx {
144136
let (tcp_runner, tcp_listener) = TcpListener::new(tcp_rx, stack_tx);
@@ -207,7 +199,7 @@ impl Stack {
207199

208200
// Recv from stack.
209201
impl Stream for Stack {
210-
type Item = io::Result<AnyIpPktFrame>;
202+
type Item = std::io::Result<AnyIpPktFrame>;
211203

212204
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
213205
match self.stack_rx.poll_recv(cx) {
@@ -220,7 +212,7 @@ impl Stream for Stack {
220212

221213
// Send to stack.
222214
impl Sink<AnyIpPktFrame> for Stack {
223-
type Error = io::Error;
215+
type Error = std::io::Error;
224216

225217
fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
226218
if self.sink_buf.is_none() {
@@ -235,24 +227,16 @@ impl Sink<AnyIpPktFrame> for Stack {
235227
return Ok(());
236228
}
237229

238-
let packet = IpPacket::new_checked(item.as_slice()).map_err(|err| {
239-
io::Error::new(
240-
io::ErrorKind::InvalidInput,
241-
format!("invalid IP packet: {}", err),
242-
)
243-
})?;
230+
use std::io::{Error, ErrorKind::InvalidInput};
231+
let packet = IpPacket::new_checked(item.as_slice())
232+
.map_err(|err| Error::new(InvalidInput, format!("invalid IP packet: {}", err)))?;
244233

245234
let src_ip = packet.src_addr();
246235
let dst_ip = packet.dst_addr();
247236

248237
let addr_allowed = self.ip_filters.is_allowed(&src_ip, &dst_ip);
249238
if !addr_allowed {
250-
trace!(
251-
"IP packet {} -> {} (allowed? {}) throwing away",
252-
src_ip,
253-
dst_ip,
254-
addr_allowed,
255-
);
239+
trace!("IP packet {src_ip} -> {dst_ip} (allowed? {addr_allowed}) throwing away",);
256240
return Ok(());
257241
}
258242

src/tcp.rs

Lines changed: 22 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::{
22
collections::HashMap,
3-
io, mem,
43
net::SocketAddr,
54
pin::Pin,
65
sync::{
@@ -29,7 +28,7 @@ use tokio::{
2928
};
3029
use tracing::{error, trace};
3130

32-
use super::{
31+
use crate::{
3332
device::VirtualDevice,
3433
packet::{AnyIpPktFrame, IpPacket},
3534
Runner,
@@ -116,17 +115,12 @@ impl TcpListenerRunner {
116115

117116
let src_ip = packet.src_addr();
118117
let dst_ip = packet.dst_addr();
118+
let payload = packet.payload();
119119

120-
let packet = match TcpPacket::new_checked(packet.payload()) {
120+
let packet = match TcpPacket::new_checked(payload) {
121121
Ok(p) => p,
122122
Err(err) => {
123-
error!(
124-
"invalid TCP err: {}, src_ip: {}, dst_ip: {}, payload: {:?}",
125-
err,
126-
packet.src_addr(),
127-
packet.dst_addr(),
128-
packet.payload(),
129-
);
123+
error!("invalid TCP err: {err}, src_ip: {src_ip}, dst_ip: {dst_ip}, payload: {payload:?}");
130124
continue;
131125
}
132126
};
@@ -253,9 +247,7 @@ impl TcpListenerRunner {
253247
});
254248

255249
match result {
256-
Ok(..) => {
257-
wake_receiver = true;
258-
}
250+
Ok(..) => wake_receiver = true,
259251
Err(err) => {
260252
error!("socket recv error: {:?}, {:?}", err, socket.state());
261253

@@ -275,16 +267,16 @@ impl TcpListenerRunner {
275267

276268
// If socket is not in ESTABLISH, FIN-WAIT-1, FIN-WAIT-2,
277269
// the local client have closed our receiver.
270+
let states = [
271+
TcpState::Listen,
272+
TcpState::SynReceived,
273+
TcpState::Established,
274+
TcpState::FinWait1,
275+
TcpState::FinWait2,
276+
];
278277
if matches!(control.recv_state, TcpSocketState::Normal)
279278
&& !socket.may_recv()
280-
&& !matches!(
281-
socket.state(),
282-
TcpState::Listen
283-
| TcpState::SynReceived
284-
| TcpState::Established
285-
| TcpState::FinWait1
286-
| TcpState::FinWait2
287-
)
279+
&& !states.contains(&socket.state())
288280
{
289281
trace!("closed TCP Read Half, {:?}", socket.state());
290282

@@ -308,9 +300,7 @@ impl TcpListenerRunner {
308300
});
309301

310302
match result {
311-
Ok(..) => {
312-
wake_sender = true;
313-
}
303+
Ok(..) => wake_sender = true,
314304
Err(err) => {
315305
error!("socket send error: {:?}, {:?}", err, socket.state());
316306

@@ -466,7 +456,7 @@ impl AsyncRead for TcpStream {
466456
self: Pin<&mut Self>,
467457
cx: &mut Context<'_>,
468458
buf: &mut ReadBuf<'_>,
469-
) -> Poll<io::Result<()>> {
459+
) -> Poll<std::io::Result<()>> {
470460
let mut control = self.control.lock();
471461

472462
// Read from buffer
@@ -486,7 +476,9 @@ impl AsyncRead for TcpStream {
486476
return Poll::Pending;
487477
}
488478

489-
let recv_buf = unsafe { mem::transmute::<_, &mut [u8]>(buf.unfilled_mut()) };
479+
let recv_buf = unsafe {
480+
std::mem::transmute::<&mut [std::mem::MaybeUninit<u8>], &mut [u8]>(buf.unfilled_mut())
481+
};
490482
let n = control.recv_buffer.dequeue_slice(recv_buf);
491483
buf.advance(n);
492484

@@ -503,12 +495,12 @@ impl AsyncWrite for TcpStream {
503495
self: Pin<&mut Self>,
504496
cx: &mut Context<'_>,
505497
buf: &[u8],
506-
) -> Poll<io::Result<usize>> {
498+
) -> Poll<std::io::Result<usize>> {
507499
let mut control = self.control.lock();
508500

509501
// If state == Close | Closing | Closed, the TCP stream WR half is closed.
510502
if !matches!(control.send_state, TcpSocketState::Normal) {
511-
return Err(io::ErrorKind::BrokenPipe.into()).into();
503+
return Err(std::io::ErrorKind::BrokenPipe.into()).into();
512504
}
513505

514506
// Write to buffer
@@ -532,11 +524,11 @@ impl AsyncWrite for TcpStream {
532524
Ok(n).into()
533525
}
534526

535-
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
527+
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
536528
Ok(()).into()
537529
}
538530

539-
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
531+
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
540532
let mut control = self.control.lock();
541533

542534
if matches!(control.send_state, TcpSocketState::Closed) {

0 commit comments

Comments
 (0)