Skip to content

Commit

Permalink
V3 (#105)
Browse files Browse the repository at this point in the history
* compatible with low-version rustc

* pass clippy

* Bump version

* prepare to support windows-tap

* update

* prepare to support windows-tap (#101)

* compatible with low-version rustc

* pass clippy

* Bump version

* prepare to support windows-tap

* update

* support windows-tap

* support windows-tap

* fix

* cargo fmt

* cargo clippy

* cargo clippy

* deliver layer2 for tap

* deliver layer2

* Update device.rs

* refine

* fix codec

* adjust 'AbstractDevice'

* remove tap_packet

* change

* fix bsd error

* fix bsd error

* fix bsd error

* fix bsd error

* fix bsd error

* fix bsd error

* fix bsd error

* fix linux error

* cargo clippy

* cargo clippy

* fix linux error

* fix cargo.toml

* fix some errors

* cargo fmt

* fix windows example

* fix windows example

* Bump version

* cargo clippy

* fix error

* fix error

* fix error

* update linux

* update config

* fix macos error

* fix macos

* update recv

* config linux

* fix some errors

* Remove the MTU on Tun

* fix error

* fix macos

* fix error

* fix example

* fix android

* refine

* fix windows async

* fix async windows

* fix freebsd

* fix freebsd

* update readme

* Update README.md

* windows async

* windows shutdown

* AsyncDevice Drop

* update linux

* Remove useless code

* shutdown

* tap drop

* add shutdown

* add shutdown

* add shutdown

* add shutdown

* add feature experimental

* add feature experimental

* add feature experimental

* add feature experimental

* fix features

* fix features

* fix bug

* remove shutdown

* windows enable

* windows enable

* windows enable

* update experimental

* update experimental

* cargo clippy

* update experimental

* add flag

* recv Interest ERROR

* address_with_prefix

* use IntoAddress

* clippy

* set_destination

* rename variable name

* update cargo.toml

* cargo clippy ios&android

* fix shutdown

* update macos

* update macos

* refine macos route

* update freebsd

* update freebsd

* update freebsd

* update freebsd

* update freebsd

* update freebsd

* update freebsd

* add tap for freebsd

* select fd

* add tap for freebsd

* update

* update

* update

* select pipe macos

* update readme

* linux if_indextoname

* Change method name

* use write_all

* ioctl_read tungetiff

* fmt

* fmt

* linux from_raw_fd

* fmt

* get name from libc

* test freebsd

* revert freebsd

* add into_raw_fd

* freebsd

* freebsd

* freebsd

* revert freebsd

* platform from_raw_fd

* packet_information default is true in iOS|macos

* update freebsd

* update freebsd

* update freebsd

* update freebsd

* update freebsd

* mac address

* mac address

* mac address

* mac address

* add set mac address for freebsd

* update

* update freebsd

* update freebsd

* update freebsd mac

* open len

* open mac_address for windows

* linux set/get mac addr

* linux set/get mac addr

* linux set/get mac addr

* windows tap

* cargo fmt

* cargo fmt

* cargo clippy

* cargo clippy windows

* cargo clippy windows

* remove println

* map_err

* windows code

* ping-tap

* cargo fmt

* cargo fmt

* cargo clippy

---------

Co-authored-by: lubeilin <1791778603@qq.com>
Co-authored-by: lbl <49143209+lbl8603@users.noreply.github.com>
  • Loading branch information
3 people authored Aug 30, 2024
1 parent 0451815 commit 6746129
Show file tree
Hide file tree
Showing 41 changed files with 3,334 additions and 2,842 deletions.
2 changes: 2 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ protocol = "sparse"
# target = ["x86_64-unknown-linux-musl"]
# target = ["x86_64-unknown-linux-gnu"]
# target = ["aarch64-linux-android"]
# target = ["x86_64-linux-android"]
# target = ["aarch64-apple-ios"]
# target = ["x86_64-apple-ios"]
# target = ["x86_64-pc-windows-msvc"]
# target = ["x86_64-apple-darwin"]
# target = ["x86_64-unknown-freebsd"]
37 changes: 19 additions & 18 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,14 @@ rustversion = "1.0.17"
nix = { version = "0.29", features = ["ioctl"] }

[target.'cfg(target_os = "windows")'.dependencies]
scopeguard = "1.2.0"
winreg = "0.52.0"
c2rust-bitfields = "0.18"
windows-sys = { version = "0.59", features = [
"Win32_Networking_WinSock",
"Win32_Devices_DeviceAndDriverInstallation",
"Win32_Storage_FileSystem",
"Win32_System_Registry",
"Win32_Networking_WinSock",
"Win32_NetworkManagement_Ndis",
"Win32_Foundation",
"Win32_Security",
Expand All @@ -42,47 +48,42 @@ windows-sys = { version = "0.59", features = [
"Win32_UI_WindowsAndMessaging",
"Win32_System_LibraryLoader",
] }
wintun = { version = "0.6", features = ["panic_on_unsent_packets"],package="wintun-bindings" }
wintun = { version = "0.6", features = ["panic_on_unsent_packets"], package = "wintun-bindings" }
libloading = "0.8"
winapi = {version = "0.3",features = [
"errhandlingapi",
"combaseapi",
"ioapiset",
"winioctl",
"setupapi",
"synchapi",
"netioapi",
"fileapi","handleapi","winerror","minwindef","ifdef","basetsd","winnt","winreg","winbase","minwinbase",
"impl-default"
]}

[target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies]
ipnet = "2"

[target.'cfg(any(target_os = "linux", target_os = "freebsd",target_os = "windows"))'.dependencies]
mac_address = "1.1.7"

[dev-dependencies]
ctrlc2 = { version = "3", features = ["tokio", "termination"] }
env_logger = "0.11"
futures = "0.3"
packet = "0.1"
serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread"] }
tokio = { version = "1", features = ["rt-multi-thread", "time"] }

[features]
default = ["wintun-dns"]
async = ["tokio", "futures-core", "tokio-util"]
wintun-dns = []
experimental = []

[package.metadata.docs.rs]
features = ["async"]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

[[example]]
name = "read-async"
required-features = ["async"]

[[example]]
name = "read-async-codec"
required-features = ["async"]

[[example]]
name = "ping-tun"
required-features = ["async"]

[[example]]
name = "ping-tap"
required-features = ["async"]
38 changes: 10 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,26 @@
TUN interfaces
Tun/Tap interfaces
==============
[![Crates.io](https://img.shields.io/crates/v/tun2.svg)](https://crates.io/crates/tun2)
![tun2](https://docs.rs/tun2/badge.svg)
![WTFPL](http://img.shields.io/badge/license-WTFPL-blue.svg)

This crate allows the creation and usage of TUN interfaces, the aim is to make this cross-platform.

> Since the original maintainer @meh is no longer interested in continuing to maintain
> [tun](https://crates.io/crates/tun) at [repo](https://github.com/meh/rust-tun),
> We (@ssrlive, @xmh0511) created the [tun2](https://github.com/ssrlive/rust-tun) branch repo and
> continued to actively update. Welcome to any interested contributor.
> If you want to be a co-contributor and publisher of [tun2](https://crates.io/crates/tun2),
> please contact me in [issues](https://github.com/ssrlive/rust-tun/issues).
>
> For me, a submitted PR has not been reviewed for a long time,
> cannot be merged to the main branch, and cannot be published.
> It is like a patient who has not been sutured on the operating table for a long time.
> This is a bad experience.
> I believe that many people feel the same.
This crate allows the creation and usage of Tun/Tap interfaces, the aim is to make this cross-platform.


Usage
-----
First, add the following to your `Cargo.toml`:

```toml
[dependencies]
tun2 = "2"
tun2 = "3"
```

If you want to use the TUN interface with mio/tokio, you need to enable the `async` feature:

```toml
[dependencies]
tun2 = { version = "2", features = ["async"] }
tun2 = { version = "3", features = ["async"] }
```

Example
Expand All @@ -51,17 +39,11 @@ fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
.destination((10, 0, 0, 1))
.up();

#[cfg(target_os = "linux")]
config.platform_config(|config| {
// requiring root privilege to acquire complete functions
config.ensure_root_privileges(true);
});

let mut dev = tun2::create(&config)?;
let dev = tun2::create(&config)?;
let mut buf = [0; 4096];

loop {
let amount = dev.read(&mut buf)?;
let amount = dev.recv(&mut buf)?;
println!("{:?}", &buf[0..amount]);
}
}
Expand Down Expand Up @@ -123,9 +105,9 @@ pub extern "C" fn start_tun(fd: std::os::raw::c_int) {
cfg.platform_config(|p_cfg| {
p_cfg.packet_information(true);
});
let mut tun = tun2::create_as_async(&cfg).unwrap();
let mut framed = tun.into_framed();
while let Some(packet) = framed.next().await {
let tun = tun2::create_as_async(&cfg).unwrap();
let mut buf = [0u8;1500];
while let Ok(packet) = tun.recv(& mut buf).await {
...
}
});
Expand Down
39 changes: 17 additions & 22 deletions examples/dev-config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@
// TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
// 0. You just DO WHAT THE FUCK YOU WANT TO.

#[allow(unused_imports)]
use packet::{builder::Builder, icmp, ip, Packet};
use std::io::{Read, Write};
#[cfg(not(target_os = "windows"))]
use std::net::Ipv4Addr;
use std::sync::mpsc::Receiver;
#[allow(unused_imports)]
use tun2::{AbstractDevice, BoxError};

fn main() -> Result<(), BoxError> {
Expand All @@ -33,22 +31,25 @@ fn main() -> Result<(), BoxError> {
handle.join().unwrap();
Ok(())
}

#[cfg(any(target_os = "ios", target_os = "android",))]
fn main_entry(_quit: Receiver<()>) -> Result<(), BoxError> {
unimplemented!()
}
#[cfg(any(
target_os = "windows",
target_os = "linux",
target_os = "macos",
target_os = "freebsd",
))]
fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> {
let mut config = tun2::Configuration::default();

config
.address((10, 0, 0, 9))
.netmask((255, 255, 255, 0))
.address_with_prefix((10, 0, 0, 9), 24)
.destination((10, 0, 0, 1))
.up();

#[cfg(target_os = "linux")]
config.platform_config(|config| {
config.ensure_root_privileges(true);
});

let mut dev = tun2::create(&config)?;
let dev = tun2::create(&config)?;
let r = dev.address()?;
println!("{:?}", r);

Expand All @@ -57,13 +58,7 @@ fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> {

let r = dev.netmask()?;
println!("{:?}", r);

#[cfg(not(target_os = "windows"))]
{
dev.set_address(std::net::IpAddr::V4(Ipv4Addr::new(10, 0, 0, 20)))?;
dev.set_destination(std::net::IpAddr::V4(Ipv4Addr::new(10, 0, 0, 66)))?;
dev.set_netmask(std::net::IpAddr::V4(Ipv4Addr::new(255, 255, 0, 0)))?;
}
dev.set_network_address((10, 0, 0, 2), (255, 255, 255, 0), None)?;
dev.set_mtu(65535)?;

//dev.set_tun_name("tun8")?;
Expand All @@ -77,7 +72,7 @@ fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> {

std::thread::spawn(move || {
loop {
let amount = dev.read(&mut buf)?;
let amount = dev.recv(&mut buf)?;
let pkt = &buf[0..amount];
match ip::Packet::new(pkt) {
Ok(ip::Packet::V4(pkt)) => {
Expand All @@ -96,7 +91,7 @@ fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> {
.sequence(icmp.sequence())?
.payload(icmp.payload())?
.build()?;
let size = dev.write(&reply[..])?;
let size = dev.send(&reply[..])?;
println!("write {size} len {}", reply.len());
}
}
Expand Down
Loading

0 comments on commit 6746129

Please sign in to comment.