Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 5 additions & 27 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 0 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ members = [
"ts_netcheck",
"ts_netmon",
"ts_netstack_smoltcp",
"ts_netstack_smoltcp_core",
"ts_netstack_smoltcp_socket",
"ts_nodecapability",
"ts_noise",
"ts_packet",
Expand Down Expand Up @@ -128,8 +126,6 @@ ts_kv_store_tokio = { path = "ts_kv_store_tokio", version = "0.6.1" }
ts_netcheck = { path = "ts_netcheck", version = "0.6.1" }
ts_netmon = { path = "ts_netmon", version = "0.6.1" }
ts_netstack_smoltcp = { path = "ts_netstack_smoltcp", version = "0.6.1" }
ts_netstack_smoltcp_core = { path = "ts_netstack_smoltcp_core", version = "0.6.1" }
ts_netstack_smoltcp_socket = { path = "ts_netstack_smoltcp_socket", version = "0.6.1" }
ts_nodecapability = { path = "ts_nodecapability", version = "0.6.1" }
ts_noise = { path = "ts_noise", version = "0.6.1" }
ts_packet = { path = "ts_packet", version = "0.6.1" }
Expand Down
27 changes: 27 additions & 0 deletions ts_dataplane/src/packet_ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ impl PacketIdent {

let ty = if disco::is_disco_message(payload) {
PacketType::Disco
} else if Self::looks_like_stun(payload) {
PacketType::StunBinding
} else if Self::could_be_wireguard(payload) {
// Assume that all remaining traffic that could be a Wireguard packet is one.
PacketType::Wireguard
Expand Down Expand Up @@ -115,6 +117,31 @@ impl PacketIdent {

[0u8; 3] == pkt[1..=3]
}

/// Report whether the packet looks like a STUN packet as defined in [RFC 8489].
///
/// Checks certain invariants that must be true if this is RFC 8489 STUN; does not
/// establish conclusive proof.
///
/// [RFC 8489]: https://www.rfc-editor.org/info/rfc8489/#section-5
Comment thread
npry marked this conversation as resolved.
Resolved
pub fn looks_like_stun(pkt: &[u8]) -> bool {
const MAGIC: &[u8] = &[0x21, 0x12, 0xa4, 0x42];

if pkt.len() < 20 {
return false;
}

if &pkt[4..8] != MAGIC {
return false;
}

// High two bits are always zero.
if pkt[0] >> 6 != 0 {
return false;
}

true
}
}

bitrs::layout!({
Expand Down
52 changes: 44 additions & 8 deletions ts_netstack_smoltcp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,37 @@ rust-version.workspace = true
workspace = true

[dependencies]
# Our crates.
ts_netstack_smoltcp_core.workspace = true
ts_netstack_smoltcp_socket.workspace = true

# Unconditionally required dependencies.
bytes.workspace = true
futures-util = { workspace = true, features = ["async-await", "async-await-macro"] }
tracing.workspace = true
flume.workspace = true
heapless.workspace = true
thiserror.workspace = true

# Required dependencies for the "tokio" feature.
tokio = { workspace = true, optional = true, features = ["time"] }

# Required dependencies for the "tun" feature.
tun-rs = { version = "2.8", optional = true, features = ["interruptible", "async"] }

futures-io = { version = "0.3", optional = true }

[dependencies.smoltcp]
workspace = true
features = [
"alloc",
"proto-ipv6",
"proto-ipv6-fragmentation",
"proto-ipv4",
"proto-ipv4-fragmentation",
"medium-ip",
"socket-tcp",
"socket-udp",
"socket-icmp",
"socket-raw",
]

[dev-dependencies]
# Required dependencies for benchmarks and examples.
axum = "0.8"
Expand All @@ -43,12 +59,32 @@ tracing-panic = "0.1"
ts_cli_util.workspace = true
tun-rs = { version = "2.8", features = ["async", "async_framed"] }

[dev-dependencies.smoltcp]
workspace = true
features = [
"alloc",
"proto-ipv6",
"proto-ipv6-fragmentation",
"proto-ipv4",
"proto-ipv4-fragmentation",
"medium-ip",
"socket-tcp",
"socket-udp",
"socket-icmp",
"socket-raw",
"iface-max-addr-count-4",
"log",
"verbose",
]

[features]
std = ["ts_netstack_smoltcp_socket/std"]
tokio = ["dep:tokio", "ts_netstack_smoltcp_socket/tokio", "std"]
futures-io = ["ts_netstack_smoltcp_socket/futures-io", "std"]
std = []

tokio = ["dep:tokio", "std"]
futures-io = ["dep:futures-io", "std"]

# provide a device driver using tun-rs
tun = ["dep:tun-rs"]
tun = ["dep:tun-rs", "std"]

[[example]]
name = "udp_tun"
Expand Down
20 changes: 18 additions & 2 deletions ts_netstack_smoltcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ Userspace netstack built as an opinionated wrapper around [`smoltcp`].

# Example

Compare the examples from [`ts_netstack_smoltcp_core`] and [`ts_netstack_smoltcp_socket`]:
NB: compare the examples from [`netcore`] and [`netsock`]:

```rust
#![cfg(feature = "std")]

extern crate ts_netstack_smoltcp as netstack;

use core::time::Duration;
use netstack::{netcore::smoltcp, HasChannel, CreateSocket};
use netstack::{smoltcp, HasChannel, CreateSocket};

fn main() {
let (mut stack, mut pipe) = netstack::piped(Default::default());
Expand All @@ -35,3 +35,19 @@ fn main() {
assert!(packet.ends_with(b"hello"));
}
```

# Crate layout

The core netstack is implemented in [`netcore`]. This is a minimal channel-based command API. It
doesn't provide ergonomic socket types, just the commands to manipulate them.

[`netsock`] provides a sockets implementation around [`netcore`], i.e. it has `UdpSocket`,
`TcpStream`, etc. types.

The top-level crate namespace provides [`Netstack`], which is essentially a runner that adapts a
[`smoltcp::phy::Device`] onto the core logic and exposes the methods required to construct the
sockets from [`netsock`].

The crate is laid out this way to allow users to replace components if desired. [`netcore`] has no
knowledge of and does not depend on any of the internals of [`netsock`]; ditto from [`netsock`] to
the root crate.
4 changes: 2 additions & 2 deletions ts_netstack_smoltcp/benches/throughput_tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::time::Instant;
use bytes::BytesMut;
use clap::Parser;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use ts_netstack_smoltcp_socket::CreateSocket;
use ts_netstack_smoltcp::{netcore, netsock::CreateSocket};

#[path = "../examples/common/mod.rs"]
mod common;
Expand All @@ -31,7 +31,7 @@ async fn main() -> common::Result<()> {
let args = Args::parse();

let (ch1, ch2) = common::spawn_piped_netstacks(
ts_netstack_smoltcp_core::Config {
netcore::Config {
tcp_buffer_size: TCP_SOCKET_BUF_SIZE,
command_channel_capacity: Some(128),
mtu: usize::MAX,
Expand Down
4 changes: 2 additions & 2 deletions ts_netstack_smoltcp/benches/throughput_udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::time::Instant;

use bytes::BytesMut;
use clap::Parser;
use ts_netstack_smoltcp_socket::CreateSocket;
use ts_netstack_smoltcp::{CreateSocket, netcore};

#[path = "../examples/common/mod.rs"]
mod common;
Expand All @@ -25,7 +25,7 @@ async fn main() -> common::Result<()> {
let args = Args::parse();

let (ch1, ch2) = common::spawn_piped_netstacks(
ts_netstack_smoltcp_core::Config {
netcore::Config {
udp_buffer_size: BUF_SIZE,
udp_message_count: 1024,
command_channel_capacity: Some(128),
Expand Down
7 changes: 3 additions & 4 deletions ts_netstack_smoltcp/examples/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ use core::net::{Ipv4Addr, SocketAddr};
use std::sync::Once;

pub extern crate ts_netstack_smoltcp as netstack;
pub extern crate ts_netstack_smoltcp_core as netcore;
pub extern crate ts_netstack_smoltcp_socket as netsock;

#[cfg(feature = "std")]
use netcore::{HasChannel, NetstackControl, smoltcp};
use netcore::{HasChannel, NetstackControl};
#[cfg(feature = "std")]
use netstack::{Netstack, WakingPipe, WakingPipeDev};
use netstack::{Netstack, WakingPipe, WakingPipeDev, smoltcp};
pub use netstack::{netcore, netsock};

pub type Result<T> = core::result::Result<T, Box<dyn core::error::Error + Send + Sync + 'static>>;

Expand Down
9 changes: 6 additions & 3 deletions ts_netstack_smoltcp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ extern crate alloc;
#[cfg(any(test, feature = "std"))]
extern crate std;

pub extern crate flume;
pub extern crate smoltcp;

use core::{borrow::Borrow, time::Duration};

pub extern crate ts_netstack_smoltcp_core as netcore;
pub extern crate ts_netstack_smoltcp_socket as netsock;
pub mod netcore;
pub mod netsock;

use netcore::{Channel, smoltcp};
use netcore::Channel;
pub use netcore::{HasChannel, Netstack as CoreStack};
pub use netsock::CreateSocket;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ more-portable API.
This is the `core` crate, which just provides a [`Netstack`] type that contains the
required state and logic to drive the contained [`smoltcp::iface::Interface`] to process
commands received over a [`Channel`]. The ergonomic sockets API around the
remote end of that channel is provided by `ts_netstack_smoltcp_socket`.
remote end of that channel is provided by [`netsock`][crate::netsock].

The whole thing is integrated along with runtime functionality in `ts_netstack_smoltcp`.

Expand All @@ -36,13 +36,14 @@ The whole thing is integrated along with runtime functionality in `ts_netstack_s
## Example

```rust
extern crate ts_netstack_smoltcp_core as netcore;

use core::net::SocketAddr;
use bytes::Bytes;
use smoltcp::time::Instant;
use smoltcp::phy::Medium;
use netcore::{Response, udp, HasChannel};
use ts_netstack_smoltcp::{
netcore::{Response, udp, HasChannel, self},
smoltcp::{
self, phy::Medium, time::Instant,
},
};

fn main() -> Result<(), netcore::Error> {
// Construct a new netstack:
Expand Down Expand Up @@ -102,6 +103,6 @@ fn main() -> Result<(), netcore::Error> {
}
```

Compare the examples in `ts_netstack_smoltcp_socket` and `ts_netstack_smoltcp` (which
Compare the examples in [`netsock`][crate::netsock] and [the crate root][crate] (which
do the same thing as this example) for an indication of the abstraction that crate
provides.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use core::borrow::Borrow;

use smoltcp::iface::SocketHandle;

use crate::{ChannelClosedError, Command, Error, Netstack, Response, command::Request};
use crate::{
netcore,
netcore::{ChannelClosedError, Command, Error, Netstack, Response, command::Request},
};

/// Channel type through which commands to the netstack flow.
// NOTE(npry): command channels are weak because the netstack holds a strong sender handle
Expand All @@ -26,18 +29,18 @@ pub trait HasChannel {

/// Send a request through the channel.
///
/// Convenience wrapper around [`request_blocking`][crate::request_blocking].
/// Convenience wrapper around [`request_blocking`][netcore::request_blocking].
fn request_blocking(
&self,
handle: Option<SocketHandle>,
command: impl Into<Command>,
) -> Result<Response, ChannelClosedError> {
crate::request_blocking(self.borrow_channel().borrow(), handle, command)
netcore::request_blocking(self.borrow_channel().borrow(), handle, command)
}

/// Asynchronously send a request through the channel.
///
/// Convenience wrapper around [`request`][crate::request].
/// Convenience wrapper around [`request`][netcore::request].
fn request(
&self,
handle: Option<SocketHandle>,
Expand All @@ -46,21 +49,21 @@ pub trait HasChannel {
let ch = self.command_channel();
let command = command.into();

async move { crate::request(&ch, handle, command).await }
async move { netcore::request(&ch, handle, command).await }
}

/// Send a nonblocking request, discarding any response.
///
/// This is mainly intended for use in [`Drop`] implementations, as they can't be `async`
/// and it would be frequently be surprising if they blocked the calling thread.
///
/// Convenience wrapper around [`request_nonblocking`][crate::request_nonblocking].
/// Convenience wrapper around [`request_nonblocking`][netcore::request_nonblocking].
fn request_nonblocking(
&self,
handle: Option<SocketHandle>,
command: impl Into<Command>,
) -> Result<(), ChannelClosedError> {
crate::request_nonblocking(self.borrow_channel().borrow(), handle, command)
netcore::request_nonblocking(self.borrow_channel().borrow(), handle, command)
}
}

Expand Down
Loading
Loading