Skip to content

Commit

Permalink
reformat code
Browse files Browse the repository at this point in the history
  • Loading branch information
ssrlive authored and cavivie committed Oct 13, 2024
1 parent 874d07d commit 1da226b
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 139 deletions.
58 changes: 15 additions & 43 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
name: CI
on: [push, pull_request]

on:
push:
branches:
- '**'
pull_request:
branches:
- '**'

env:
CARGO_INCREMENTAL: 0
Expand Down Expand Up @@ -50,59 +57,24 @@ jobs:
shell: bash
- uses: Swatinem/rust-cache@v2
- name: Setup android environment
if: contains(matrix.build, 'android')
uses: ./.github/actions/ndk-dev-rs
with:
rust-target: ${{ matrix.target }}
if: contains(matrix.build, 'android')
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }}
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }} --release

msrv:
name: MSRV
msrv_n_clippy:
name: MSRV & Clippy & Rustfmt
runs-on: ${{ matrix.os }}
env:
MSRV: 1.65.0
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
rustup toolchain install $MSRV --no-self-update --profile minimal
rustup toolchain install nightly --no-self-update --profile minimal
rustup default $MSRV
shell: bash
- name: Create Cargo.lock with minimal version
run: cargo +nightly update -Zminimal-versions
- name: Cache downloaded crates since minimal version is really slow in fetching
uses: Swatinem/rust-cache@v2
- run: cargo check --lib -p netstack-smoltcp --locked
- run: cargo check --lib -p netstack-smoltcp --locked --all-features

clippy:
name: Clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
rustup toolchain install stable --no-self-update --profile minimal --component rustfmt
rustup default stable
shell: bash
- uses: Swatinem/rust-cache@v2
- run: cargo clippy

rustfmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
run: |
rustup toolchain install stable --no-self-update --profile minimal --component rustfmt
rustup default stable
shell: bash
- uses: Swatinem/rust-cache@v2
- uses: dtolnay/rust-toolchain@stable
- run: cargo fmt -- --check
- run: cargo clippy --all-features -- -D warnings
- run: cargo check --lib -p netstack-smoltcp
- run: cargo check --lib -p netstack-smoltcp --all-features
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/Cargo.lock

.idea
.VSCodeCounter/
.vscode
.DS_Store
*.iml
Expand Down
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ description = """
A netstack for the special purpose of turning packets from/to a TUN interface
into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
"""
rust-version = "1.75.0"

[dependencies]
tracing = { version = "0.1", default-features = false, features = ["std"] }
tokio = { version = "1", features = ["sync", "time", "rt", "macros"] }
tokio-util = "0.7.10"
etherparse = "0.13"
etherparse = "0.16"
futures = "0.3"
rand = "0.8"
spin = "0.9"
Expand All @@ -34,7 +35,7 @@ smoltcp = { version = "0.11", default-features = false, features = [
] }

[dev-dependencies]
tun = { package = "tun2", version = "1.0", features = ["async"] }
tun2 = { version = "3", features = ["async"] }
tokio = { version = "1", features = [
"rt",
"macros",
Expand Down
18 changes: 9 additions & 9 deletions examples/forward.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,24 +86,24 @@ async fn main_exec(opt: Opt) {
)
.unwrap();

let mut cfg = tun::Configuration::default();
cfg.layer(tun::Layer::L3);
let mut cfg = tun2::Configuration::default();
cfg.layer(tun2::Layer::L3);
let fd = -1;
if fd >= 0 {
cfg.raw_fd(fd);
} else {
cfg.tun_name("utun8")
.address("10.10.10.2")
.destination("10.10.10.1")
.mtu(tun::DEFAULT_MTU);
.mtu(tun2::DEFAULT_MTU);
#[cfg(not(any(target_arch = "mips", target_arch = "mips64",)))]
{
cfg.netmask("255.255.255.0");
}
cfg.up();
}

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

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

let mtu = device.as_ref().mtu().unwrap_or(tun::DEFAULT_MTU);
let mtu = device.mtu().unwrap_or(tun2::DEFAULT_MTU);

let address = match device.as_ref().address() {
let address = match device.address() {
Ok(a) => match a {
IpAddr::V4(v4) => v4,
IpAddr::V6(_) => return None,
},
Err(_) => return None,
};

let netmask = match device.as_ref().netmask() {
let netmask = match device.netmask() {
Ok(n) => match n {
IpAddr::V4(v4) => v4,
IpAddr::V6(_) => return None,
Expand Down
2 changes: 1 addition & 1 deletion src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use smoltcp::{
};
use tokio::sync::mpsc::{unbounded_channel, Permit, Sender, UnboundedReceiver, UnboundedSender};

use super::packet::AnyIpPktFrame;
use crate::packet::AnyIpPktFrame;

pub(super) struct VirtualDevice {
in_buf_avail: Arc<AtomicBool>,
Expand Down
34 changes: 9 additions & 25 deletions src/stack.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::{
io,
net::IpAddr,
pin::Pin,
task::{Context, Poll},
Expand Down Expand Up @@ -92,6 +91,7 @@ impl StackBuilder {
self
}

#[allow(clippy::type_complexity)]
pub fn build(
self,
) -> std::io::Result<(
Expand Down Expand Up @@ -125,20 +125,12 @@ impl StackBuilder {
));
}
let icmp_tx = if self.enable_icmp {
if let Some(ref tcp_tx) = tcp_tx {
Some(tcp_tx.clone())
} else {
None
}
tcp_tx.clone()
} else {
None
};

let udp_socket = if let Some(udp_rx) = udp_rx {
Some(UdpSocket::new(udp_rx, stack_tx.clone()))
} else {
None
};
let udp_socket = udp_rx.map(|udp_rx| UdpSocket::new(udp_rx, stack_tx.clone()));

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

// Recv from stack.
impl Stream for Stack {
type Item = io::Result<AnyIpPktFrame>;
type Item = std::io::Result<AnyIpPktFrame>;

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

// Send to stack.
impl Sink<AnyIpPktFrame> for Stack {
type Error = io::Error;
type Error = std::io::Error;

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

let packet = IpPacket::new_checked(item.as_slice()).map_err(|err| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("invalid IP packet: {}", err),
)
})?;
use std::io::{Error, ErrorKind::InvalidInput};
let packet = IpPacket::new_checked(item.as_slice())
.map_err(|err| Error::new(InvalidInput, format!("invalid IP packet: {}", err)))?;

let src_ip = packet.src_addr();
let dst_ip = packet.dst_addr();

let addr_allowed = self.ip_filters.is_allowed(&src_ip, &dst_ip);
if !addr_allowed {
trace!(
"IP packet {} -> {} (allowed? {}) throwing away",
src_ip,
dst_ip,
addr_allowed,
);
trace!("IP packet {src_ip} -> {dst_ip} (allowed? {addr_allowed}) throwing away",);
return Ok(());
}

Expand Down
52 changes: 22 additions & 30 deletions src/tcp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{
collections::HashMap,
io, mem,
net::SocketAddr,
pin::Pin,
sync::{
Expand Down Expand Up @@ -29,7 +28,7 @@ use tokio::{
};
use tracing::{error, trace};

use super::{
use crate::{
device::VirtualDevice,
packet::{AnyIpPktFrame, IpPacket},
Runner,
Expand Down Expand Up @@ -116,17 +115,12 @@ impl TcpListenerRunner {

let src_ip = packet.src_addr();
let dst_ip = packet.dst_addr();
let payload = packet.payload();

let packet = match TcpPacket::new_checked(packet.payload()) {
let packet = match TcpPacket::new_checked(payload) {
Ok(p) => p,
Err(err) => {
error!(
"invalid TCP err: {}, src_ip: {}, dst_ip: {}, payload: {:?}",
err,
packet.src_addr(),
packet.dst_addr(),
packet.payload(),
);
error!("invalid TCP err: {err}, src_ip: {src_ip}, dst_ip: {dst_ip}, payload: {payload:?}");
continue;
}
};
Expand Down Expand Up @@ -253,9 +247,7 @@ impl TcpListenerRunner {
});

match result {
Ok(..) => {
wake_receiver = true;
}
Ok(..) => wake_receiver = true,
Err(err) => {
error!("socket recv error: {:?}, {:?}", err, socket.state());

Expand All @@ -275,16 +267,16 @@ impl TcpListenerRunner {

// If socket is not in ESTABLISH, FIN-WAIT-1, FIN-WAIT-2,
// the local client have closed our receiver.
let states = [
TcpState::Listen,
TcpState::SynReceived,
TcpState::Established,
TcpState::FinWait1,
TcpState::FinWait2,
];
if matches!(control.recv_state, TcpSocketState::Normal)
&& !socket.may_recv()
&& !matches!(
socket.state(),
TcpState::Listen
| TcpState::SynReceived
| TcpState::Established
| TcpState::FinWait1
| TcpState::FinWait2
)
&& !states.contains(&socket.state())
{
trace!("closed TCP Read Half, {:?}", socket.state());

Expand All @@ -308,9 +300,7 @@ impl TcpListenerRunner {
});

match result {
Ok(..) => {
wake_sender = true;
}
Ok(..) => wake_sender = true,
Err(err) => {
error!("socket send error: {:?}, {:?}", err, socket.state());

Expand Down Expand Up @@ -466,7 +456,7 @@ impl AsyncRead for TcpStream {
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
) -> Poll<std::io::Result<()>> {
let mut control = self.control.lock();

// Read from buffer
Expand All @@ -486,7 +476,9 @@ impl AsyncRead for TcpStream {
return Poll::Pending;
}

let recv_buf = unsafe { mem::transmute::<_, &mut [u8]>(buf.unfilled_mut()) };
let recv_buf = unsafe {
std::mem::transmute::<&mut [std::mem::MaybeUninit<u8>], &mut [u8]>(buf.unfilled_mut())
};
let n = control.recv_buffer.dequeue_slice(recv_buf);
buf.advance(n);

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

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

// Write to buffer
Expand All @@ -532,11 +524,11 @@ impl AsyncWrite for TcpStream {
Ok(n).into()
}

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

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

if matches!(control.send_state, TcpSocketState::Closed) {
Expand Down
Loading

0 comments on commit 1da226b

Please sign in to comment.