├── .cargo └── config.toml ├── .github ├── dependabot.yml └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── README.md ├── examples ├── dev-config.rs ├── ping-tun.rs ├── read-async-codec.rs ├── read-async.rs ├── read.rs ├── split.rs └── write.rs ├── flake.lock ├── flake.nix └── src ├── address.rs ├── async ├── codec.rs ├── mod.rs ├── unix_device.rs └── win_device.rs ├── configuration.rs ├── device.rs ├── error.rs ├── lib.rs ├── platform ├── android │ ├── device.rs │ └── mod.rs ├── freebsd │ ├── device.rs │ ├── mod.rs │ └── sys.rs ├── ios │ ├── device.rs │ └── mod.rs ├── linux │ ├── device.rs │ ├── mod.rs │ └── sys.rs ├── macos │ ├── device.rs │ ├── mod.rs │ └── sys.rs ├── mod.rs ├── posix │ ├── fd.rs │ ├── mod.rs │ ├── sockaddr.rs │ └── split.rs └── windows │ ├── device.rs │ └── mod.rs └── run_command.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [registries.crates-io] 2 | protocol = "sparse" 3 | 4 | [build] 5 | # target = ["x86_64-unknown-linux-musl"] 6 | # target = ["x86_64-unknown-linux-gnu"] 7 | # target = ["aarch64-linux-android"] 8 | # target = ["aarch64-apple-ios"] 9 | # target = ["x86_64-pc-windows-msvc"] 10 | # target = ["x86_64-apple-darwin"] 11 | # target = ["x86_64-unknown-freebsd"] 12 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | - package-ecosystem: "cargo" 8 | directory: "/" 9 | schedule: 10 | interval: "daily" 11 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Push or PR 2 | 3 | on: 4 | [push, pull_request] 5 | 6 | env: 7 | CARGO_TERM_COLOR: always 8 | 9 | jobs: 10 | build_n_test: 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | os: [ubuntu-latest, macos-latest, windows-latest] 15 | 16 | runs-on: ${{ matrix.os }} 17 | 18 | steps: 19 | - uses: actions/checkout@v4 20 | - name: rustfmt 21 | if: ${{ !cancelled() }} 22 | run: cargo fmt --all -- --check 23 | - name: check 24 | if: ${{ !cancelled() }} 25 | run: cargo check --verbose 26 | - name: clippy 27 | if: ${{ !cancelled() }} 28 | run: cargo clippy --all-targets --all-features -- -D warnings 29 | - name: Build 30 | if: ${{ !cancelled() }} 31 | run: | 32 | cargo build --verbose --examples --tests --all-features --features="async tokio/rt-multi-thread" 33 | cargo clean 34 | cargo build --verbose --examples --tests --no-default-features 35 | - name: Abort on error 36 | if: ${{ failure() }} 37 | run: echo "Some of jobs failed" && false 38 | 39 | build_n_test_android: 40 | strategy: 41 | fail-fast: false 42 | runs-on: ubuntu-latest 43 | 44 | steps: 45 | - uses: actions/checkout@v4 46 | - name: Install cargo ndk and rust compiler for android target 47 | if: ${{ !cancelled() }} 48 | run: | 49 | cargo install --locked cargo-ndk 50 | rustup target add x86_64-linux-android 51 | - name: clippy 52 | if: ${{ !cancelled() }} 53 | run: cargo ndk -t x86_64 clippy --all-features --features="async tokio/rt-multi-thread" -- -D warnings 54 | - name: Build 55 | if: ${{ !cancelled() }} 56 | run: | 57 | cargo ndk -t x86_64 rustc --verbose --all-features --features="async tokio/rt-multi-thread" --lib --crate-type=cdylib 58 | - name: Abort on error 59 | if: ${{ failure() }} 60 | run: echo "Android build job failed" && false 61 | 62 | build_n_test_ios: 63 | strategy: 64 | fail-fast: false 65 | runs-on: macos-latest 66 | 67 | steps: 68 | - uses: actions/checkout@v4 69 | - name: Install cargo lipo and rust compiler for ios target 70 | if: ${{ !cancelled() }} 71 | run: | 72 | cargo install --locked cargo-lipo 73 | rustup target add x86_64-apple-ios aarch64-apple-ios 74 | - name: clippy 75 | if: ${{ !cancelled() }} 76 | run: cargo clippy --target x86_64-apple-ios --all-features --features="async tokio/rt-multi-thread" -- -D warnings 77 | - name: Build 78 | if: ${{ !cancelled() }} 79 | run: | 80 | cargo lipo --verbose --all-features --features="async tokio/rt-multi-thread" 81 | - name: Abort on error 82 | if: ${{ failure() }} 83 | run: echo "iOs build job failed" && false 84 | 85 | semver: 86 | name: Check semver 87 | strategy: 88 | fail-fast: false 89 | matrix: 90 | os: [ubuntu-latest, macos-latest, windows-latest] 91 | runs-on: ${{ matrix.os }} 92 | steps: 93 | - uses: actions/checkout@v4 94 | - uses: dtolnay/rust-toolchain@stable 95 | - name: Check semver 96 | if: ${{ !cancelled() }} 97 | uses: obi1kenobi/cargo-semver-checks-action@v2 98 | - name: Abort on error 99 | if: ${{ failure() }} 100 | run: echo "Semver check failed" && false 101 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | .VSCodeCounter/ 3 | build/ 4 | tmp/ 5 | target/ 6 | **/*.rs.bk 7 | Cargo.lock 8 | wintun.dll 9 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tun2" 3 | version = "4.0.0" 4 | edition = "2021" 5 | authors = ["meh. ", "@ssrlive"] 6 | license = "WTFPL" 7 | description = "TUN device creation and handling." 8 | repository = "https://github.com/ssrlive/rust-tun" 9 | keywords = ["tun", "network", "tunnel", "bindings"] 10 | 11 | [lib] 12 | crate-type = ["staticlib", "cdylib", "lib"] 13 | 14 | [dependencies] 15 | bytes = { version = "1" } 16 | cfg-if = "1" 17 | futures-core = { version = "0.3", optional = true } 18 | libc = { version = "0.2", features = ["extra_traits"] } 19 | log = "0.4" 20 | thiserror = "1" 21 | tokio = { version = "1", features = [ 22 | "net", 23 | "macros", 24 | "io-util", 25 | ], optional = true } 26 | tokio-util = { version = "0.7", features = ["codec"], optional = true } 27 | 28 | [target.'cfg(unix)'.dependencies] 29 | nix = { version = "0.29", features = ["ioctl"] } 30 | 31 | [target.'cfg(target_os = "windows")'.dependencies] 32 | futures = { version = "0.3", optional = true } 33 | windows-sys = { version = "0.59", features = [ 34 | "Win32_Foundation", 35 | "Win32_Security", 36 | "Win32_Security_WinTrust", 37 | "Win32_Security_Cryptography", 38 | "Win32_System_Threading", 39 | "Win32_UI_WindowsAndMessaging", 40 | "Win32_System_LibraryLoader", 41 | ] } 42 | wintun-bindings = { version = "^0.7.7", features = [ 43 | "panic_on_unsent_packets", 44 | "verify_binary_signature", 45 | "async", 46 | ] } 47 | 48 | [target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies] 49 | ipnet = "2" 50 | 51 | [dev-dependencies] 52 | ctrlc2 = { version = "3", features = ["tokio", "termination"] } 53 | env_logger = "0.11" 54 | futures = "0.3" 55 | packet = "0.1" 56 | serde_json = "1" 57 | tokio = { version = "1", features = ["rt-multi-thread"] } 58 | 59 | [features] 60 | default = [] 61 | # default = ["async"] 62 | async = [ 63 | "tokio", 64 | "futures-core", 65 | "futures", 66 | "tokio-util", 67 | "wintun-bindings/async", 68 | ] 69 | 70 | [package.metadata.docs.rs] 71 | features = ["async"] 72 | 73 | [[example]] 74 | name = "read-async" 75 | required-features = ["async"] 76 | 77 | [[example]] 78 | name = "read-async-codec" 79 | required-features = ["async"] 80 | 81 | [[example]] 82 | name = "ping-tun" 83 | required-features = ["async"] 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | TUN interfaces 2 | ============== 3 | [![Crates.io](https://img.shields.io/crates/v/tun2.svg)](https://crates.io/crates/tun2) 4 | ![tun2](https://docs.rs/tun2/badge.svg) 5 | ![WTFPL](http://img.shields.io/badge/license-WTFPL-blue.svg) 6 | 7 | This crate allows the creation and usage of TUN interfaces, the aim is to make this cross-platform. 8 | 9 | Now that I (@ssrlive) am a co-contributor of the [tun](https://crates.io/crates/tun) crate, 10 | this crate is no longer maintained and all code is merged into the [tun](https://crates.io/crates/tun) crate. 11 | 12 | Usage 13 | ----- 14 | First, add the following to your `Cargo.toml`: 15 | 16 | ```toml 17 | [dependencies] 18 | tun2 = "4" 19 | ``` 20 | 21 | If you want to use the TUN interface with mio/tokio, you need to enable the `async` feature: 22 | 23 | ```toml 24 | [dependencies] 25 | tun2 = { version = "4", features = ["async"] } 26 | ``` 27 | 28 | Example 29 | ------- 30 | The following example creates and configures a TUN interface and starts reading 31 | packets from it. 32 | 33 | ```rust 34 | use std::io::Read; 35 | 36 | fn main() -> Result<(), Box> { 37 | let mut config = tun2::Configuration::default(); 38 | config 39 | .address((10, 0, 0, 9)) 40 | .netmask((255, 255, 255, 0)) 41 | .destination((10, 0, 0, 1)) 42 | .up(); 43 | 44 | #[cfg(target_os = "linux")] 45 | config.platform_config(|config| { 46 | // requiring root privilege to acquire complete functions 47 | config.ensure_root_privileges(true); 48 | }); 49 | 50 | let mut dev = tun2::create(&config)?; 51 | let mut buf = [0; 4096]; 52 | 53 | loop { 54 | let amount = dev.read(&mut buf)?; 55 | println!("{:?}", &buf[0..amount]); 56 | } 57 | } 58 | ``` 59 | 60 | Platforms 61 | ========= 62 | ## Supported Platforms 63 | 64 | - [x] Windows 65 | - [x] Linux 66 | - [x] macOS 67 | - [x] FreeBSD 68 | - [x] Android 69 | - [x] iOS 70 | 71 | 72 | Linux 73 | ----- 74 | You will need the `tun` module to be loaded and root is required to create 75 | interfaces. 76 | 77 | macOS & FreeBSD 78 | ----- 79 | `tun2` will automatically set up a route according to the provided configuration, which does a similar thing like this: 80 | > sudo route -n add -net 10.0.0.0/24 10.0.0.1 81 | 82 | 83 | iOS 84 | ---- 85 | You can pass the file descriptor of the TUN device to `tun2` to create the interface. 86 | 87 | Here is an example to create the TUN device on iOS and pass the `fd` to `tun2`: 88 | ```swift 89 | // Swift 90 | class PacketTunnelProvider: NEPacketTunnelProvider { 91 | override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { 92 | let tunnelNetworkSettings = createTunnelSettings() // Configure TUN address, DNS, mtu, routing... 93 | setTunnelNetworkSettings(tunnelNetworkSettings) { [weak self] error in 94 | // The tunnel of this tunFd is contains `Packet Information` prifix. 95 | let tunFd = self?.packetFlow.value(forKeyPath: "socket.fileDescriptor") as! Int32 96 | DispatchQueue.global(qos: .default).async { 97 | start_tun(tunFd) 98 | } 99 | completionHandler(nil) 100 | } 101 | } 102 | } 103 | ``` 104 | 105 | ```rust 106 | #[no_mangle] 107 | pub extern "C" fn start_tun(fd: std::os::raw::c_int) { 108 | let mut rt = tokio::runtime::Runtime::new().unwrap(); 109 | rt.block_on(async { 110 | let mut cfg = tun2::Configuration::default(); 111 | cfg.raw_fd(fd); 112 | #[cfg(target_os = "ios")] 113 | cfg.platform_config(|p_cfg| { 114 | p_cfg.packet_information(true); 115 | }); 116 | let mut tun = tun2::create_as_async(&cfg).unwrap(); 117 | let mut framed = tun.into_framed(); 118 | while let Some(packet) = framed.next().await { 119 | ... 120 | } 121 | }); 122 | } 123 | ``` 124 | 125 | Windows 126 | ----- 127 | You need to copy the [wintun.dll](https://wintun.net/) file which matches your architecture to 128 | the same directory as your executable and run your program as administrator. 129 | -------------------------------------------------------------------------------- /examples/dev-config.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use packet::{builder::Builder, icmp, ip, Packet}; 16 | use std::io::{Read, Write}; 17 | use std::{net::Ipv4Addr, sync::mpsc::Receiver}; 18 | use tun2::{AbstractDevice, BoxError}; 19 | 20 | fn main() -> Result<(), BoxError> { 21 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 22 | let (tx, rx) = std::sync::mpsc::channel(); 23 | 24 | let handle = ctrlc2::set_handler(move || { 25 | tx.send(()).expect("Signal error."); 26 | true 27 | }) 28 | .expect("Error setting Ctrl-C handler"); 29 | 30 | main_entry(rx)?; 31 | handle.join().unwrap(); 32 | Ok(()) 33 | } 34 | 35 | fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> { 36 | let mut config = tun2::Configuration::default(); 37 | 38 | config 39 | .address((10, 0, 0, 9)) 40 | .netmask((255, 255, 255, 0)) 41 | .destination((10, 0, 0, 1)) 42 | .up(); 43 | 44 | #[cfg(target_os = "linux")] 45 | config.platform_config(|config| { 46 | config.ensure_root_privileges(true); 47 | }); 48 | 49 | let mut dev = tun2::create(&config)?; 50 | 51 | let r = dev.tun_index()?; 52 | println!("Index: {:?}", r); 53 | 54 | let r = dev.address()?; 55 | println!("Address: {:?}", r); 56 | 57 | let r = dev.destination()?; 58 | println!("Destination: {:?}", r); 59 | 60 | let r = dev.netmask()?; 61 | println!("Netmask: {:?}", r); 62 | 63 | dev.set_address(std::net::IpAddr::V4(Ipv4Addr::new(10, 0, 0, 20)))?; 64 | dev.set_destination(std::net::IpAddr::V4(Ipv4Addr::new(10, 0, 0, 66)))?; 65 | dev.set_netmask(std::net::IpAddr::V4(Ipv4Addr::new(255, 255, 0, 0)))?; 66 | dev.set_mtu(65535)?; 67 | 68 | //dev.set_tun_name("tun8")?; 69 | 70 | //dev.set_address(std::net::IpAddr::V4(Ipv4Addr::new(10, 0, 0, 21)))?; 71 | 72 | // let r = dev.broadcast()?; 73 | // println!("{:?}",r); 74 | 75 | let mut buf = [0; 4096]; 76 | 77 | std::thread::spawn(move || { 78 | loop { 79 | let amount = dev.read(&mut buf)?; 80 | let pkt = &buf[0..amount]; 81 | match ip::Packet::new(pkt) { 82 | Ok(ip::Packet::V4(pkt)) => { 83 | if let Ok(icmp) = icmp::Packet::new(pkt.payload()) { 84 | if let Ok(icmp) = icmp.echo() { 85 | println!("{:?} - {:?}", icmp.sequence(), pkt.destination()); 86 | let reply = ip::v4::Builder::default() 87 | .id(0x42)? 88 | .ttl(64)? 89 | .source(pkt.destination())? 90 | .destination(pkt.source())? 91 | .icmp()? 92 | .echo()? 93 | .reply()? 94 | .identifier(icmp.identifier())? 95 | .sequence(icmp.sequence())? 96 | .payload(icmp.payload())? 97 | .build()?; 98 | let size = dev.write(&reply[..])?; 99 | println!("write {size} len {}", reply.len()); 100 | } 101 | } 102 | } 103 | Err(err) => println!("Received an invalid packet: {:?}", err), 104 | _ => {} 105 | } 106 | } 107 | #[allow(unreachable_code)] 108 | Ok::<(), BoxError>(()) 109 | }); 110 | 111 | quit.recv().expect("Quit error."); 112 | Ok(()) 113 | } 114 | -------------------------------------------------------------------------------- /examples/ping-tun.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use futures::{SinkExt, StreamExt}; 16 | use packet::{builder::Builder, icmp, ip, Packet}; 17 | use tokio::sync::mpsc::Receiver; 18 | use tun2::{self, BoxError, Configuration}; 19 | 20 | #[tokio::main] 21 | async fn main() -> Result<(), BoxError> { 22 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 23 | let (tx, rx) = tokio::sync::mpsc::channel::<()>(1); 24 | 25 | ctrlc2::set_async_handler(async move { 26 | tx.send(()).await.expect("Signal error"); 27 | }) 28 | .await; 29 | 30 | main_entry(rx).await?; 31 | Ok(()) 32 | } 33 | 34 | async fn main_entry(mut quit: Receiver<()>) -> Result<(), BoxError> { 35 | let mut config = Configuration::default(); 36 | 37 | config 38 | .address((10, 0, 0, 9)) 39 | .netmask((255, 255, 255, 0)) 40 | .destination((10, 0, 0, 1)) 41 | .up(); 42 | 43 | #[cfg(target_os = "linux")] 44 | config.platform_config(|config| { 45 | #[allow(deprecated)] 46 | config.packet_information(true); 47 | config.ensure_root_privileges(true); 48 | }); 49 | 50 | #[cfg(target_os = "windows")] 51 | config.platform_config(|config| { 52 | config.device_guid(9099482345783245345345_u128); 53 | }); 54 | 55 | let dev = tun2::create_as_async(&config)?; 56 | 57 | let mut framed = dev.into_framed(); 58 | 59 | loop { 60 | tokio::select! { 61 | _ = quit.recv() => { 62 | println!("Quit..."); 63 | break; 64 | } 65 | Some(packet) = framed.next() => { 66 | let pkt: Vec = packet?; 67 | match ip::Packet::new(pkt) { 68 | Ok(ip::Packet::V4(pkt)) => { 69 | if let Ok(icmp) = icmp::Packet::new(pkt.payload()) { 70 | if let Ok(icmp) = icmp.echo() { 71 | println!("{:?} - {:?}", icmp.sequence(), pkt.destination()); 72 | let reply = ip::v4::Builder::default() 73 | .id(0x42)? 74 | .ttl(64)? 75 | .source(pkt.destination())? 76 | .destination(pkt.source())? 77 | .icmp()? 78 | .echo()? 79 | .reply()? 80 | .identifier(icmp.identifier())? 81 | .sequence(icmp.sequence())? 82 | .payload(icmp.payload())? 83 | .build()?; 84 | framed.send(reply).await?; 85 | } 86 | } 87 | } 88 | Err(err) => println!("Received an invalid packet: {:?}", err), 89 | _ => {} 90 | } 91 | } 92 | } 93 | } 94 | Ok(()) 95 | } 96 | -------------------------------------------------------------------------------- /examples/read-async-codec.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use bytes::BytesMut; 16 | use futures::StreamExt; 17 | use packet::{ip::Packet, Error}; 18 | use tokio::sync::mpsc::Receiver; 19 | use tokio_util::codec::{Decoder, FramedRead}; 20 | use tun2::BoxError; 21 | 22 | pub struct IPPacketCodec; 23 | 24 | impl Decoder for IPPacketCodec { 25 | type Item = Packet; 26 | type Error = Error; 27 | 28 | fn decode(&mut self, buf: &mut BytesMut) -> Result, Self::Error> { 29 | if buf.is_empty() { 30 | return Ok(None); 31 | } 32 | 33 | let buf = buf.split_to(buf.len()); 34 | Ok(match Packet::no_payload(buf) { 35 | Ok(pkt) => Some(pkt), 36 | Err(err) => { 37 | println!("error {:?}", err); 38 | None 39 | } 40 | }) 41 | } 42 | } 43 | 44 | #[tokio::main] 45 | async fn main() -> Result<(), BoxError> { 46 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 47 | let (tx, rx) = tokio::sync::mpsc::channel::<()>(1); 48 | 49 | ctrlc2::set_async_handler(async move { 50 | tx.send(()).await.expect("Signal error"); 51 | }) 52 | .await; 53 | 54 | main_entry(rx).await?; 55 | Ok(()) 56 | } 57 | 58 | async fn main_entry(mut quit: Receiver<()>) -> Result<(), BoxError> { 59 | let mut config = tun2::Configuration::default(); 60 | 61 | config 62 | .address((10, 0, 0, 9)) 63 | .netmask((255, 255, 255, 0)) 64 | .destination((10, 0, 0, 1)) 65 | .up(); 66 | 67 | #[cfg(target_os = "linux")] 68 | config.platform_config(|config| { 69 | #[allow(deprecated)] 70 | config.packet_information(true); 71 | config.ensure_root_privileges(true); 72 | }); 73 | 74 | #[cfg(target_os = "windows")] 75 | config.platform_config(|config| { 76 | config.device_guid(9099482345783245345345_u128); 77 | }); 78 | 79 | let dev = tun2::create_as_async(&config)?; 80 | 81 | let mut stream = FramedRead::new(dev, IPPacketCodec); 82 | 83 | loop { 84 | tokio::select! { 85 | _ = quit.recv() => { 86 | println!("Quit..."); 87 | break; 88 | } 89 | Some(packet) = stream.next() => { 90 | match packet { 91 | Ok(pkt) => println!("pkt: {:#?}", pkt), 92 | Err(err) => panic!("Error: {:?}", err), 93 | } 94 | } 95 | }; 96 | } 97 | Ok(()) 98 | } 99 | -------------------------------------------------------------------------------- /examples/read-async.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use tokio::io::AsyncReadExt; 16 | use tokio::sync::mpsc::Receiver; 17 | use tun2::{AbstractDevice, BoxError}; 18 | 19 | #[tokio::main] 20 | async fn main() -> Result<(), BoxError> { 21 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 22 | let (tx, rx) = tokio::sync::mpsc::channel::<()>(1); 23 | 24 | ctrlc2::set_async_handler(async move { 25 | tx.send(()).await.expect("Signal error"); 26 | }) 27 | .await; 28 | 29 | main_entry(rx).await?; 30 | Ok(()) 31 | } 32 | 33 | async fn main_entry(mut quit: Receiver<()>) -> Result<(), BoxError> { 34 | let mut config = tun2::Configuration::default(); 35 | 36 | config 37 | .address((10, 0, 0, 9)) 38 | .netmask((255, 255, 255, 0)) 39 | .destination((10, 0, 0, 1)) 40 | .mtu(tun2::DEFAULT_MTU) 41 | .up(); 42 | 43 | #[cfg(target_os = "linux")] 44 | config.platform_config(|config| { 45 | config.ensure_root_privileges(true); 46 | }); 47 | 48 | let mut dev = tun2::create_as_async(&config)?; 49 | let size = dev.mtu()? as usize + tun2::PACKET_INFORMATION_LENGTH; 50 | let mut buf = vec![0; size]; 51 | loop { 52 | tokio::select! { 53 | _ = quit.recv() => { 54 | println!("Quit..."); 55 | break; 56 | } 57 | len = dev.read(&mut buf) => { 58 | println!("pkt: {:?}", &buf[..len?]); 59 | } 60 | }; 61 | } 62 | Ok(()) 63 | } 64 | -------------------------------------------------------------------------------- /examples/read.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use std::io::Read; 16 | use std::sync::mpsc::Receiver; 17 | use tun2::BoxError; 18 | 19 | fn main() -> Result<(), BoxError> { 20 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 21 | let (tx, rx) = std::sync::mpsc::channel(); 22 | 23 | let handle = ctrlc2::set_handler(move || { 24 | tx.send(()).expect("Signal error."); 25 | true 26 | }) 27 | .expect("Error setting Ctrl-C handler"); 28 | 29 | main_entry(rx)?; 30 | handle.join().unwrap(); 31 | Ok(()) 32 | } 33 | 34 | fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> { 35 | let mut config = tun2::Configuration::default(); 36 | 37 | config 38 | .address((10, 0, 0, 9)) 39 | .netmask((255, 255, 255, 0)) 40 | .destination((10, 0, 0, 1)) 41 | .up(); 42 | 43 | #[cfg(target_os = "linux")] 44 | config.platform_config(|config| { 45 | config.ensure_root_privileges(true); 46 | }); 47 | 48 | let mut dev = tun2::create(&config)?; 49 | std::thread::spawn(move || { 50 | let mut buf = [0; 4096]; 51 | loop { 52 | let amount = dev.read(&mut buf)?; 53 | println!("{:?}", &buf[0..amount]); 54 | } 55 | #[allow(unreachable_code)] 56 | Ok::<(), BoxError>(()) 57 | }); 58 | quit.recv().expect("Quit error."); 59 | Ok(()) 60 | } 61 | -------------------------------------------------------------------------------- /examples/split.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use packet::{builder::Builder, icmp, ip, Packet}; 16 | use std::io::{Read, Write}; 17 | use std::sync::mpsc::Receiver; 18 | use tun2::BoxError; 19 | 20 | fn main() -> Result<(), BoxError> { 21 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 22 | let (tx, rx) = std::sync::mpsc::channel(); 23 | 24 | let handle = ctrlc2::set_handler(move || { 25 | tx.send(()).expect("Signal error."); 26 | true 27 | }) 28 | .expect("Error setting Ctrl-C handler"); 29 | 30 | main_entry(rx)?; 31 | handle.join().unwrap(); 32 | Ok(()) 33 | } 34 | 35 | fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> { 36 | let mut config = tun2::Configuration::default(); 37 | 38 | config 39 | .address((10, 0, 0, 9)) 40 | .netmask((255, 255, 255, 0)) 41 | .destination((10, 0, 0, 1)) 42 | .up(); 43 | 44 | #[cfg(target_os = "linux")] 45 | config.platform_config(|config| { 46 | config.ensure_root_privileges(true); 47 | }); 48 | 49 | let dev = tun2::create(&config)?; 50 | let (mut reader, mut writer) = dev.split(); 51 | 52 | let (tx, rx) = std::sync::mpsc::channel(); 53 | 54 | let _t1 = std::thread::spawn(move || { 55 | let mut buf = [0; 4096]; 56 | loop { 57 | let size = reader.read(&mut buf)?; 58 | let pkt = &buf[..size]; 59 | use std::io::{Error, ErrorKind::Other}; 60 | tx.send(pkt.to_vec()).map_err(|e| Error::new(Other, e))?; 61 | } 62 | #[allow(unreachable_code)] 63 | Ok::<(), std::io::Error>(()) 64 | }); 65 | 66 | let _t2 = std::thread::spawn(move || { 67 | loop { 68 | if let Ok(pkt) = rx.recv() { 69 | match ip::Packet::new(pkt.as_slice()) { 70 | Ok(ip::Packet::V4(pkt)) => { 71 | if let Ok(icmp) = icmp::Packet::new(pkt.payload()) { 72 | if let Ok(icmp) = icmp.echo() { 73 | println!("{:?} - {:?}", icmp.sequence(), pkt.destination()); 74 | let reply = ip::v4::Builder::default() 75 | .id(0x42)? 76 | .ttl(64)? 77 | .source(pkt.destination())? 78 | .destination(pkt.source())? 79 | .icmp()? 80 | .echo()? 81 | .reply()? 82 | .identifier(icmp.identifier())? 83 | .sequence(icmp.sequence())? 84 | .payload(icmp.payload())? 85 | .build()?; 86 | writer.write_all(&reply[..])?; 87 | } 88 | } 89 | } 90 | Err(err) => println!("Received an invalid packet: {:?}", err), 91 | _ => { 92 | println!("receive pkt {:?}", pkt); 93 | } 94 | } 95 | } 96 | } 97 | #[allow(unreachable_code)] 98 | Ok::<(), packet::Error>(()) 99 | }); 100 | quit.recv().expect("Quit error."); 101 | Ok(()) 102 | } 103 | -------------------------------------------------------------------------------- /examples/write.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use packet::{builder::Builder, icmp, ip, Packet}; 16 | use std::io::{Read, Write}; 17 | use std::sync::mpsc::Receiver; 18 | use tun2::BoxError; 19 | 20 | fn main() -> Result<(), BoxError> { 21 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 22 | let (tx, rx) = std::sync::mpsc::channel(); 23 | 24 | let handle = ctrlc2::set_handler(move || { 25 | tx.send(()).expect("Signal error."); 26 | true 27 | }) 28 | .expect("Error setting Ctrl-C handler"); 29 | 30 | main_entry(rx)?; 31 | handle.join().unwrap(); 32 | Ok(()) 33 | } 34 | 35 | fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> { 36 | let mut config = tun2::Configuration::default(); 37 | 38 | config 39 | .address((10, 0, 0, 9)) 40 | .netmask((255, 255, 255, 0)) 41 | .destination((10, 0, 0, 1)) 42 | .up(); 43 | 44 | #[cfg(target_os = "linux")] 45 | config.platform_config(|config| { 46 | config.ensure_root_privileges(true); 47 | }); 48 | 49 | let mut dev = tun2::create(&config)?; 50 | let mut buf = [0; 4096]; 51 | 52 | std::thread::spawn(move || { 53 | loop { 54 | let amount = dev.read(&mut buf)?; 55 | let pkt = &buf[0..amount]; 56 | match ip::Packet::new(pkt) { 57 | Ok(ip::Packet::V4(pkt)) => { 58 | if let Ok(icmp) = icmp::Packet::new(pkt.payload()) { 59 | if let Ok(icmp) = icmp.echo() { 60 | println!("{:?} - {:?}", icmp.sequence(), pkt.destination()); 61 | let reply = ip::v4::Builder::default() 62 | .id(0x42)? 63 | .ttl(64)? 64 | .source(pkt.destination())? 65 | .destination(pkt.source())? 66 | .icmp()? 67 | .echo()? 68 | .reply()? 69 | .identifier(icmp.identifier())? 70 | .sequence(icmp.sequence())? 71 | .payload(icmp.payload())? 72 | .build()?; 73 | let size = dev.write(&reply[..])?; 74 | println!("write {size} len {}", reply.len()); 75 | } 76 | } 77 | } 78 | Err(err) => println!("Received an invalid packet: {:?}", err), 79 | _ => {} 80 | } 81 | } 82 | #[allow(unreachable_code)] 83 | Ok::<(), BoxError>(()) 84 | }); 85 | quit.recv().expect("Quit error."); 86 | Ok(()) 87 | } 88 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "fenix": { 4 | "inputs": { 5 | "nixpkgs": [ 6 | "nixpkgs" 7 | ], 8 | "rust-analyzer-src": "rust-analyzer-src" 9 | }, 10 | "locked": { 11 | "lastModified": 1629858211, 12 | "narHash": "sha256-YyQvCmRekZ5QGN9RObUZWg6Pqmi5+idTZ5Ew1Ct5tEk=", 13 | "owner": "nix-community", 14 | "repo": "fenix", 15 | "rev": "495510be4bc7ccf03b54ff4226fcc7b01fcf62ee", 16 | "type": "github" 17 | }, 18 | "original": { 19 | "owner": "nix-community", 20 | "repo": "fenix", 21 | "type": "github" 22 | } 23 | }, 24 | "nixpkgs": { 25 | "locked": { 26 | "lastModified": 1629827819, 27 | "narHash": "sha256-cysfDbdjTluO+UtuT6iRrf/2Lt7Qo/qRlpz9F5rz3Sc=", 28 | "owner": "NixOS", 29 | "repo": "nixpkgs", 30 | "rev": "503209808cd613daed238e21e7a18ffcbeacebe3", 31 | "type": "github" 32 | }, 33 | "original": { 34 | "owner": "NixOS", 35 | "ref": "nixpkgs-unstable", 36 | "repo": "nixpkgs", 37 | "type": "github" 38 | } 39 | }, 40 | "root": { 41 | "inputs": { 42 | "fenix": "fenix", 43 | "nixpkgs": "nixpkgs", 44 | "utils": "utils" 45 | } 46 | }, 47 | "rust-analyzer-src": { 48 | "flake": false, 49 | "locked": { 50 | "lastModified": 1629817082, 51 | "narHash": "sha256-qdKZss+bNccS8FJsKbkVGZGISiAGlQ/Se1PFlcroVEk=", 52 | "owner": "rust-analyzer", 53 | "repo": "rust-analyzer", 54 | "rev": "ce4670f299d72a0f23f347b5df9790aca72da617", 55 | "type": "github" 56 | }, 57 | "original": { 58 | "owner": "rust-analyzer", 59 | "ref": "nightly", 60 | "repo": "rust-analyzer", 61 | "type": "github" 62 | } 63 | }, 64 | "utils": { 65 | "locked": { 66 | "lastModified": 1629481132, 67 | "narHash": "sha256-JHgasjPR0/J1J3DRm4KxM4zTyAj4IOJY8vIl75v/kPI=", 68 | "owner": "numtide", 69 | "repo": "flake-utils", 70 | "rev": "997f7efcb746a9c140ce1f13c72263189225f482", 71 | "type": "github" 72 | }, 73 | "original": { 74 | "owner": "numtide", 75 | "repo": "flake-utils", 76 | "type": "github" 77 | } 78 | } 79 | }, 80 | "root": "root", 81 | "version": 7 82 | } 83 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | inputs = { 3 | nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; 4 | utils.url = "github:numtide/flake-utils"; 5 | fenix = { 6 | url = "github:nix-community/fenix"; 7 | inputs.nixpkgs.follows = "nixpkgs"; 8 | }; 9 | }; 10 | 11 | outputs = { self, utils, nixpkgs, fenix, }: utils.lib.eachDefaultSystem (system: let 12 | pkgs = nixpkgs.legacyPackages.${system}; 13 | rust = fenix.packages.${system}; 14 | lib = pkgs.lib; 15 | in { 16 | devShell = pkgs.mkShell { 17 | buildInputs = with pkgs; with llvmPackages; [ 18 | # For building. 19 | clang rust.stable.toolchain pkg-config openssl libsodium libclang.lib 20 | ]; 21 | 22 | LIBCLANG_PATH = "${pkgs.llvmPackages.libclang.lib}/lib"; 23 | RUST_BACKTRACE = 1; 24 | # RUST_LOG = "info,sqlx::query=warn"; 25 | RUSTFLAGS = "-C target-cpu=native"; 26 | }; 27 | }); 28 | } 29 | -------------------------------------------------------------------------------- /src/address.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use crate::error::{Error, Result}; 16 | use std::net::{IpAddr, Ipv4Addr}; 17 | use std::net::{SocketAddr, SocketAddrV4}; 18 | 19 | /// Helper trait to convert things into IPv4 addresses. 20 | pub trait ToAddress { 21 | /// Convert the type to an `Ipv4Addr`. 22 | fn to_address(&self) -> Result; 23 | } 24 | 25 | impl ToAddress for u32 { 26 | fn to_address(&self) -> Result { 27 | Ok(IpAddr::V4(Ipv4Addr::new( 28 | ((*self) & 0xff) as u8, 29 | ((*self >> 8) & 0xff) as u8, 30 | ((*self >> 16) & 0xff) as u8, 31 | ((*self >> 24) & 0xff) as u8, 32 | ))) 33 | } 34 | } 35 | 36 | impl ToAddress for i32 { 37 | fn to_address(&self) -> Result { 38 | (*self as u32).to_address() 39 | } 40 | } 41 | 42 | impl ToAddress for (u8, u8, u8, u8) { 43 | fn to_address(&self) -> Result { 44 | Ok(IpAddr::V4(Ipv4Addr::new(self.0, self.1, self.2, self.3))) 45 | } 46 | } 47 | 48 | impl ToAddress for str { 49 | fn to_address(&self) -> Result { 50 | self.parse().map_err(|_| Error::InvalidAddress) 51 | } 52 | } 53 | 54 | impl<'a> ToAddress for &'a str { 55 | fn to_address(&self) -> Result { 56 | (*self).to_address() 57 | } 58 | } 59 | 60 | impl ToAddress for String { 61 | fn to_address(&self) -> Result { 62 | self.as_str().to_address() 63 | } 64 | } 65 | 66 | impl<'a> ToAddress for &'a String { 67 | fn to_address(&self) -> Result { 68 | self.as_str().to_address() 69 | } 70 | } 71 | 72 | impl ToAddress for Ipv4Addr { 73 | fn to_address(&self) -> Result { 74 | Ok(IpAddr::V4(*self)) 75 | } 76 | } 77 | 78 | impl<'a> ToAddress for &'a Ipv4Addr { 79 | fn to_address(&self) -> Result { 80 | (*self).to_address() 81 | } 82 | } 83 | 84 | impl ToAddress for IpAddr { 85 | fn to_address(&self) -> Result { 86 | Ok(*self) 87 | } 88 | } 89 | 90 | impl<'a> ToAddress for &'a IpAddr { 91 | fn to_address(&self) -> Result { 92 | (*self).to_address() 93 | } 94 | } 95 | 96 | impl ToAddress for SocketAddrV4 { 97 | fn to_address(&self) -> Result { 98 | Ok(IpAddr::V4(*self.ip())) 99 | } 100 | } 101 | 102 | impl<'a> ToAddress for &'a SocketAddrV4 { 103 | fn to_address(&self) -> Result { 104 | (*self).to_address() 105 | } 106 | } 107 | 108 | impl ToAddress for SocketAddr { 109 | fn to_address(&self) -> Result { 110 | Ok(self.ip()) 111 | } 112 | } 113 | 114 | impl<'a> ToAddress for &'a SocketAddr { 115 | fn to_address(&self) -> Result { 116 | (*self).to_address() 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/async/codec.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | use bytes::{BufMut, BytesMut}; 15 | use tokio_util::codec::{Decoder, Encoder}; 16 | 17 | /// A TUN packet Encoder/Decoder. 18 | #[derive(Debug, Default)] 19 | pub struct TunPacketCodec(usize); 20 | 21 | impl TunPacketCodec { 22 | /// Create a new `TunPacketCodec` specifying whether the underlying 23 | /// tunnel Device has enabled the packet information header. 24 | pub fn new(mtu: usize) -> TunPacketCodec { 25 | TunPacketCodec(mtu) 26 | } 27 | } 28 | 29 | impl Decoder for TunPacketCodec { 30 | type Item = Vec; 31 | type Error = std::io::Error; 32 | 33 | fn decode(&mut self, buf: &mut BytesMut) -> Result, Self::Error> { 34 | if buf.is_empty() { 35 | return Ok(None); 36 | } 37 | let pkt = buf.split_to(buf.len()); 38 | //reserve enough space for the next packet 39 | buf.reserve(self.0); 40 | Ok(Some(pkt.freeze().to_vec())) 41 | } 42 | } 43 | 44 | impl Encoder> for TunPacketCodec { 45 | type Error = std::io::Error; 46 | 47 | fn encode(&mut self, item: Vec, dst: &mut BytesMut) -> Result<(), Self::Error> { 48 | let bytes = item.as_slice(); 49 | dst.reserve(bytes.len()); 50 | dst.put(bytes); 51 | Ok(()) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/async/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Async specific modules. 16 | 17 | use crate::error; 18 | 19 | use crate::configuration::Configuration; 20 | use crate::platform::create; 21 | 22 | mod codec; 23 | pub use codec::TunPacketCodec; 24 | 25 | #[cfg(unix)] 26 | mod unix_device; 27 | #[cfg(unix)] 28 | pub use unix_device::{AsyncDevice, DeviceReader, DeviceWriter}; 29 | 30 | #[cfg(target_os = "windows")] 31 | mod win_device; 32 | #[cfg(target_os = "windows")] 33 | pub use win_device::{AsyncDevice, DeviceReader, DeviceWriter}; 34 | 35 | /// Create a TUN device with the given name. 36 | pub fn create_as_async(configuration: &Configuration) -> Result { 37 | let device = create(configuration)?; 38 | AsyncDevice::new(device).map_err(|err| err.into()) 39 | } 40 | -------------------------------------------------------------------------------- /src/async/unix_device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use core::pin::Pin; 16 | use core::task::{Context, Poll}; 17 | use futures_core::ready; 18 | use std::io::{IoSlice, Read, Write}; 19 | use tokio::io::unix::AsyncFd; 20 | use tokio::io::Interest; 21 | use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; 22 | use tokio_util::codec::Framed; 23 | 24 | use super::TunPacketCodec; 25 | use crate::device::AbstractDevice; 26 | use crate::platform::posix::{Reader, Writer}; 27 | use crate::platform::Device; 28 | 29 | /// An async TUN device wrapper around a TUN device. 30 | pub struct AsyncDevice { 31 | inner: AsyncFd, 32 | } 33 | 34 | /// Returns a shared reference to the underlying Device object. 35 | impl core::ops::Deref for AsyncDevice { 36 | type Target = Device; 37 | 38 | fn deref(&self) -> &Self::Target { 39 | self.inner.get_ref() 40 | } 41 | } 42 | 43 | /// Returns a mutable reference to the underlying Device object. 44 | impl core::ops::DerefMut for AsyncDevice { 45 | fn deref_mut(&mut self) -> &mut Self::Target { 46 | self.inner.get_mut() 47 | } 48 | } 49 | 50 | impl AsyncDevice { 51 | /// Create a new `AsyncDevice` wrapping around a `Device`. 52 | pub fn new(device: Device) -> std::io::Result { 53 | device.set_nonblock()?; 54 | Ok(AsyncDevice { 55 | inner: AsyncFd::new(device)?, 56 | }) 57 | } 58 | 59 | /// Consumes this AsyncDevice and return a Framed object (unified Stream and Sink interface) 60 | pub fn into_framed(self) -> Framed { 61 | let mtu = self.mtu().unwrap_or(crate::DEFAULT_MTU); 62 | let codec = TunPacketCodec::new(mtu as usize); 63 | // associate mtu with the capacity of ReadBuf 64 | Framed::with_capacity(self, codec, mtu as usize) 65 | } 66 | pub fn split(self) -> std::io::Result<(DeviceWriter, DeviceReader)> { 67 | let device = self.inner.into_inner(); 68 | let (reader, writer) = device.split(); 69 | Ok((DeviceWriter::new(writer)?, DeviceReader::new(reader)?)) 70 | } 71 | 72 | /// Recv a packet from tun device 73 | pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result { 74 | let guard = self.inner.readable().await?; 75 | guard 76 | .get_ref() 77 | .async_io(Interest::READABLE, |inner| inner.recv(buf)) 78 | .await 79 | } 80 | 81 | /// Send a packet to tun device 82 | pub async fn send(&self, buf: &[u8]) -> std::io::Result { 83 | let guard = self.inner.writable().await?; 84 | guard 85 | .get_ref() 86 | .async_io(Interest::WRITABLE, |inner| inner.send(buf)) 87 | .await 88 | } 89 | } 90 | 91 | impl AsyncRead for AsyncDevice { 92 | fn poll_read( 93 | mut self: Pin<&mut Self>, 94 | cx: &mut Context<'_>, 95 | buf: &mut ReadBuf, 96 | ) -> Poll> { 97 | loop { 98 | let mut guard = ready!(self.inner.poll_read_ready_mut(cx))?; 99 | let rbuf = buf.initialize_unfilled(); 100 | match guard.try_io(|inner| inner.get_mut().read(rbuf)) { 101 | Ok(res) => return Poll::Ready(res.map(|n| buf.advance(n))), 102 | Err(_wb) => continue, 103 | } 104 | } 105 | } 106 | } 107 | 108 | impl AsyncWrite for AsyncDevice { 109 | fn poll_write( 110 | mut self: Pin<&mut Self>, 111 | cx: &mut Context<'_>, 112 | buf: &[u8], 113 | ) -> Poll> { 114 | loop { 115 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 116 | match guard.try_io(|inner| inner.get_mut().write(buf)) { 117 | Ok(res) => return Poll::Ready(res), 118 | Err(_wb) => continue, 119 | } 120 | } 121 | } 122 | 123 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 124 | loop { 125 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 126 | match guard.try_io(|inner| inner.get_mut().flush()) { 127 | Ok(res) => return Poll::Ready(res), 128 | Err(_wb) => continue, 129 | } 130 | } 131 | } 132 | 133 | fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 134 | Poll::Ready(Ok(())) 135 | } 136 | 137 | fn poll_write_vectored( 138 | mut self: Pin<&mut Self>, 139 | cx: &mut Context<'_>, 140 | bufs: &[IoSlice<'_>], 141 | ) -> Poll> { 142 | loop { 143 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 144 | match guard.try_io(|inner| inner.get_mut().write_vectored(bufs)) { 145 | Ok(res) => return Poll::Ready(res), 146 | Err(_wb) => continue, 147 | } 148 | } 149 | } 150 | 151 | fn is_write_vectored(&self) -> bool { 152 | true 153 | } 154 | } 155 | pub struct DeviceReader { 156 | inner: AsyncFd, 157 | } 158 | impl DeviceReader { 159 | fn new(reader: Reader) -> std::io::Result { 160 | Ok(Self { 161 | inner: AsyncFd::new(reader)?, 162 | }) 163 | } 164 | } 165 | impl AsyncRead for DeviceReader { 166 | fn poll_read( 167 | mut self: Pin<&mut Self>, 168 | cx: &mut Context<'_>, 169 | buf: &mut ReadBuf, 170 | ) -> Poll> { 171 | loop { 172 | let mut guard = ready!(self.inner.poll_read_ready_mut(cx))?; 173 | let rbuf = buf.initialize_unfilled(); 174 | match guard.try_io(|inner| inner.get_mut().read(rbuf)) { 175 | Ok(res) => return Poll::Ready(res.map(|n| buf.advance(n))), 176 | Err(_wb) => continue, 177 | } 178 | } 179 | } 180 | } 181 | 182 | pub struct DeviceWriter { 183 | inner: AsyncFd, 184 | } 185 | impl DeviceWriter { 186 | fn new(writer: Writer) -> std::io::Result { 187 | Ok(Self { 188 | inner: AsyncFd::new(writer)?, 189 | }) 190 | } 191 | } 192 | 193 | impl AsyncWrite for DeviceWriter { 194 | fn poll_write( 195 | mut self: Pin<&mut Self>, 196 | cx: &mut Context<'_>, 197 | buf: &[u8], 198 | ) -> Poll> { 199 | loop { 200 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 201 | match guard.try_io(|inner| inner.get_mut().write(buf)) { 202 | Ok(res) => return Poll::Ready(res), 203 | Err(_wb) => continue, 204 | } 205 | } 206 | } 207 | 208 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 209 | loop { 210 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 211 | match guard.try_io(|inner| inner.get_mut().flush()) { 212 | Ok(res) => return Poll::Ready(res), 213 | Err(_wb) => continue, 214 | } 215 | } 216 | } 217 | 218 | fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 219 | Poll::Ready(Ok(())) 220 | } 221 | 222 | fn poll_write_vectored( 223 | mut self: Pin<&mut Self>, 224 | cx: &mut Context<'_>, 225 | bufs: &[IoSlice<'_>], 226 | ) -> Poll> { 227 | loop { 228 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 229 | match guard.try_io(|inner| inner.get_mut().write_vectored(bufs)) { 230 | Ok(res) => return Poll::Ready(res), 231 | Err(_wb) => continue, 232 | } 233 | } 234 | } 235 | 236 | fn is_write_vectored(&self) -> bool { 237 | true 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /src/async/win_device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use super::TunPacketCodec; 16 | use crate::device::AbstractDevice; 17 | use crate::platform::windows::Driver; 18 | use crate::platform::Device; 19 | use core::pin::Pin; 20 | use core::task::{Context, Poll}; 21 | use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; 22 | use tokio_util::codec::Framed; 23 | use wintun_bindings::AsyncSession; 24 | 25 | /// An async TUN device wrapper around a TUN device. 26 | pub struct AsyncDevice { 27 | inner: Device, 28 | session_reader: DeviceReader, 29 | session_writer: DeviceWriter, 30 | } 31 | 32 | /// Returns a shared reference to the underlying Device object. 33 | impl core::ops::Deref for AsyncDevice { 34 | type Target = Device; 35 | 36 | fn deref(&self) -> &Self::Target { 37 | &self.inner 38 | } 39 | } 40 | 41 | /// Returns a mutable reference to the underlying Device object. 42 | impl core::ops::DerefMut for AsyncDevice { 43 | fn deref_mut(&mut self) -> &mut Self::Target { 44 | &mut self.inner 45 | } 46 | } 47 | 48 | impl AsyncDevice { 49 | /// Create a new `AsyncDevice` wrapping around a `Device`. 50 | pub fn new(device: Device) -> std::io::Result { 51 | match &device.driver { 52 | Driver::Tun(tun) => { 53 | let session_reader = DeviceReader::new(tun.get_session().into())?; 54 | let session_writer = DeviceWriter::new(tun.get_session().into())?; 55 | Ok(AsyncDevice { 56 | inner: device, 57 | session_reader, 58 | session_writer, 59 | }) 60 | } 61 | Driver::Tap(_) => unimplemented!(), 62 | } 63 | } 64 | 65 | /// Consumes this AsyncDevice and return a Framed object (unified Stream and Sink interface) 66 | pub fn into_framed(self) -> Framed { 67 | let mtu = self.mtu().unwrap_or(crate::DEFAULT_MTU); 68 | let codec = TunPacketCodec::new(mtu as usize); 69 | // guarantee to avoid the mtu of wintun may far away larger than the default provided capacity of ReadBuf of Framed 70 | Framed::with_capacity(self, codec, mtu as usize) 71 | } 72 | 73 | pub fn split(self) -> std::io::Result<(DeviceWriter, DeviceReader)> { 74 | Ok((self.session_writer, self.session_reader)) 75 | } 76 | 77 | /// Recv a packet from tun device - Not implemented for windows 78 | pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result { 79 | self.session_reader.session.recv(buf).await 80 | } 81 | 82 | /// Send a packet to tun device - Not implemented for windows 83 | pub async fn send(&self, buf: &[u8]) -> std::io::Result { 84 | self.session_writer.session.send(buf).await 85 | } 86 | } 87 | 88 | impl AsyncRead for AsyncDevice { 89 | fn poll_read( 90 | mut self: Pin<&mut Self>, 91 | cx: &mut Context<'_>, 92 | buf: &mut ReadBuf<'_>, 93 | ) -> Poll> { 94 | Pin::new(&mut self.session_reader).poll_read(cx, buf) 95 | } 96 | } 97 | 98 | impl AsyncWrite for AsyncDevice { 99 | fn poll_write( 100 | mut self: Pin<&mut Self>, 101 | cx: &mut Context<'_>, 102 | buf: &[u8], 103 | ) -> Poll> { 104 | Pin::new(&mut self.session_writer).poll_write(cx, buf) 105 | } 106 | 107 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 108 | Pin::new(&mut self.session_writer).poll_flush(cx) 109 | } 110 | 111 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 112 | Pin::new(&mut self.session_writer).poll_shutdown(cx) 113 | } 114 | } 115 | 116 | pub struct DeviceReader { 117 | session: AsyncSession, 118 | } 119 | 120 | impl DeviceReader { 121 | fn new(session: AsyncSession) -> std::io::Result { 122 | Ok(DeviceReader { session }) 123 | } 124 | } 125 | 126 | impl AsyncRead for DeviceReader { 127 | fn poll_read( 128 | mut self: Pin<&mut Self>, 129 | cx: &mut Context<'_>, 130 | buf: &mut ReadBuf<'_>, 131 | ) -> Poll> { 132 | let buf_ref = buf.initialize_unfilled(); 133 | match futures::AsyncRead::poll_read(Pin::new(&mut self.session), cx, buf_ref) { 134 | Poll::Ready(Ok(size)) => { 135 | buf.advance(size); 136 | Poll::Ready(Ok(())) 137 | } 138 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 139 | Poll::Pending => Poll::Pending, 140 | } 141 | } 142 | } 143 | 144 | pub struct DeviceWriter { 145 | session: AsyncSession, 146 | } 147 | 148 | impl DeviceWriter { 149 | fn new(session: AsyncSession) -> std::io::Result { 150 | Ok(DeviceWriter { session }) 151 | } 152 | } 153 | 154 | impl AsyncWrite for DeviceWriter { 155 | fn poll_write( 156 | mut self: Pin<&mut Self>, 157 | cx: &mut Context<'_>, 158 | buf: &[u8], 159 | ) -> Poll> { 160 | futures::AsyncWrite::poll_write(Pin::new(&mut self.session), cx, buf) 161 | } 162 | 163 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 164 | futures::AsyncWrite::poll_flush(Pin::new(&mut self.session), cx) 165 | } 166 | 167 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 168 | futures::AsyncWrite::poll_close(Pin::new(&mut self.session), cx) 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/configuration.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use std::net::IpAddr; 16 | #[cfg(unix)] 17 | use std::os::unix::io::RawFd; 18 | 19 | use crate::address::ToAddress; 20 | use crate::platform::PlatformConfig; 21 | 22 | cfg_if::cfg_if! { 23 | if #[cfg(windows)] { 24 | #[allow(dead_code)] 25 | #[derive(Clone, Debug)] 26 | pub(crate) struct WinHandle(std::os::windows::raw::HANDLE); 27 | unsafe impl Send for WinHandle {} 28 | unsafe impl Sync for WinHandle {} 29 | } 30 | } 31 | 32 | /// TUN interface OSI layer of operation. 33 | #[derive(Clone, Copy, Default, Debug, Eq, PartialEq)] 34 | pub enum Layer { 35 | L2, 36 | #[default] 37 | L3, 38 | } 39 | 40 | /// Configuration builder for a TUN interface. 41 | #[derive(Clone, Default, Debug)] 42 | pub struct Configuration { 43 | pub(crate) tun_name: Option, 44 | pub(crate) platform_config: PlatformConfig, 45 | pub(crate) address: Option, 46 | pub(crate) destination: Option, 47 | pub(crate) broadcast: Option, 48 | pub(crate) netmask: Option, 49 | pub(crate) mtu: Option, 50 | pub(crate) enabled: Option, 51 | pub(crate) layer: Option, 52 | pub(crate) queues: Option, 53 | #[cfg(unix)] 54 | pub(crate) raw_fd: Option, 55 | #[cfg(not(unix))] 56 | pub(crate) raw_fd: Option, 57 | #[cfg(windows)] 58 | pub(crate) raw_handle: Option, 59 | #[cfg(windows)] 60 | pub(crate) ring_capacity: Option, 61 | #[cfg(windows)] 62 | pub(crate) metric: Option, 63 | #[cfg(unix)] 64 | pub(crate) close_fd_on_drop: Option, 65 | } 66 | 67 | impl Configuration { 68 | /// Access the platform-dependent configuration. 69 | pub fn platform_config(&mut self, f: F) -> &mut Self 70 | where 71 | F: FnOnce(&mut PlatformConfig), 72 | { 73 | f(&mut self.platform_config); 74 | self 75 | } 76 | 77 | /// Functionally equivalent to `tun_name` 78 | #[deprecated( 79 | since = "1.1.2", 80 | note = "Since the API `name` may have an easy name conflict when IDE prompts, it is replaced by `tun_name` for better coding experience" 81 | )] 82 | pub fn name>(&mut self, tun_name: S) -> &mut Self { 83 | self.tun_name = Some(tun_name.as_ref().into()); 84 | self 85 | } 86 | 87 | /// Set the tun name. 88 | /// 89 | /// [Note: on macOS, the tun name must be the form `utunx` where `x` is a number, such as `utun3`. -- end note] 90 | pub fn tun_name>(&mut self, tun_name: S) -> &mut Self { 91 | self.tun_name = Some(tun_name.as_ref().into()); 92 | self 93 | } 94 | 95 | /// Set the address. 96 | pub fn address(&mut self, value: A) -> &mut Self { 97 | self.address = Some(value.to_address().unwrap()); 98 | self 99 | } 100 | 101 | /// Set the destination address. 102 | pub fn destination(&mut self, value: A) -> &mut Self { 103 | self.destination = Some(value.to_address().unwrap()); 104 | self 105 | } 106 | 107 | /// Set the broadcast address. 108 | pub fn broadcast(&mut self, value: A) -> &mut Self { 109 | self.broadcast = Some(value.to_address().unwrap()); 110 | self 111 | } 112 | 113 | /// Set the netmask. 114 | pub fn netmask(&mut self, value: A) -> &mut Self { 115 | self.netmask = Some(value.to_address().unwrap()); 116 | self 117 | } 118 | 119 | /// Set the MTU. 120 | pub fn mtu(&mut self, value: u16) -> &mut Self { 121 | self.mtu = Some(value); 122 | self 123 | } 124 | 125 | /// Set the interface to be enabled once created. 126 | pub fn up(&mut self) -> &mut Self { 127 | self.enabled = Some(true); 128 | self 129 | } 130 | 131 | /// Set the interface to be disabled once created. 132 | pub fn down(&mut self) -> &mut Self { 133 | self.enabled = Some(false); 134 | self 135 | } 136 | 137 | /// Set the OSI layer of operation. 138 | pub fn layer(&mut self, value: Layer) -> &mut Self { 139 | self.layer = Some(value); 140 | self 141 | } 142 | 143 | /// Set the number of queues. 144 | /// Note: The queues must be 1, otherwise will failed. 145 | #[deprecated(since = "1.0.0", note = "The queues will always be 1.")] 146 | pub fn queues(&mut self, value: usize) -> &mut Self { 147 | self.queues = Some(value); 148 | self 149 | } 150 | 151 | /// Set the raw fd. 152 | #[cfg(unix)] 153 | pub fn raw_fd(&mut self, fd: RawFd) -> &mut Self { 154 | self.raw_fd = Some(fd); 155 | self 156 | } 157 | #[cfg(not(unix))] 158 | pub fn raw_fd(&mut self, fd: i32) -> &mut Self { 159 | self.raw_fd = Some(fd); 160 | self 161 | } 162 | #[cfg(windows)] 163 | pub fn raw_handle(&mut self, handle: std::os::windows::raw::HANDLE) -> &mut Self { 164 | self.raw_handle = Some(WinHandle(handle)); 165 | self 166 | } 167 | #[cfg(windows)] 168 | pub fn ring_capacity(&mut self, ring_capacity: u32) -> &mut Self { 169 | self.ring_capacity = Some(ring_capacity); 170 | self 171 | } 172 | #[cfg(windows)] 173 | pub fn metric(&mut self, metric: u16) -> &mut Self { 174 | self.metric = Some(metric); 175 | self 176 | } 177 | /// Set whether to close the received raw file descriptor on drop or not. 178 | /// The default behaviour is to close the received or tun2 generated file descriptor. 179 | /// Note: If this is set to false, it is up to the caller to ensure the 180 | /// file descriptor that they pass via [Configuration::raw_fd] is properly closed. 181 | #[cfg(unix)] 182 | pub fn close_fd_on_drop(&mut self, value: bool) -> &mut Self { 183 | self.close_fd_on_drop = Some(value); 184 | self 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use crate::configuration::Configuration; 16 | use crate::error::Result; 17 | use std::io::{Read, Write}; 18 | use std::net::IpAddr; 19 | 20 | /// A TUN abstract device interface. 21 | pub trait AbstractDevice: Read + Write { 22 | /// Reconfigure the device. 23 | fn configure(&mut self, config: &Configuration) -> Result<()> { 24 | if let Some(ip) = config.address { 25 | self.set_address(ip)?; 26 | } 27 | 28 | if let Some(ip) = config.destination { 29 | self.set_destination(ip)?; 30 | } 31 | 32 | if let Some(ip) = config.broadcast { 33 | self.set_broadcast(ip)?; 34 | } 35 | 36 | if let Some(ip) = config.netmask { 37 | self.set_netmask(ip)?; 38 | } 39 | 40 | if let Some(mtu) = config.mtu { 41 | self.set_mtu(mtu)?; 42 | } 43 | 44 | if let Some(enabled) = config.enabled { 45 | self.enabled(enabled)?; 46 | } 47 | 48 | Ok(()) 49 | } 50 | 51 | /// Get the device index. 52 | fn tun_index(&self) -> Result; 53 | 54 | /// Get the device tun name. 55 | fn tun_name(&self) -> Result; 56 | 57 | /// Set the device tun name. 58 | fn set_tun_name(&mut self, tun_name: &str) -> Result<()>; 59 | 60 | /// Turn on or off the interface. 61 | fn enabled(&mut self, value: bool) -> Result<()>; 62 | 63 | /// Get the address. 64 | fn address(&self) -> Result; 65 | 66 | /// Set the address. 67 | fn set_address(&mut self, value: IpAddr) -> Result<()>; 68 | 69 | /// Get the destination address. 70 | fn destination(&self) -> Result; 71 | 72 | /// Set the destination address. 73 | fn set_destination(&mut self, value: IpAddr) -> Result<()>; 74 | 75 | /// Get the broadcast address. 76 | fn broadcast(&self) -> Result; 77 | 78 | /// Set the broadcast address. 79 | fn set_broadcast(&mut self, value: IpAddr) -> Result<()>; 80 | 81 | /// Get the netmask. 82 | fn netmask(&self) -> Result; 83 | 84 | /// Set the netmask. 85 | fn set_netmask(&mut self, value: IpAddr) -> Result<()>; 86 | 87 | /// Get the MTU. 88 | fn mtu(&self) -> Result; 89 | 90 | /// Set the MTU. 91 | /// 92 | /// [Note: This setting has no effect on the Windows platform due to the mtu of wintun is always 65535. --end note] 93 | fn set_mtu(&mut self, value: u16) -> Result<()>; 94 | 95 | /// Return whether the underlying tun device on the platform has packet information 96 | /// 97 | /// [Note: This value is not used to specify whether the packets delivered from/to tun2 have packet information. -- end note] 98 | fn packet_information(&self) -> bool; 99 | } 100 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | #[derive(thiserror::Error, Debug)] 16 | pub enum Error { 17 | #[error("invalid configuration")] 18 | InvalidConfig, 19 | 20 | #[error("not implementated")] 21 | NotImplemented, 22 | 23 | #[error("device tun name too long")] 24 | NameTooLong, 25 | 26 | #[error("invalid device tun name")] 27 | InvalidName, 28 | 29 | #[error("invalid address")] 30 | InvalidAddress, 31 | 32 | #[error("invalid file descriptor")] 33 | InvalidDescriptor, 34 | 35 | #[error("unsuported network layer of operation")] 36 | UnsupportedLayer, 37 | 38 | #[error("invalid queues number")] 39 | InvalidQueuesNumber, 40 | 41 | #[error("out of range integral type conversion attempted")] 42 | TryFromIntError, 43 | 44 | #[error(transparent)] 45 | Io(#[from] std::io::Error), 46 | 47 | #[error(transparent)] 48 | Nul(#[from] std::ffi::NulError), 49 | 50 | #[error(transparent)] 51 | ParseNum(#[from] std::num::ParseIntError), 52 | 53 | #[cfg(target_os = "windows")] 54 | #[error(transparent)] 55 | WintunError(#[from] wintun_bindings::Error), 56 | 57 | #[error("{0}")] 58 | String(String), 59 | } 60 | 61 | impl From<&str> for Error { 62 | fn from(err: &str) -> Self { 63 | Self::String(err.to_string()) 64 | } 65 | } 66 | 67 | impl From for Error { 68 | fn from(err: String) -> Self { 69 | Self::String(err) 70 | } 71 | } 72 | 73 | impl From<&String> for Error { 74 | fn from(err: &String) -> Self { 75 | Self::String(err.to_string()) 76 | } 77 | } 78 | 79 | impl From for std::io::Error { 80 | fn from(value: Error) -> Self { 81 | match value { 82 | Error::Io(err) => err, 83 | _ => std::io::Error::new(std::io::ErrorKind::Other, value), 84 | } 85 | } 86 | } 87 | 88 | pub type BoxError = Box; 89 | 90 | pub type Result = ::std::result::Result; 91 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | mod error; 16 | pub use crate::error::{BoxError, Error, Result}; 17 | 18 | mod address; 19 | pub use crate::address::ToAddress; 20 | 21 | mod device; 22 | pub use crate::device::AbstractDevice; 23 | 24 | mod configuration; 25 | pub use crate::configuration::{Configuration, Layer}; 26 | 27 | mod platform; 28 | pub use crate::platform::*; 29 | 30 | pub(crate) mod run_command; 31 | 32 | #[cfg(feature = "async")] 33 | mod r#async; 34 | #[cfg(feature = "async")] 35 | pub use r#async::*; 36 | 37 | pub fn configure() -> Configuration { 38 | Configuration::default() 39 | } 40 | 41 | #[cfg(unix)] 42 | pub const DEFAULT_MTU: u16 = 1500; 43 | #[cfg(windows)] 44 | pub const DEFAULT_MTU: u16 = wintun_bindings::MAX_IP_PACKET_SIZE as _; // u16::MAX 45 | 46 | pub const PACKET_INFORMATION_LENGTH: usize = 4; 47 | -------------------------------------------------------------------------------- /src/platform/android/device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | #![allow(unused_variables)] 15 | 16 | use std::io::{Read, Write}; 17 | use std::net::IpAddr; 18 | use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; 19 | 20 | use crate::configuration::Configuration; 21 | use crate::device::AbstractDevice; 22 | use crate::error::{Error, Result}; 23 | use crate::platform::posix::{self, Fd, Tun}; 24 | 25 | /// A TUN device for Android. 26 | pub struct Device { 27 | tun: Tun, 28 | } 29 | 30 | impl AsRef for Device { 31 | fn as_ref(&self) -> &(dyn AbstractDevice + 'static) { 32 | self 33 | } 34 | } 35 | 36 | impl AsMut for Device { 37 | fn as_mut(&mut self) -> &mut (dyn AbstractDevice + 'static) { 38 | self 39 | } 40 | } 41 | 42 | impl Device { 43 | /// Create a new `Device` for the given `Configuration`. 44 | pub fn new(config: &Configuration) -> Result { 45 | let close_fd_on_drop = config.close_fd_on_drop.unwrap_or(true); 46 | let fd = match config.raw_fd { 47 | Some(raw_fd) => raw_fd, 48 | _ => return Err(Error::InvalidConfig), 49 | }; 50 | let device = { 51 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 52 | let tun = Fd::new(fd, close_fd_on_drop).map_err(|_| std::io::Error::last_os_error())?; 53 | 54 | Device { 55 | tun: Tun::new(tun, mtu, false), 56 | } 57 | }; 58 | 59 | Ok(device) 60 | } 61 | 62 | /// Split the interface into a `Reader` and `Writer`. 63 | pub fn split(self) -> (posix::Reader, posix::Writer) { 64 | (self.tun.reader, self.tun.writer) 65 | } 66 | 67 | /// Set non-blocking mode 68 | pub fn set_nonblock(&self) -> std::io::Result<()> { 69 | self.tun.set_nonblock() 70 | } 71 | 72 | /// Recv a packet from tun device 73 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 74 | self.tun.recv(buf) 75 | } 76 | 77 | /// Send a packet to tun device 78 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 79 | self.tun.send(buf) 80 | } 81 | } 82 | 83 | impl Read for Device { 84 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 85 | self.tun.read(buf) 86 | } 87 | } 88 | 89 | impl Write for Device { 90 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 91 | self.tun.write(buf) 92 | } 93 | 94 | fn flush(&mut self) -> std::io::Result<()> { 95 | self.tun.flush() 96 | } 97 | } 98 | 99 | impl AbstractDevice for Device { 100 | fn tun_index(&self) -> Result { 101 | Err(Error::NotImplemented) 102 | } 103 | 104 | fn tun_name(&self) -> Result { 105 | Ok("".to_string()) 106 | } 107 | 108 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 109 | Err(Error::NotImplemented) 110 | } 111 | 112 | fn enabled(&mut self, value: bool) -> Result<()> { 113 | Ok(()) 114 | } 115 | 116 | fn address(&self) -> Result { 117 | Err(Error::NotImplemented) 118 | } 119 | 120 | fn set_address(&mut self, _value: IpAddr) -> Result<()> { 121 | Ok(()) 122 | } 123 | 124 | fn destination(&self) -> Result { 125 | Err(Error::NotImplemented) 126 | } 127 | 128 | fn set_destination(&mut self, _value: IpAddr) -> Result<()> { 129 | Ok(()) 130 | } 131 | 132 | fn broadcast(&self) -> Result { 133 | Err(Error::NotImplemented) 134 | } 135 | 136 | fn set_broadcast(&mut self, _value: IpAddr) -> Result<()> { 137 | Ok(()) 138 | } 139 | 140 | fn netmask(&self) -> Result { 141 | Err(Error::NotImplemented) 142 | } 143 | 144 | fn set_netmask(&mut self, _value: IpAddr) -> Result<()> { 145 | Ok(()) 146 | } 147 | 148 | fn mtu(&self) -> Result { 149 | // TODO: must get the mtu from the underlying device driver 150 | Ok(self.tun.mtu()) 151 | } 152 | 153 | fn set_mtu(&mut self, value: u16) -> Result<()> { 154 | // TODO: must set the mtu to the underlying device driver 155 | self.tun.set_mtu(value); 156 | Ok(()) 157 | } 158 | 159 | fn packet_information(&self) -> bool { 160 | self.tun.packet_information() 161 | } 162 | } 163 | 164 | impl AsRawFd for Device { 165 | fn as_raw_fd(&self) -> RawFd { 166 | self.tun.as_raw_fd() 167 | } 168 | } 169 | 170 | impl IntoRawFd for Device { 171 | fn into_raw_fd(self) -> RawFd { 172 | self.tun.into_raw_fd() 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/platform/android/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Android specific functionality. 16 | 17 | mod device; 18 | pub use self::device::Device; 19 | 20 | use crate::configuration::Configuration; 21 | use crate::error::Result; 22 | 23 | /// Android-only interface configuration. 24 | #[derive(Copy, Clone, Default, Debug)] 25 | pub struct PlatformConfig; 26 | 27 | /// Create a TUN device with the given name. 28 | pub fn create(configuration: &Configuration) -> Result { 29 | Device::new(configuration) 30 | } 31 | -------------------------------------------------------------------------------- /src/platform/freebsd/device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, March 2024 3 | // 4 | // Copyleft (ↄ) xmh. <970252187@qq.com> 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use libc::{ 16 | self, c_char, c_short, ifreq, AF_INET, IFF_RUNNING, IFF_UP, IFNAMSIZ, O_RDWR, SOCK_DGRAM, 17 | }; 18 | use std::{ 19 | // ffi::{CStr, CString}, 20 | io::{Read, Write}, 21 | mem, 22 | net::{IpAddr, Ipv4Addr}, 23 | os::unix::io::{AsRawFd, IntoRawFd, RawFd}, 24 | ptr, 25 | }; 26 | 27 | use crate::{ 28 | configuration::{Configuration, Layer}, 29 | device::AbstractDevice, 30 | error::{Error, Result}, 31 | platform::freebsd::sys::*, 32 | platform::posix::{self, sockaddr_union, Fd, Tun}, 33 | run_command::run_command, 34 | }; 35 | 36 | #[derive(Clone, Copy)] 37 | struct Route { 38 | addr: Ipv4Addr, 39 | netmask: Ipv4Addr, 40 | dest: Ipv4Addr, 41 | } 42 | 43 | /// A TUN device using the TUN/TAP Linux driver. 44 | pub struct Device { 45 | tun_name: String, 46 | tun: Tun, 47 | ctl: Fd, 48 | route: Option, 49 | } 50 | 51 | impl AsRef for Device { 52 | fn as_ref(&self) -> &(dyn AbstractDevice + 'static) { 53 | self 54 | } 55 | } 56 | 57 | impl AsMut for Device { 58 | fn as_mut(&mut self) -> &mut (dyn AbstractDevice + 'static) { 59 | self 60 | } 61 | } 62 | 63 | impl Device { 64 | /// Create a new `Device` for the given `Configuration`. 65 | pub fn new(config: &Configuration) -> Result { 66 | let mut device = unsafe { 67 | let dev = match config.tun_name.as_ref() { 68 | Some(tun_name) => { 69 | let tun_name = tun_name.clone(); 70 | 71 | if tun_name.len() > IFNAMSIZ { 72 | return Err(Error::NameTooLong); 73 | } 74 | 75 | Some(tun_name) 76 | } 77 | 78 | None => None, 79 | }; 80 | 81 | if config.layer.filter(|l| *l != Layer::L3).is_some() { 82 | return Err(Error::UnsupportedLayer); 83 | } 84 | 85 | let queues_num = config.queues.unwrap_or(1); 86 | if queues_num != 1 { 87 | return Err(Error::InvalidQueuesNumber); 88 | } 89 | 90 | let ctl = Fd::new(libc::socket(AF_INET, SOCK_DGRAM, 0), true)?; 91 | 92 | let (tun, tun_name) = { 93 | if let Some(name) = dev.as_ref() { 94 | let device_path = format!("/dev/{}\0", name); 95 | let fd = libc::open(device_path.as_ptr() as *const _, O_RDWR); 96 | let tun = Fd::new(fd, true).map_err(|_| std::io::Error::last_os_error())?; 97 | (tun, name.clone()) 98 | } else { 99 | let (tun, device_name) = 'End: { 100 | for i in 0..256 { 101 | let device_name = format!("tun{i}"); 102 | let device_path = format!("/dev/{device_name}\0"); 103 | let fd = libc::open(device_path.as_ptr() as *const _, O_RDWR); 104 | if fd > 0 { 105 | use std::io::Error; 106 | let tun = Fd::new(fd, true).map_err(|_| Error::last_os_error())?; 107 | break 'End (tun, device_name); 108 | } 109 | } 110 | use std::io::ErrorKind::AlreadyExists; 111 | let info = "no avaiable file descriptor"; 112 | return Err(Error::Io(std::io::Error::new(AlreadyExists, info).into())); 113 | }; 114 | (tun, device_name) 115 | } 116 | }; 117 | 118 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 119 | 120 | Device { 121 | tun_name, 122 | tun: Tun::new(tun, mtu, false), 123 | ctl, 124 | route: None, 125 | } 126 | }; 127 | 128 | device.set_alias( 129 | config 130 | .address 131 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))), 132 | config 133 | .destination 134 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 255))), 135 | config 136 | .netmask 137 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 0))), 138 | )?; 139 | 140 | device.configure(config)?; 141 | 142 | Ok(device) 143 | } 144 | 145 | /// Set the IPv4 alias of the device. 146 | fn set_alias(&mut self, addr: IpAddr, dest: IpAddr, mask: IpAddr) -> Result<()> { 147 | let IpAddr::V4(addr) = addr else { 148 | unimplemented!("do not support IPv6 yet") 149 | }; 150 | let IpAddr::V4(dest) = dest else { 151 | unimplemented!("do not support IPv6 yet") 152 | }; 153 | let IpAddr::V4(mask) = mask else { 154 | unimplemented!("do not support IPv6 yet") 155 | }; 156 | let ctl = &self.ctl; 157 | unsafe { 158 | let mut req: ifaliasreq = mem::zeroed(); 159 | ptr::copy_nonoverlapping( 160 | self.tun_name.as_ptr() as *const c_char, 161 | req.ifran.as_mut_ptr(), 162 | self.tun_name.len(), 163 | ); 164 | 165 | req.addr = posix::sockaddr_union::from((addr, 0)).addr; 166 | req.dstaddr = posix::sockaddr_union::from((dest, 0)).addr; 167 | req.mask = posix::sockaddr_union::from((mask, 0)).addr; 168 | 169 | if let Err(err) = siocaifaddr(ctl.as_raw_fd(), &req) { 170 | return Err(std::io::Error::from(err).into()); 171 | } 172 | 173 | let route = Route { 174 | addr, 175 | netmask: mask, 176 | dest: dest, 177 | }; 178 | if let Err(e) = self.set_route(route) { 179 | log::warn!("{e:?}"); 180 | } 181 | 182 | Ok(()) 183 | } 184 | } 185 | 186 | /// Prepare a new request. 187 | unsafe fn request(&self) -> ifreq { 188 | let mut req: ifreq = mem::zeroed(); 189 | ptr::copy_nonoverlapping( 190 | self.tun_name.as_ptr() as *const c_char, 191 | req.ifr_name.as_mut_ptr(), 192 | self.tun_name.len(), 193 | ); 194 | 195 | req 196 | } 197 | 198 | /// Split the interface into a `Reader` and `Writer`. 199 | pub fn split(self) -> (posix::Reader, posix::Writer) { 200 | (self.tun.reader, self.tun.writer) 201 | } 202 | 203 | /// Set non-blocking mode 204 | pub fn set_nonblock(&self) -> std::io::Result<()> { 205 | self.tun.set_nonblock() 206 | } 207 | 208 | fn set_route(&mut self, route: Route) -> Result<()> { 209 | // if let Some(v) = &self.route { 210 | // let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(v.netmask)) 211 | // .map_err(|_| Error::InvalidConfig)?; 212 | // let network = ipnet::Ipv4Net::new(v.addr, prefix_len) 213 | // .map_err(|e| Error::InvalidConfig)? 214 | // .network(); 215 | // // command: route -n delete -net 10.0.0.0/24 10.0.0.1 216 | // let args = [ 217 | // "-n", 218 | // "delete", 219 | // "-net", 220 | // &format!("{}/{}", network, prefix_len), 221 | // &v.dest.to_string(), 222 | // ]; 223 | // println!("{args:?}"); 224 | // run_command("route", &args); 225 | // log::info!("route {}", args.join(" ")); 226 | // } 227 | 228 | // command: route -n add -net 10.0.0.9/24 10.0.0.1 229 | let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(route.netmask)) 230 | .map_err(|_| Error::InvalidConfig)?; 231 | let args = [ 232 | "-n", 233 | "add", 234 | "-net", 235 | &format!("{}/{}", route.addr, prefix_len), 236 | &route.dest.to_string(), 237 | ]; 238 | run_command("route", &args)?; 239 | log::info!("route {}", args.join(" ")); 240 | self.route = Some(route); 241 | Ok(()) 242 | } 243 | 244 | /// Recv a packet from tun device 245 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 246 | self.tun.recv(buf) 247 | } 248 | 249 | /// Send a packet to tun device 250 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 251 | self.tun.send(buf) 252 | } 253 | } 254 | 255 | impl Read for Device { 256 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 257 | self.tun.read(buf) 258 | } 259 | 260 | fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result { 261 | self.tun.read_vectored(bufs) 262 | } 263 | } 264 | 265 | impl Write for Device { 266 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 267 | self.tun.write(buf) 268 | } 269 | 270 | fn flush(&mut self) -> std::io::Result<()> { 271 | self.tun.flush() 272 | } 273 | 274 | fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { 275 | self.tun.write_vectored(bufs) 276 | } 277 | } 278 | 279 | impl AbstractDevice for Device { 280 | fn tun_index(&self) -> Result { 281 | let name = self.tun_name()?; 282 | Ok(posix::tun_name_to_index(name)? as i32) 283 | } 284 | 285 | fn tun_name(&self) -> Result { 286 | Ok(self.tun_name.clone()) 287 | } 288 | 289 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 290 | use std::ffi::CString; 291 | unsafe { 292 | if value.len() > IFNAMSIZ { 293 | return Err(Error::NameTooLong); 294 | } 295 | let mut req = self.request(); 296 | let tun_name = CString::new(value)?; 297 | let mut tun_name: Vec = tun_name 298 | .into_bytes_with_nul() 299 | .into_iter() 300 | .map(|c| c as i8) 301 | .collect::<_>(); 302 | req.ifr_ifru.ifru_data = tun_name.as_mut_ptr(); 303 | if let Err(err) = siocsifname(self.ctl.as_raw_fd(), &req) { 304 | return Err(std::io::Error::from(err).into()); 305 | } 306 | 307 | self.tun_name = value.to_string(); 308 | Ok(()) 309 | } 310 | } 311 | 312 | fn enabled(&mut self, value: bool) -> Result<()> { 313 | unsafe { 314 | let mut req = self.request(); 315 | 316 | if let Err(err) = siocgifflags(self.ctl.as_raw_fd(), &mut req) { 317 | return Err(std::io::Error::from(err).into()); 318 | } 319 | 320 | if value { 321 | req.ifr_ifru.ifru_flags[0] |= (IFF_UP | IFF_RUNNING) as c_short; 322 | } else { 323 | req.ifr_ifru.ifru_flags[0] &= !(IFF_UP as c_short); 324 | } 325 | 326 | if let Err(err) = siocsifflags(self.ctl.as_raw_fd(), &req) { 327 | return Err(std::io::Error::from(err).into()); 328 | } 329 | 330 | Ok(()) 331 | } 332 | } 333 | 334 | fn address(&self) -> Result { 335 | unsafe { 336 | let mut req = self.request(); 337 | if let Err(err) = siocgifaddr(self.ctl.as_raw_fd(), &mut req) { 338 | return Err(std::io::Error::from(err).into()); 339 | } 340 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 341 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 342 | } 343 | } 344 | 345 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 346 | unsafe { 347 | let mut req = self.request(); 348 | if let Err(err) = siocdifaddr(self.ctl.as_raw_fd(), &mut req) { 349 | return Err(std::io::Error::from(err).into()); 350 | } 351 | let previous = self.route.as_ref().ok_or(Error::InvalidConfig)?; 352 | self.set_alias( 353 | value, 354 | IpAddr::V4(previous.dest), 355 | IpAddr::V4(previous.netmask), 356 | )?; 357 | } 358 | Ok(()) 359 | } 360 | 361 | fn destination(&self) -> Result { 362 | unsafe { 363 | let mut req = self.request(); 364 | if let Err(err) = siocgifdstaddr(self.ctl.as_raw_fd(), &mut req) { 365 | return Err(std::io::Error::from(err).into()); 366 | } 367 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_dstaddr); 368 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 369 | } 370 | } 371 | 372 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 373 | unsafe { 374 | let mut req = self.request(); 375 | if let Err(err) = siocdifaddr(self.ctl.as_raw_fd(), &mut req) { 376 | return Err(std::io::Error::from(err).into()); 377 | } 378 | let previous = self.route.as_ref().ok_or(Error::InvalidConfig)?; 379 | self.set_alias( 380 | IpAddr::V4(previous.addr), 381 | value, 382 | IpAddr::V4(previous.netmask), 383 | )?; 384 | } 385 | Ok(()) 386 | } 387 | 388 | fn broadcast(&self) -> Result { 389 | unsafe { 390 | let mut req = self.request(); 391 | if let Err(err) = siocgifbrdaddr(self.ctl.as_raw_fd(), &mut req) { 392 | return Err(std::io::Error::from(err).into()); 393 | } 394 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_broadaddr); 395 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 396 | } 397 | } 398 | 399 | fn set_broadcast(&mut self, _value: IpAddr) -> Result<()> { 400 | Ok(()) 401 | } 402 | 403 | fn netmask(&self) -> Result { 404 | unsafe { 405 | let mut req = self.request(); 406 | if let Err(err) = siocgifnetmask(self.ctl.as_raw_fd(), &mut req) { 407 | return Err(std::io::Error::from(err).into()); 408 | } 409 | // NOTE: Here should be `ifru_netmask` instead of `ifru_addr`, but `ifreq` does not define it. 410 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 411 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 412 | } 413 | } 414 | 415 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 416 | unsafe { 417 | let mut req = self.request(); 418 | if let Err(err) = siocdifaddr(self.ctl.as_raw_fd(), &mut req) { 419 | return Err(std::io::Error::from(err).into()); 420 | } 421 | let previous = self.route.as_ref().ok_or(Error::InvalidConfig)?; 422 | self.set_alias(IpAddr::V4(previous.addr), IpAddr::V4(previous.dest), value)?; 423 | } 424 | Ok(()) 425 | } 426 | 427 | fn mtu(&self) -> Result { 428 | unsafe { 429 | let mut req = self.request(); 430 | 431 | if let Err(err) = siocgifmtu(self.ctl.as_raw_fd(), &mut req) { 432 | return Err(std::io::Error::from(err).into()); 433 | } 434 | 435 | req.ifr_ifru 436 | .ifru_mtu 437 | .try_into() 438 | .map_err(|_| Error::TryFromIntError) 439 | } 440 | } 441 | 442 | fn set_mtu(&mut self, value: u16) -> Result<()> { 443 | unsafe { 444 | let mut req = self.request(); 445 | req.ifr_ifru.ifru_mtu = value as i32; 446 | 447 | if let Err(err) = siocsifmtu(self.ctl.as_raw_fd(), &req) { 448 | return Err(std::io::Error::from(err).into()); 449 | } 450 | self.tun.set_mtu(value); 451 | Ok(()) 452 | } 453 | } 454 | 455 | fn packet_information(&self) -> bool { 456 | self.tun.packet_information() 457 | } 458 | } 459 | 460 | impl AsRawFd for Device { 461 | fn as_raw_fd(&self) -> RawFd { 462 | self.tun.as_raw_fd() 463 | } 464 | } 465 | 466 | impl IntoRawFd for Device { 467 | fn into_raw_fd(self) -> RawFd { 468 | self.tun.into_raw_fd() 469 | } 470 | } 471 | 472 | impl From for c_short { 473 | fn from(layer: Layer) -> Self { 474 | match layer { 475 | Layer::L2 => 2, 476 | Layer::L3 => 3, 477 | } 478 | } 479 | } 480 | -------------------------------------------------------------------------------- /src/platform/freebsd/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Linux specific functionality. 16 | 17 | pub mod sys; 18 | 19 | mod device; 20 | pub use self::device::Device; 21 | 22 | use crate::configuration::Configuration; 23 | use crate::error::Result; 24 | 25 | /// FreeBSD-only interface configuration. 26 | #[derive(Copy, Clone, Default, Debug)] 27 | pub struct PlatformConfig; 28 | 29 | /// Create a TUN device with the given name. 30 | pub fn create(configuration: &Configuration) -> Result { 31 | Device::new(configuration) 32 | } 33 | -------------------------------------------------------------------------------- /src/platform/freebsd/sys.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, March 2024 3 | // 4 | // Copyleft (ↄ) xmh. <970252187@qq.com> 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Bindings to internal FreeBSD stuff. 16 | 17 | use libc::{c_char, c_int, c_uint, ifreq, sockaddr, IFNAMSIZ}; 18 | use nix::{ioctl_readwrite, ioctl_write_ptr}; 19 | 20 | #[allow(non_camel_case_types)] 21 | #[repr(C)] 22 | #[derive(Copy, Clone)] 23 | pub struct ctl_info { 24 | pub ctl_id: c_uint, 25 | pub ctl_name: [c_char; 96], 26 | } 27 | 28 | #[allow(non_camel_case_types)] 29 | #[repr(C)] 30 | #[derive(Copy, Clone)] 31 | pub struct ifaliasreq { 32 | pub ifran: [c_char; IFNAMSIZ], 33 | pub addr: sockaddr, 34 | pub dstaddr: sockaddr, 35 | pub mask: sockaddr, 36 | pub ifra_vhid: c_int, 37 | } 38 | 39 | // #[allow(non_camel_case_types)] 40 | // #[repr(C)] 41 | // #[derive(Copy, Clone)] 42 | // pub struct in_aliasreq { 43 | // pub ifra_name: [c_char; IFNAMSIZ], 44 | // pub ifra_addr: sockaddr_in, 45 | // pub ifra_dstaddr: sockaddr_in, 46 | // pub ifra_mask: sockaddr_in, 47 | // pub ifra_vhid:c_int 48 | // } 49 | 50 | ioctl_write_ptr!(siocsifflags, b'i', 16, ifreq); 51 | ioctl_readwrite!(siocgifflags, b'i', 17, ifreq); 52 | 53 | ioctl_write_ptr!(siocsifaddr, b'i', 12, ifreq); 54 | ioctl_readwrite!(siocgifaddr, b'i', 33, ifreq); 55 | 56 | ioctl_write_ptr!(siocsifdstaddr, b'i', 14, ifreq); 57 | ioctl_readwrite!(siocgifdstaddr, b'i', 34, ifreq); 58 | 59 | ioctl_write_ptr!(siocsifbrdaddr, b'i', 19, ifreq); 60 | ioctl_readwrite!(siocgifbrdaddr, b'i', 35, ifreq); 61 | 62 | ioctl_write_ptr!(siocsifnetmask, b'i', 22, ifreq); 63 | ioctl_readwrite!(siocgifnetmask, b'i', 37, ifreq); 64 | 65 | ioctl_write_ptr!(siocsifmtu, b'i', 52, ifreq); 66 | ioctl_readwrite!(siocgifmtu, b'i', 51, ifreq); 67 | 68 | ioctl_write_ptr!(siocaifaddr, b'i', 43, ifaliasreq); 69 | ioctl_write_ptr!(siocdifaddr, b'i', 25, ifreq); 70 | 71 | ioctl_write_ptr!(siocifcreate, b'i', 122, ifreq); 72 | 73 | ioctl_write_ptr!(siocsifphyaddr, b'i', 70, ifaliasreq); 74 | 75 | ioctl_write_ptr!(siocsifname, b'i', 40, ifreq); 76 | -------------------------------------------------------------------------------- /src/platform/ios/device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | #![allow(unused_variables)] 15 | 16 | use crate::{ 17 | configuration::Configuration, 18 | device::AbstractDevice, 19 | error::{Error, Result}, 20 | platform::posix::{self, Fd, Tun}, 21 | }; 22 | use std::{ 23 | io::{Read, Write}, 24 | net::IpAddr, 25 | os::unix::io::{AsRawFd, IntoRawFd, RawFd}, 26 | }; 27 | 28 | /// A TUN device for iOS. 29 | pub struct Device { 30 | tun: Tun, 31 | } 32 | 33 | impl AsRef for Device { 34 | fn as_ref(&self) -> &(dyn AbstractDevice + 'static) { 35 | self 36 | } 37 | } 38 | 39 | impl AsMut for Device { 40 | fn as_mut(&mut self) -> &mut (dyn AbstractDevice + 'static) { 41 | self 42 | } 43 | } 44 | 45 | impl Device { 46 | /// Create a new `Device` for the given `Configuration`. 47 | pub fn new(config: &Configuration) -> Result { 48 | let close_fd_on_drop = config.close_fd_on_drop.unwrap_or(true); 49 | let fd = match config.raw_fd { 50 | Some(raw_fd) => raw_fd, 51 | _ => return Err(Error::InvalidConfig), 52 | }; 53 | let device = { 54 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 55 | let fd = Fd::new(fd, close_fd_on_drop).map_err(|_| std::io::Error::last_os_error())?; 56 | Device { 57 | tun: Tun::new(fd, mtu, config.platform_config.packet_information), 58 | } 59 | }; 60 | 61 | Ok(device) 62 | } 63 | 64 | /// Split the interface into a `Reader` and `Writer`. 65 | pub fn split(self) -> (posix::Reader, posix::Writer) { 66 | (self.tun.reader, self.tun.writer) 67 | } 68 | 69 | /// Set non-blocking mode 70 | pub fn set_nonblock(&self) -> std::io::Result<()> { 71 | self.tun.set_nonblock() 72 | } 73 | 74 | /// Recv a packet from tun device 75 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 76 | self.tun.recv(buf) 77 | } 78 | 79 | /// Send a packet to tun device 80 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 81 | self.tun.send(buf) 82 | } 83 | } 84 | 85 | impl Read for Device { 86 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 87 | self.tun.read(buf) 88 | } 89 | 90 | fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result { 91 | self.tun.read_vectored(bufs) 92 | } 93 | } 94 | 95 | impl Write for Device { 96 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 97 | self.tun.write(buf) 98 | } 99 | 100 | fn flush(&mut self) -> std::io::Result<()> { 101 | self.tun.flush() 102 | } 103 | 104 | fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { 105 | self.tun.write_vectored(bufs) 106 | } 107 | } 108 | 109 | impl AbstractDevice for Device { 110 | fn tun_index(&self) -> Result { 111 | Err(Error::NotImplemented) 112 | } 113 | 114 | fn tun_name(&self) -> Result { 115 | Ok("".to_string()) 116 | } 117 | 118 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 119 | Err(Error::NotImplemented) 120 | } 121 | 122 | fn enabled(&mut self, value: bool) -> Result<()> { 123 | Ok(()) 124 | } 125 | 126 | fn address(&self) -> Result { 127 | Err(Error::NotImplemented) 128 | } 129 | 130 | fn set_address(&mut self, _value: IpAddr) -> Result<()> { 131 | Ok(()) 132 | } 133 | 134 | fn destination(&self) -> Result { 135 | Err(Error::NotImplemented) 136 | } 137 | 138 | fn set_destination(&mut self, _value: IpAddr) -> Result<()> { 139 | Ok(()) 140 | } 141 | 142 | fn broadcast(&self) -> Result { 143 | Err(Error::NotImplemented) 144 | } 145 | 146 | fn set_broadcast(&mut self, _value: IpAddr) -> Result<()> { 147 | Ok(()) 148 | } 149 | 150 | fn netmask(&self) -> Result { 151 | Err(Error::NotImplemented) 152 | } 153 | 154 | fn set_netmask(&mut self, _value: IpAddr) -> Result<()> { 155 | Ok(()) 156 | } 157 | 158 | fn mtu(&self) -> Result { 159 | // TODO: must get the mtu from the underlying device driver 160 | Ok(self.tun.mtu()) 161 | } 162 | 163 | fn set_mtu(&mut self, value: u16) -> Result<()> { 164 | // TODO: must set the mtu to the underlying device driver 165 | self.tun.set_mtu(value); 166 | Ok(()) 167 | } 168 | 169 | fn packet_information(&self) -> bool { 170 | self.tun.packet_information() 171 | } 172 | } 173 | 174 | impl AsRawFd for Device { 175 | fn as_raw_fd(&self) -> RawFd { 176 | self.tun.as_raw_fd() 177 | } 178 | } 179 | 180 | impl IntoRawFd for Device { 181 | fn into_raw_fd(self) -> RawFd { 182 | self.tun.into_raw_fd() 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/platform/ios/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! iOS specific functionality. 16 | 17 | mod device; 18 | pub use device::Device; 19 | 20 | use crate::configuration::Configuration; 21 | use crate::error::Result; 22 | 23 | /// iOS-only interface configuration. 24 | #[derive(Copy, Clone, Debug)] 25 | pub struct PlatformConfig { 26 | /// switch of Enable/Disable packet information for network driver 27 | pub(crate) packet_information: bool, 28 | } 29 | 30 | impl Default for PlatformConfig { 31 | fn default() -> Self { 32 | PlatformConfig { 33 | packet_information: true, // default is true in iOS 34 | } 35 | } 36 | } 37 | 38 | impl PlatformConfig { 39 | /// Enable or disable packet information, the first 4 bytes of 40 | /// each packet delivered from/to iOS underlying API is a header with flags and protocol type when enabled. 41 | /// 42 | /// - If get the fd from 43 | /// ```Objective-C 44 | /// int32_t tunFd = [[NEPacketTunnelProvider::packetFlow valueForKeyPath:@"socket.fileDescriptor"] intValue]; 45 | /// ``` 46 | /// there exist PI. 47 | /// 48 | /// - But if get packet from `[NEPacketTunnelProvider::packetFlow readPacketsWithCompletionHandler:]` 49 | /// and write packet via `[NEPacketTunnelProvider::packetFlow writePackets:withProtocols:]`, there is no PI. 50 | pub fn packet_information(&mut self, value: bool) -> &mut Self { 51 | self.packet_information = value; 52 | self 53 | } 54 | } 55 | 56 | /// Create a TUN device with the given name. 57 | pub fn create(configuration: &Configuration) -> Result { 58 | Device::new(configuration) 59 | } 60 | -------------------------------------------------------------------------------- /src/platform/linux/device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use libc::{ 16 | self, c_char, c_short, ifreq, AF_INET, IFF_MULTI_QUEUE, IFF_NAPI, IFF_NO_PI, IFF_RUNNING, 17 | IFF_TAP, IFF_TUN, IFF_UP, IFF_VNET_HDR, IFNAMSIZ, O_RDWR, SOCK_DGRAM, 18 | }; 19 | use std::{ 20 | ffi::{CStr, CString}, 21 | io::{Read, Write}, 22 | mem, 23 | net::IpAddr, 24 | os::unix::io::{AsRawFd, IntoRawFd, RawFd}, 25 | ptr, 26 | }; 27 | 28 | use crate::{ 29 | configuration::{Configuration, Layer}, 30 | device::AbstractDevice, 31 | error::{Error, Result}, 32 | platform::linux::sys::*, 33 | platform::posix::{self, ipaddr_to_sockaddr, sockaddr_union, Fd, Tun}, 34 | }; 35 | 36 | const OVERWRITE_SIZE: usize = std::mem::size_of::(); 37 | 38 | /// A TUN device using the TUN/TAP Linux driver. 39 | pub struct Device { 40 | tun_name: String, 41 | tun: Tun, 42 | ctl: Fd, 43 | } 44 | 45 | impl AsRef for Device { 46 | fn as_ref(&self) -> &(dyn AbstractDevice + 'static) { 47 | self 48 | } 49 | } 50 | 51 | impl AsMut for Device { 52 | fn as_mut(&mut self) -> &mut (dyn AbstractDevice + 'static) { 53 | self 54 | } 55 | } 56 | 57 | impl Device { 58 | /// Create a new `Device` for the given `Configuration`. 59 | pub fn new(config: &Configuration) -> Result { 60 | if let Some(fd) = config.raw_fd { 61 | let close_fd_on_drop = config.close_fd_on_drop.unwrap_or(true); 62 | let tun_fd = Fd::new(fd, close_fd_on_drop)?; 63 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 64 | let packet_information = config.platform_config.packet_information; 65 | let tun_name = config.tun_name.clone().unwrap_or_else(|| "".into()); 66 | let ctl = Fd::new(unsafe { libc::socket(AF_INET, SOCK_DGRAM, 0) }, true)?; 67 | return Ok(Device { 68 | tun: Tun::new(tun_fd, mtu, packet_information), 69 | tun_name, 70 | ctl, 71 | }); 72 | } 73 | 74 | let mut device = unsafe { 75 | let dev_name = match config.tun_name.as_ref() { 76 | Some(tun_name) => { 77 | let tun_name = CString::new(tun_name.clone())?; 78 | 79 | if tun_name.as_bytes_with_nul().len() > IFNAMSIZ { 80 | return Err(Error::NameTooLong); 81 | } 82 | 83 | Some(tun_name) 84 | } 85 | 86 | None => None, 87 | }; 88 | 89 | let mut req: ifreq = mem::zeroed(); 90 | 91 | if let Some(dev_name) = dev_name.as_ref() { 92 | ptr::copy_nonoverlapping( 93 | dev_name.as_ptr() as *const c_char, 94 | req.ifr_name.as_mut_ptr(), 95 | dev_name.as_bytes_with_nul().len(), 96 | ); 97 | } 98 | 99 | let device_type: c_short = config.layer.unwrap_or(Layer::L3).into(); 100 | 101 | let queues_num = config.queues.unwrap_or(1); 102 | if queues_num != 1 { 103 | return Err(Error::InvalidQueuesNumber); 104 | } 105 | 106 | let iff_no_pi = IFF_NO_PI as c_short; 107 | let iff_multi_queue = IFF_MULTI_QUEUE as c_short; 108 | let iff_napi = IFF_NAPI as c_short; 109 | let iff_vnet_hdr = IFF_VNET_HDR as c_short; 110 | let packet_information = config.platform_config.packet_information; 111 | let napi = config.platform_config.napi; 112 | let vnet_hdr = config.platform_config.vnet_hdr; 113 | req.ifr_ifru.ifru_flags = device_type 114 | | if packet_information { 0 } else { iff_no_pi } 115 | | if napi { iff_napi } else { 0 } 116 | | if vnet_hdr { iff_vnet_hdr } else { 0 } 117 | | if queues_num > 1 { iff_multi_queue } else { 0 }; 118 | 119 | let tun_fd = { 120 | let fd = libc::open(b"/dev/net/tun\0".as_ptr() as *const _, O_RDWR); 121 | let tun_fd = Fd::new(fd, true).map_err(|_| std::io::Error::last_os_error())?; 122 | 123 | if let Err(err) = tunsetiff(tun_fd.inner, &mut req as *mut _ as *mut _) { 124 | return Err(std::io::Error::from(err).into()); 125 | } 126 | 127 | tun_fd 128 | }; 129 | 130 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 131 | 132 | let ctl = Fd::new(libc::socket(AF_INET, SOCK_DGRAM, 0), true)?; 133 | 134 | let tun_name = CStr::from_ptr(req.ifr_name.as_ptr()) 135 | .to_string_lossy() 136 | .to_string(); 137 | Device { 138 | tun_name, 139 | tun: Tun::new(tun_fd, mtu, packet_information), 140 | ctl, 141 | } 142 | }; 143 | 144 | if config.platform_config.ensure_root_privileges { 145 | device.configure(config)?; 146 | } 147 | 148 | Ok(device) 149 | } 150 | 151 | /// Prepare a new request. 152 | unsafe fn request(&self) -> ifreq { 153 | let mut req: ifreq = mem::zeroed(); 154 | ptr::copy_nonoverlapping( 155 | self.tun_name.as_ptr() as *const c_char, 156 | req.ifr_name.as_mut_ptr(), 157 | self.tun_name.len(), 158 | ); 159 | 160 | req 161 | } 162 | 163 | /// Make the device persistent. 164 | pub fn persist(&mut self) -> Result<()> { 165 | unsafe { 166 | if let Err(err) = tunsetpersist(self.as_raw_fd(), &1) { 167 | Err(std::io::Error::from(err).into()) 168 | } else { 169 | Ok(()) 170 | } 171 | } 172 | } 173 | 174 | /// Set the owner of the device. 175 | pub fn user(&mut self, value: i32) -> Result<()> { 176 | unsafe { 177 | if let Err(err) = tunsetowner(self.as_raw_fd(), &value) { 178 | Err(std::io::Error::from(err).into()) 179 | } else { 180 | Ok(()) 181 | } 182 | } 183 | } 184 | 185 | /// Set the group of the device. 186 | pub fn group(&mut self, value: i32) -> Result<()> { 187 | unsafe { 188 | if let Err(err) = tunsetgroup(self.as_raw_fd(), &value) { 189 | Err(std::io::Error::from(err).into()) 190 | } else { 191 | Ok(()) 192 | } 193 | } 194 | } 195 | 196 | /// Split the interface into a `Reader` and `Writer`. 197 | pub fn split(self) -> (posix::Reader, posix::Writer) { 198 | (self.tun.reader, self.tun.writer) 199 | } 200 | 201 | /// Set non-blocking mode 202 | pub fn set_nonblock(&self) -> std::io::Result<()> { 203 | self.tun.set_nonblock() 204 | } 205 | 206 | /// Recv a packet from tun device 207 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 208 | self.tun.recv(buf) 209 | } 210 | 211 | /// Send a packet to tun device 212 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 213 | self.tun.send(buf) 214 | } 215 | } 216 | 217 | impl Read for Device { 218 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 219 | self.tun.read(buf) 220 | } 221 | 222 | fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result { 223 | self.tun.read_vectored(bufs) 224 | } 225 | } 226 | 227 | impl Write for Device { 228 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 229 | self.tun.write(buf) 230 | } 231 | 232 | fn flush(&mut self) -> std::io::Result<()> { 233 | self.tun.flush() 234 | } 235 | 236 | fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { 237 | self.tun.write_vectored(bufs) 238 | } 239 | } 240 | 241 | impl AbstractDevice for Device { 242 | fn tun_index(&self) -> Result { 243 | let name = self.tun_name()?; 244 | Ok(posix::tun_name_to_index(name)? as i32) 245 | } 246 | 247 | fn tun_name(&self) -> Result { 248 | Ok(self.tun_name.clone()) 249 | } 250 | 251 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 252 | unsafe { 253 | let tun_name = CString::new(value)?; 254 | 255 | if tun_name.as_bytes_with_nul().len() > IFNAMSIZ { 256 | return Err(Error::NameTooLong); 257 | } 258 | 259 | let mut req = self.request(); 260 | ptr::copy_nonoverlapping( 261 | tun_name.as_ptr() as *const c_char, 262 | req.ifr_ifru.ifru_newname.as_mut_ptr(), 263 | value.len(), 264 | ); 265 | 266 | if let Err(err) = siocsifname(self.ctl.as_raw_fd(), &req) { 267 | return Err(std::io::Error::from(err).into()); 268 | } 269 | 270 | self.tun_name = value.into(); 271 | 272 | Ok(()) 273 | } 274 | } 275 | 276 | fn enabled(&mut self, value: bool) -> Result<()> { 277 | unsafe { 278 | let mut req = self.request(); 279 | 280 | if let Err(err) = siocgifflags(self.ctl.as_raw_fd(), &mut req) { 281 | return Err(std::io::Error::from(err).into()); 282 | } 283 | 284 | if value { 285 | req.ifr_ifru.ifru_flags |= (IFF_UP | IFF_RUNNING) as c_short; 286 | } else { 287 | req.ifr_ifru.ifru_flags &= !(IFF_UP as c_short); 288 | } 289 | 290 | if let Err(err) = siocsifflags(self.ctl.as_raw_fd(), &req) { 291 | return Err(std::io::Error::from(err).into()); 292 | } 293 | 294 | Ok(()) 295 | } 296 | } 297 | 298 | fn address(&self) -> Result { 299 | unsafe { 300 | let mut req = self.request(); 301 | if let Err(err) = siocgifaddr(self.ctl.as_raw_fd(), &mut req) { 302 | return Err(std::io::Error::from(err).into()); 303 | } 304 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 305 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 306 | } 307 | } 308 | 309 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 310 | unsafe { 311 | let mut req = self.request(); 312 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_addr, OVERWRITE_SIZE); 313 | if let Err(err) = siocsifaddr(self.ctl.as_raw_fd(), &req) { 314 | return Err(std::io::Error::from(err).into()); 315 | } 316 | Ok(()) 317 | } 318 | } 319 | 320 | fn destination(&self) -> Result { 321 | unsafe { 322 | let mut req = self.request(); 323 | if let Err(err) = siocgifdstaddr(self.ctl.as_raw_fd(), &mut req) { 324 | return Err(std::io::Error::from(err).into()); 325 | } 326 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_dstaddr); 327 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 328 | } 329 | } 330 | 331 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 332 | unsafe { 333 | let mut req = self.request(); 334 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_dstaddr, OVERWRITE_SIZE); 335 | if let Err(err) = siocsifdstaddr(self.ctl.as_raw_fd(), &req) { 336 | return Err(std::io::Error::from(err).into()); 337 | } 338 | Ok(()) 339 | } 340 | } 341 | 342 | fn broadcast(&self) -> Result { 343 | unsafe { 344 | let mut req = self.request(); 345 | if let Err(err) = siocgifbrdaddr(self.ctl.as_raw_fd(), &mut req) { 346 | return Err(std::io::Error::from(err).into()); 347 | } 348 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_broadaddr); 349 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 350 | } 351 | } 352 | 353 | fn set_broadcast(&mut self, value: IpAddr) -> Result<()> { 354 | unsafe { 355 | let mut req = self.request(); 356 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_broadaddr, OVERWRITE_SIZE); 357 | if let Err(err) = siocsifbrdaddr(self.ctl.as_raw_fd(), &req) { 358 | return Err(std::io::Error::from(err).into()); 359 | } 360 | Ok(()) 361 | } 362 | } 363 | 364 | fn netmask(&self) -> Result { 365 | unsafe { 366 | let mut req = self.request(); 367 | if let Err(err) = siocgifnetmask(self.ctl.as_raw_fd(), &mut req) { 368 | return Err(std::io::Error::from(err).into()); 369 | } 370 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_netmask); 371 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 372 | } 373 | } 374 | 375 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 376 | unsafe { 377 | let mut req = self.request(); 378 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_netmask, OVERWRITE_SIZE); 379 | if let Err(err) = siocsifnetmask(self.ctl.as_raw_fd(), &req) { 380 | return Err(std::io::Error::from(err).into()); 381 | } 382 | Ok(()) 383 | } 384 | } 385 | 386 | fn mtu(&self) -> Result { 387 | unsafe { 388 | let mut req = self.request(); 389 | 390 | if let Err(err) = siocgifmtu(self.ctl.as_raw_fd(), &mut req) { 391 | return Err(std::io::Error::from(err).into()); 392 | } 393 | 394 | req.ifr_ifru 395 | .ifru_mtu 396 | .try_into() 397 | .map_err(|_| Error::TryFromIntError) 398 | } 399 | } 400 | 401 | fn set_mtu(&mut self, value: u16) -> Result<()> { 402 | unsafe { 403 | let mut req = self.request(); 404 | req.ifr_ifru.ifru_mtu = value as i32; 405 | 406 | if let Err(err) = siocsifmtu(self.ctl.as_raw_fd(), &req) { 407 | return Err(std::io::Error::from(err).into()); 408 | } 409 | self.tun.set_mtu(value); 410 | Ok(()) 411 | } 412 | } 413 | 414 | fn packet_information(&self) -> bool { 415 | self.tun.packet_information() 416 | } 417 | } 418 | 419 | impl AsRawFd for Device { 420 | fn as_raw_fd(&self) -> RawFd { 421 | self.tun.as_raw_fd() 422 | } 423 | } 424 | 425 | impl IntoRawFd for Device { 426 | fn into_raw_fd(self) -> RawFd { 427 | self.tun.into_raw_fd() 428 | } 429 | } 430 | 431 | impl From for c_short { 432 | fn from(layer: Layer) -> Self { 433 | match layer { 434 | Layer::L2 => IFF_TAP as c_short, 435 | Layer::L3 => IFF_TUN as c_short, 436 | } 437 | } 438 | } 439 | -------------------------------------------------------------------------------- /src/platform/linux/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Linux specific functionality. 16 | 17 | mod sys; 18 | 19 | mod device; 20 | pub use self::device::Device; 21 | 22 | use crate::configuration::Configuration; 23 | use crate::error::Result; 24 | 25 | /// Linux-only interface configuration. 26 | #[derive(Copy, Clone, Debug)] 27 | pub struct PlatformConfig { 28 | /// switch of Enable/Disable packet information for network driver 29 | pub(crate) packet_information: bool, 30 | /// root privileges required or not 31 | pub(crate) ensure_root_privileges: bool, 32 | 33 | /// Enable IFF_NAPI 34 | pub(crate) napi: bool, 35 | 36 | /// Enable IFF_VNET_HDR 37 | pub(crate) vnet_hdr: bool, 38 | } 39 | 40 | /// `packet_information` is default to be `false` and `ensure_root_privileges` is default to be `true`. 41 | impl Default for PlatformConfig { 42 | fn default() -> Self { 43 | PlatformConfig { 44 | packet_information: false, 45 | ensure_root_privileges: true, 46 | napi: false, 47 | vnet_hdr: false, 48 | } 49 | } 50 | } 51 | 52 | impl PlatformConfig { 53 | /// Enable or disable packet information, the first 4 bytes of 54 | /// each packet delivered from/to Linux underlying API is a header with flags and protocol type when enabled. 55 | /// 56 | /// [Note: This configuration just applies to the Linux underlying API and is a no-op on tun2(i.e. the packets delivered from/to tun2 always contain no packet information) -- end note]. 57 | #[deprecated( 58 | since = "1.0.0", 59 | note = "No effect applies to the packets delivered from/to tun2 since the packets always contain no header on all platforms." 60 | )] 61 | pub fn packet_information(&mut self, value: bool) -> &mut Self { 62 | self.packet_information = value; 63 | self 64 | } 65 | 66 | /// Indicated whether tun2 running in root privilege, 67 | /// since some operations need it such as assigning IP/netmask/destination etc. 68 | pub fn ensure_root_privileges(&mut self, value: bool) -> &mut Self { 69 | self.ensure_root_privileges = value; 70 | self 71 | } 72 | 73 | /// Enable / Disable IFF_NAPI flag. 74 | pub fn napi(&mut self, value: bool) -> &mut Self { 75 | self.napi = value; 76 | self 77 | } 78 | 79 | /// Enable / Disable IFF_VNET_HDR flag. 80 | pub fn vnet_hdr(&mut self, value: bool) -> &mut Self { 81 | self.vnet_hdr = value; 82 | self 83 | } 84 | } 85 | 86 | /// Create a TUN device with the given name. 87 | pub fn create(configuration: &Configuration) -> Result { 88 | Device::new(configuration) 89 | } 90 | -------------------------------------------------------------------------------- /src/platform/linux/sys.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Bindings to internal Linux stuff. 16 | 17 | use libc::{c_int, ifreq}; 18 | use nix::{ioctl_read_bad, ioctl_write_ptr, ioctl_write_ptr_bad}; 19 | 20 | ioctl_read_bad!(siocgifflags, 0x8913, ifreq); 21 | ioctl_write_ptr_bad!(siocsifflags, 0x8914, ifreq); 22 | ioctl_read_bad!(siocgifaddr, 0x8915, ifreq); 23 | ioctl_write_ptr_bad!(siocsifaddr, 0x8916, ifreq); 24 | ioctl_read_bad!(siocgifdstaddr, 0x8917, ifreq); 25 | ioctl_write_ptr_bad!(siocsifdstaddr, 0x8918, ifreq); 26 | ioctl_read_bad!(siocgifbrdaddr, 0x8919, ifreq); 27 | ioctl_write_ptr_bad!(siocsifbrdaddr, 0x891a, ifreq); 28 | ioctl_read_bad!(siocgifnetmask, 0x891b, ifreq); 29 | ioctl_write_ptr_bad!(siocsifnetmask, 0x891c, ifreq); 30 | ioctl_read_bad!(siocgifmtu, 0x8921, ifreq); 31 | ioctl_write_ptr_bad!(siocsifmtu, 0x8922, ifreq); 32 | ioctl_write_ptr_bad!(siocsifname, 0x8923, ifreq); 33 | 34 | ioctl_write_ptr!(tunsetiff, b'T', 202, c_int); 35 | ioctl_write_ptr!(tunsetpersist, b'T', 203, c_int); 36 | ioctl_write_ptr!(tunsetowner, b'T', 204, c_int); 37 | ioctl_write_ptr!(tunsetgroup, b'T', 206, c_int); 38 | -------------------------------------------------------------------------------- /src/platform/macos/device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | #![allow(unused_variables)] 15 | 16 | use crate::{ 17 | configuration::{Configuration, Layer}, 18 | device::AbstractDevice, 19 | error::{Error, Result}, 20 | platform::{ 21 | macos::sys::*, 22 | posix::{self, ipaddr_to_sockaddr, sockaddr_union, Fd}, 23 | }, 24 | run_command::run_command, 25 | }; 26 | 27 | const OVERWRITE_SIZE: usize = std::mem::size_of::(); 28 | 29 | use libc::{ 30 | self, c_char, c_short, c_uint, c_void, sockaddr, socklen_t, AF_INET, AF_SYSTEM, AF_SYS_CONTROL, 31 | IFF_RUNNING, IFF_UP, IFNAMSIZ, PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, 32 | }; 33 | use std::{ 34 | ffi::CStr, 35 | io::{Read, Write}, 36 | mem, 37 | net::{IpAddr, Ipv4Addr}, 38 | os::unix::io::{AsRawFd, IntoRawFd, RawFd}, 39 | ptr, 40 | }; 41 | 42 | #[derive(Clone, Copy)] 43 | struct Route { 44 | addr: Ipv4Addr, 45 | netmask: Ipv4Addr, 46 | dest: Ipv4Addr, 47 | } 48 | 49 | /// A TUN device using the TUN macOS driver. 50 | pub struct Device { 51 | tun_name: Option, 52 | tun: posix::Tun, 53 | ctl: Option, 54 | route: Option, 55 | } 56 | 57 | impl AsRef for Device { 58 | fn as_ref(&self) -> &(dyn AbstractDevice + 'static) { 59 | self 60 | } 61 | } 62 | 63 | impl AsMut for Device { 64 | fn as_mut(&mut self) -> &mut (dyn AbstractDevice + 'static) { 65 | self 66 | } 67 | } 68 | 69 | impl Device { 70 | /// Create a new `Device` for the given `Configuration`. 71 | pub fn new(config: &Configuration) -> Result { 72 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 73 | if let Some(fd) = config.raw_fd { 74 | let close_fd_on_drop = config.close_fd_on_drop.unwrap_or(true); 75 | let tun = Fd::new(fd, close_fd_on_drop).map_err(|_| std::io::Error::last_os_error())?; 76 | let device = Device { 77 | tun_name: None, 78 | tun: posix::Tun::new(tun, mtu, config.platform_config.packet_information), 79 | ctl: None, 80 | route: None, 81 | }; 82 | return Ok(device); 83 | } 84 | 85 | let id = if let Some(tun_name) = config.tun_name.as_ref() { 86 | if tun_name.len() > IFNAMSIZ { 87 | return Err(Error::NameTooLong); 88 | } 89 | 90 | if !tun_name.starts_with("utun") { 91 | return Err(Error::InvalidName); 92 | } 93 | 94 | tun_name[4..].parse::()? + 1_u32 95 | } else { 96 | 0_u32 97 | }; 98 | 99 | if config.layer.filter(|l| *l != Layer::L3).is_some() { 100 | return Err(Error::UnsupportedLayer); 101 | } 102 | 103 | let queues_number = config.queues.unwrap_or(1); 104 | if queues_number != 1 { 105 | return Err(Error::InvalidQueuesNumber); 106 | } 107 | 108 | let mut device = unsafe { 109 | let fd = libc::socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL); 110 | let tun = posix::Fd::new(fd, true).map_err(|_| std::io::Error::last_os_error())?; 111 | 112 | let mut info = ctl_info { 113 | ctl_id: 0, 114 | ctl_name: { 115 | let mut buffer = [0; 96]; 116 | for (i, o) in UTUN_CONTROL_NAME.as_bytes().iter().zip(buffer.iter_mut()) { 117 | *o = *i as _; 118 | } 119 | buffer 120 | }, 121 | }; 122 | 123 | if let Err(err) = ctliocginfo(tun.inner, &mut info as *mut _ as *mut _) { 124 | return Err(std::io::Error::from(err).into()); 125 | } 126 | 127 | let addr = libc::sockaddr_ctl { 128 | sc_id: info.ctl_id, 129 | sc_len: mem::size_of::() as _, 130 | sc_family: AF_SYSTEM as _, 131 | ss_sysaddr: AF_SYS_CONTROL as _, 132 | sc_unit: id as c_uint, 133 | sc_reserved: [0; 5], 134 | }; 135 | 136 | let address = &addr as *const libc::sockaddr_ctl as *const sockaddr; 137 | if libc::connect(tun.inner, address, mem::size_of_val(&addr) as socklen_t) < 0 { 138 | return Err(std::io::Error::last_os_error().into()); 139 | } 140 | 141 | let mut tun_name = [0u8; 64]; 142 | let mut name_len: socklen_t = 64; 143 | 144 | let optval = &mut tun_name as *mut _ as *mut c_void; 145 | let optlen = &mut name_len as *mut socklen_t; 146 | if libc::getsockopt(tun.inner, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, optval, optlen) < 0 { 147 | return Err(std::io::Error::last_os_error().into()); 148 | } 149 | 150 | let ctl = Some(posix::Fd::new(libc::socket(AF_INET, SOCK_DGRAM, 0), true)?); 151 | 152 | Device { 153 | tun_name: Some( 154 | CStr::from_ptr(tun_name.as_ptr() as *const c_char) 155 | .to_string_lossy() 156 | .into(), 157 | ), 158 | tun: posix::Tun::new(tun, mtu, config.platform_config.packet_information), 159 | ctl, 160 | route: None, 161 | } 162 | }; 163 | 164 | device.configure(config)?; 165 | device.set_alias( 166 | config 167 | .address 168 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))), 169 | config 170 | .destination 171 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 255))), 172 | config 173 | .netmask 174 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 0))), 175 | )?; 176 | 177 | Ok(device) 178 | } 179 | 180 | /// Prepare a new request. 181 | /// # Safety 182 | unsafe fn request(&self) -> Result { 183 | let tun_name = self.tun_name.as_ref().ok_or(Error::InvalidConfig)?; 184 | let mut req: libc::ifreq = mem::zeroed(); 185 | ptr::copy_nonoverlapping( 186 | tun_name.as_ptr() as *const c_char, 187 | req.ifr_name.as_mut_ptr(), 188 | tun_name.len(), 189 | ); 190 | 191 | Ok(req) 192 | } 193 | 194 | /// Set the IPv4 alias of the device. 195 | fn set_alias(&mut self, addr: IpAddr, broadaddr: IpAddr, mask: IpAddr) -> Result<()> { 196 | let IpAddr::V4(addr) = addr else { 197 | unimplemented!("do not support IPv6 yet") 198 | }; 199 | let IpAddr::V4(broadaddr) = broadaddr else { 200 | unimplemented!("do not support IPv6 yet") 201 | }; 202 | let IpAddr::V4(mask) = mask else { 203 | unimplemented!("do not support IPv6 yet") 204 | }; 205 | let tun_name = self.tun_name.as_ref().ok_or(Error::InvalidConfig)?; 206 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 207 | unsafe { 208 | let mut req: ifaliasreq = mem::zeroed(); 209 | ptr::copy_nonoverlapping( 210 | tun_name.as_ptr() as *const c_char, 211 | req.ifra_name.as_mut_ptr(), 212 | tun_name.len(), 213 | ); 214 | 215 | req.ifra_addr = sockaddr_union::from((addr, 0)).addr; 216 | req.ifra_broadaddr = sockaddr_union::from((broadaddr, 0)).addr; 217 | req.ifra_mask = sockaddr_union::from((mask, 0)).addr; 218 | 219 | if let Err(err) = siocaifaddr(ctl.as_raw_fd(), &req) { 220 | return Err(std::io::Error::from(err).into()); 221 | } 222 | let route = Route { 223 | addr, 224 | netmask: mask, 225 | dest: broadaddr, 226 | }; 227 | if let Err(e) = self.set_route(route) { 228 | log::warn!("{e:?}"); 229 | } 230 | Ok(()) 231 | } 232 | } 233 | 234 | /// Split the interface into a `Reader` and `Writer`. 235 | pub fn split(self) -> (posix::Reader, posix::Writer) { 236 | (self.tun.reader, self.tun.writer) 237 | } 238 | 239 | /// Set non-blocking mode 240 | pub fn set_nonblock(&self) -> std::io::Result<()> { 241 | self.tun.set_nonblock() 242 | } 243 | 244 | fn set_route(&mut self, route: Route) -> Result<()> { 245 | if let Some(v) = &self.route { 246 | let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(v.netmask)) 247 | .map_err(|_| Error::InvalidConfig)?; 248 | let network = ipnet::Ipv4Net::new(v.addr, prefix_len) 249 | .map_err(|e| Error::InvalidConfig)? 250 | .network(); 251 | // command: route -n delete -net 10.0.0.0/24 10.0.0.1 252 | let args = [ 253 | "-n", 254 | "delete", 255 | "-net", 256 | &format!("{}/{}", network, prefix_len), 257 | &v.dest.to_string(), 258 | ]; 259 | run_command("route", &args)?; 260 | log::info!("route {}", args.join(" ")); 261 | } 262 | 263 | // command: route -n add -net 10.0.0.9/24 10.0.0.1 264 | let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(route.netmask)) 265 | .map_err(|_| Error::InvalidConfig)?; 266 | let args = [ 267 | "-n", 268 | "add", 269 | "-net", 270 | &format!("{}/{}", route.addr, prefix_len), 271 | &route.dest.to_string(), 272 | ]; 273 | run_command("route", &args)?; 274 | log::info!("route {}", args.join(" ")); 275 | self.route = Some(route); 276 | Ok(()) 277 | } 278 | 279 | /// Recv a packet from tun device 280 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 281 | self.tun.recv(buf) 282 | } 283 | 284 | /// Send a packet to tun device 285 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 286 | self.tun.send(buf) 287 | } 288 | } 289 | 290 | impl Read for Device { 291 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 292 | self.tun.read(buf) 293 | } 294 | } 295 | 296 | impl Write for Device { 297 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 298 | self.tun.write(buf) 299 | } 300 | 301 | fn flush(&mut self) -> std::io::Result<()> { 302 | self.tun.flush() 303 | } 304 | } 305 | 306 | impl AbstractDevice for Device { 307 | fn tun_index(&self) -> Result { 308 | let name = self.tun_name()?; 309 | Ok(posix::tun_name_to_index(&name)? as i32) 310 | } 311 | 312 | fn tun_name(&self) -> Result { 313 | self.tun_name.as_ref().cloned().ok_or(Error::InvalidConfig) 314 | } 315 | 316 | // XXX: Cannot set interface name on Darwin. 317 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 318 | Err(Error::InvalidName) 319 | } 320 | 321 | fn enabled(&mut self, value: bool) -> Result<()> { 322 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 323 | unsafe { 324 | let mut req = self.request()?; 325 | 326 | if let Err(err) = siocgifflags(ctl.as_raw_fd(), &mut req) { 327 | return Err(std::io::Error::from(err).into()); 328 | } 329 | 330 | if value { 331 | req.ifr_ifru.ifru_flags |= (IFF_UP | IFF_RUNNING) as c_short; 332 | } else { 333 | req.ifr_ifru.ifru_flags &= !(IFF_UP as c_short); 334 | } 335 | 336 | if let Err(err) = siocsifflags(ctl.as_raw_fd(), &req) { 337 | return Err(std::io::Error::from(err).into()); 338 | } 339 | 340 | Ok(()) 341 | } 342 | } 343 | 344 | fn address(&self) -> Result { 345 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 346 | unsafe { 347 | let mut req = self.request()?; 348 | if let Err(err) = siocgifaddr(ctl.as_raw_fd(), &mut req) { 349 | return Err(std::io::Error::from(err).into()); 350 | } 351 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 352 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 353 | } 354 | } 355 | 356 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 357 | let IpAddr::V4(value) = value else { 358 | unimplemented!("do not support IPv6 yet") 359 | }; 360 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 361 | unsafe { 362 | let mut req = self.request()?; 363 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_addr, OVERWRITE_SIZE); 364 | if let Err(err) = siocsifaddr(ctl.as_raw_fd(), &req) { 365 | return Err(std::io::Error::from(err).into()); 366 | } 367 | if let Some(mut route) = self.route { 368 | route.addr = value; 369 | self.set_route(route)?; 370 | } 371 | Ok(()) 372 | } 373 | } 374 | 375 | fn destination(&self) -> Result { 376 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 377 | unsafe { 378 | let mut req = self.request()?; 379 | if let Err(err) = siocgifdstaddr(ctl.as_raw_fd(), &mut req) { 380 | return Err(std::io::Error::from(err).into()); 381 | } 382 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_dstaddr); 383 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 384 | } 385 | } 386 | 387 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 388 | let IpAddr::V4(value) = value else { 389 | unimplemented!("do not support IPv6 yet") 390 | }; 391 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 392 | unsafe { 393 | let mut req = self.request()?; 394 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_dstaddr, OVERWRITE_SIZE); 395 | if let Err(err) = siocsifdstaddr(ctl.as_raw_fd(), &req) { 396 | return Err(std::io::Error::from(err).into()); 397 | } 398 | if let Some(mut route) = self.route { 399 | route.dest = value; 400 | self.set_route(route)?; 401 | } 402 | Ok(()) 403 | } 404 | } 405 | 406 | /// Question on macOS 407 | fn broadcast(&self) -> Result { 408 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 409 | unsafe { 410 | let mut req = self.request()?; 411 | if let Err(err) = siocgifbrdaddr(ctl.as_raw_fd(), &mut req) { 412 | return Err(std::io::Error::from(err).into()); 413 | } 414 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_broadaddr); 415 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 416 | } 417 | } 418 | 419 | /// Question on macOS 420 | fn set_broadcast(&mut self, value: IpAddr) -> Result<()> { 421 | let IpAddr::V4(value) = value else { 422 | unimplemented!("do not support IPv6 yet") 423 | }; 424 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 425 | unsafe { 426 | let mut req = self.request()?; 427 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_broadaddr, OVERWRITE_SIZE); 428 | if let Err(err) = siocsifbrdaddr(ctl.as_raw_fd(), &req) { 429 | return Err(std::io::Error::from(err).into()); 430 | } 431 | Ok(()) 432 | } 433 | } 434 | 435 | fn netmask(&self) -> Result { 436 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 437 | unsafe { 438 | let mut req = self.request()?; 439 | if let Err(err) = siocgifnetmask(ctl.as_raw_fd(), &mut req) { 440 | return Err(std::io::Error::from(err).into()); 441 | } 442 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 443 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 444 | } 445 | } 446 | 447 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 448 | let IpAddr::V4(value) = value else { 449 | unimplemented!("do not support IPv6 yet") 450 | }; 451 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 452 | unsafe { 453 | let mut req = self.request()?; 454 | // Note: Here should be `ifru_netmask`, but it is not defined in `ifreq`. 455 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_addr, OVERWRITE_SIZE); 456 | if let Err(err) = siocsifnetmask(ctl.as_raw_fd(), &req) { 457 | return Err(std::io::Error::from(err).into()); 458 | } 459 | if let Some(mut route) = self.route { 460 | route.netmask = value; 461 | self.set_route(route)?; 462 | } 463 | Ok(()) 464 | } 465 | } 466 | 467 | fn mtu(&self) -> Result { 468 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 469 | unsafe { 470 | let mut req = self.request()?; 471 | 472 | if let Err(err) = siocgifmtu(ctl.as_raw_fd(), &mut req) { 473 | return Err(std::io::Error::from(err).into()); 474 | } 475 | 476 | req.ifr_ifru 477 | .ifru_mtu 478 | .try_into() 479 | .map_err(|_| Error::TryFromIntError) 480 | } 481 | } 482 | 483 | fn set_mtu(&mut self, value: u16) -> Result<()> { 484 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 485 | unsafe { 486 | let mut req = self.request()?; 487 | req.ifr_ifru.ifru_mtu = value as i32; 488 | 489 | if let Err(err) = siocsifmtu(ctl.as_raw_fd(), &req) { 490 | return Err(std::io::Error::from(err).into()); 491 | } 492 | self.tun.set_mtu(value); 493 | Ok(()) 494 | } 495 | } 496 | 497 | fn packet_information(&self) -> bool { 498 | self.tun.packet_information() 499 | } 500 | } 501 | 502 | impl AsRawFd for Device { 503 | fn as_raw_fd(&self) -> RawFd { 504 | self.tun.as_raw_fd() 505 | } 506 | } 507 | 508 | impl IntoRawFd for Device { 509 | fn into_raw_fd(self) -> RawFd { 510 | self.tun.into_raw_fd() 511 | } 512 | } 513 | -------------------------------------------------------------------------------- /src/platform/macos/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! macOS specific functionality. 16 | 17 | pub mod sys; 18 | 19 | mod device; 20 | pub use self::device::Device; 21 | 22 | use crate::configuration::Configuration; 23 | use crate::error::Result; 24 | 25 | /// macOS-only interface configuration. 26 | #[derive(Copy, Clone, Debug)] 27 | pub struct PlatformConfig { 28 | pub(crate) packet_information: bool, 29 | } 30 | 31 | impl Default for PlatformConfig { 32 | fn default() -> Self { 33 | PlatformConfig { 34 | packet_information: true, // default is true in macOS 35 | } 36 | } 37 | } 38 | 39 | impl PlatformConfig { 40 | /// Enable or disable packet information, the first 4 bytes of 41 | /// each packet delivered from/to macOS underlying API is a header with flags and protocol type when enabled. 42 | /// 43 | /// - If we open an `utun` device, there always exist PI. 44 | /// 45 | /// - If we use `Network Extension` to build our App: 46 | /// 47 | /// - If get the fd from 48 | /// ```Objective-C 49 | /// int32_t tunFd = [[NEPacketTunnelProvider::packetFlow valueForKeyPath:@"socket.fileDescriptor"] intValue]; 50 | /// ``` 51 | /// there exist PI. 52 | /// 53 | /// - But if get packet from `[NEPacketTunnelProvider::packetFlow readPacketsWithCompletionHandler:]` 54 | /// and write packet via `[NEPacketTunnelProvider::packetFlow writePackets:withProtocols:]`, there is no PI. 55 | pub fn packet_information(&mut self, value: bool) -> &mut Self { 56 | self.packet_information = value; 57 | self 58 | } 59 | } 60 | 61 | /// Create a TUN device with the given name. 62 | pub fn create(configuration: &Configuration) -> Result { 63 | Device::new(configuration) 64 | } 65 | -------------------------------------------------------------------------------- /src/platform/macos/sys.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Bindings to internal macOS stuff. 16 | 17 | use libc::{c_char, c_uint, ifreq, sockaddr, IFNAMSIZ}; 18 | use nix::{ioctl_readwrite, ioctl_write_ptr}; 19 | 20 | pub const UTUN_CONTROL_NAME: &str = "com.apple.net.utun_control"; 21 | 22 | #[allow(non_camel_case_types)] 23 | #[repr(C)] 24 | #[derive(Copy, Clone)] 25 | pub struct ctl_info { 26 | pub ctl_id: c_uint, 27 | pub ctl_name: [c_char; 96], 28 | } 29 | 30 | #[allow(non_camel_case_types)] 31 | #[repr(C)] 32 | #[derive(Copy, Clone)] 33 | pub struct ifaliasreq { 34 | pub ifra_name: [c_char; IFNAMSIZ], 35 | pub ifra_addr: sockaddr, 36 | pub ifra_broadaddr: sockaddr, 37 | pub ifra_mask: sockaddr, 38 | } 39 | 40 | ioctl_readwrite!(ctliocginfo, b'N', 3, ctl_info); 41 | 42 | ioctl_write_ptr!(siocsifflags, b'i', 16, ifreq); 43 | ioctl_readwrite!(siocgifflags, b'i', 17, ifreq); 44 | 45 | ioctl_write_ptr!(siocsifaddr, b'i', 12, ifreq); 46 | ioctl_readwrite!(siocgifaddr, b'i', 33, ifreq); 47 | 48 | ioctl_write_ptr!(siocsifdstaddr, b'i', 14, ifreq); 49 | ioctl_readwrite!(siocgifdstaddr, b'i', 34, ifreq); 50 | 51 | ioctl_write_ptr!(siocsifbrdaddr, b'i', 19, ifreq); 52 | ioctl_readwrite!(siocgifbrdaddr, b'i', 35, ifreq); 53 | 54 | ioctl_write_ptr!(siocsifnetmask, b'i', 22, ifreq); 55 | ioctl_readwrite!(siocgifnetmask, b'i', 37, ifreq); 56 | 57 | ioctl_write_ptr!(siocsifmtu, b'i', 52, ifreq); 58 | ioctl_readwrite!(siocgifmtu, b'i', 51, ifreq); 59 | 60 | ioctl_write_ptr!(siocaifaddr, b'i', 26, ifaliasreq); 61 | ioctl_write_ptr!(siocdifaddr, b'i', 25, ifreq); 62 | -------------------------------------------------------------------------------- /src/platform/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Platform specific modules. 16 | 17 | #[cfg(unix)] 18 | pub(crate) mod posix; 19 | 20 | #[cfg(target_os = "linux")] 21 | pub(crate) mod linux; 22 | #[cfg(target_os = "linux")] 23 | pub use self::linux::{create, Device, PlatformConfig}; 24 | 25 | #[cfg(target_os = "freebsd")] 26 | pub(crate) mod freebsd; 27 | #[cfg(target_os = "freebsd")] 28 | pub use self::freebsd::{create, Device, PlatformConfig}; 29 | 30 | #[cfg(target_os = "macos")] 31 | pub(crate) mod macos; 32 | #[cfg(target_os = "macos")] 33 | pub use self::macos::{create, Device, PlatformConfig}; 34 | 35 | #[cfg(target_os = "ios")] 36 | pub(crate) mod ios; 37 | #[cfg(target_os = "ios")] 38 | pub use self::ios::{create, Device, PlatformConfig}; 39 | 40 | #[cfg(target_os = "android")] 41 | pub(crate) mod android; 42 | #[cfg(target_os = "android")] 43 | pub use self::android::{create, Device, PlatformConfig}; 44 | 45 | #[cfg(unix)] 46 | pub use crate::platform::posix::Tun; 47 | 48 | #[cfg(target_os = "windows")] 49 | pub(crate) mod windows; 50 | #[cfg(target_os = "windows")] 51 | pub use self::windows::{create, Device, PlatformConfig, Tun}; 52 | 53 | #[cfg(test)] 54 | mod test { 55 | use crate::configuration::Configuration; 56 | use crate::device::AbstractDevice; 57 | use std::net::Ipv4Addr; 58 | 59 | #[test] 60 | fn create() { 61 | let dev = super::create( 62 | Configuration::default() 63 | .tun_name("utun6") 64 | .address("192.168.50.1") 65 | .netmask("255.255.0.0") 66 | .mtu(crate::DEFAULT_MTU) 67 | .up(), 68 | ) 69 | .unwrap(); 70 | 71 | assert_eq!( 72 | "192.168.50.1".parse::().unwrap(), 73 | dev.address().unwrap() 74 | ); 75 | 76 | assert_eq!( 77 | "255.255.0.0".parse::().unwrap(), 78 | dev.netmask().unwrap() 79 | ); 80 | 81 | assert_eq!(crate::DEFAULT_MTU, dev.mtu().unwrap()); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/platform/posix/fd.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use crate::error::{Error, Result}; 16 | use libc::{self, fcntl, F_GETFL, F_SETFL, O_NONBLOCK}; 17 | use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; 18 | 19 | /// POSIX file descriptor support for `io` traits. 20 | pub(crate) struct Fd { 21 | pub(crate) inner: RawFd, 22 | close_fd_on_drop: bool, 23 | } 24 | 25 | impl Fd { 26 | pub fn new(value: RawFd, close_fd_on_drop: bool) -> Result { 27 | if value < 0 { 28 | return Err(Error::InvalidDescriptor); 29 | } 30 | Ok(Fd { 31 | inner: value, 32 | close_fd_on_drop, 33 | }) 34 | } 35 | 36 | /// Enable non-blocking mode 37 | pub fn set_nonblock(&self) -> std::io::Result<()> { 38 | match unsafe { fcntl(self.inner, F_SETFL, fcntl(self.inner, F_GETFL) | O_NONBLOCK) } { 39 | 0 => Ok(()), 40 | _ => Err(std::io::Error::last_os_error()), 41 | } 42 | } 43 | 44 | pub fn read(&self, buf: &mut [u8]) -> std::io::Result { 45 | let fd = self.as_raw_fd(); 46 | let amount = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) }; 47 | if amount < 0 { 48 | return Err(std::io::Error::last_os_error()); 49 | } 50 | Ok(amount as usize) 51 | } 52 | 53 | pub fn write(&self, buf: &[u8]) -> std::io::Result { 54 | let fd = self.as_raw_fd(); 55 | let amount = unsafe { libc::write(fd, buf.as_ptr() as *const _, buf.len()) }; 56 | if amount < 0 { 57 | return Err(std::io::Error::last_os_error()); 58 | } 59 | Ok(amount as usize) 60 | } 61 | } 62 | 63 | impl AsRawFd for Fd { 64 | fn as_raw_fd(&self) -> RawFd { 65 | self.inner 66 | } 67 | } 68 | 69 | impl IntoRawFd for Fd { 70 | fn into_raw_fd(mut self) -> RawFd { 71 | let fd = self.inner; 72 | self.inner = -1; 73 | fd 74 | } 75 | } 76 | 77 | impl Drop for Fd { 78 | fn drop(&mut self) { 79 | if self.close_fd_on_drop && self.inner >= 0 { 80 | unsafe { libc::close(self.inner) }; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/platform/posix/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! POSIX compliant support. 16 | 17 | mod sockaddr; 18 | #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))] 19 | pub(crate) use sockaddr::sockaddr_union; 20 | 21 | #[cfg(any(target_os = "linux", target_os = "macos"))] 22 | pub(crate) use sockaddr::ipaddr_to_sockaddr; 23 | 24 | mod fd; 25 | pub(crate) use self::fd::Fd; 26 | 27 | mod split; 28 | pub use self::split::{Reader, Tun, Writer}; 29 | 30 | #[allow(dead_code)] 31 | pub fn tun_name_to_index(name: impl AsRef) -> std::io::Result { 32 | let name_cstr = std::ffi::CString::new(name.as_ref()).map_err(|_| { 33 | std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid interface name") 34 | })?; 35 | let result = unsafe { libc::if_nametoindex(name_cstr.as_ptr()) }; 36 | if result == 0 { 37 | Err(std::io::Error::last_os_error()) 38 | } else { 39 | Ok(result as _) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/platform/posix/sockaddr.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | /// # Safety 16 | unsafe fn sockaddr_to_rs_addr(sa: &sockaddr_union) -> Option { 17 | match sa.addr_stor.ss_family as libc::c_int { 18 | libc::AF_INET => { 19 | let sa_in = sa.addr4; 20 | let ip = std::net::Ipv4Addr::from(sa_in.sin_addr.s_addr.to_ne_bytes()); 21 | let port = u16::from_be(sa_in.sin_port); 22 | Some(std::net::SocketAddr::new(ip.into(), port)) 23 | } 24 | libc::AF_INET6 => { 25 | let sa_in6 = sa.addr6; 26 | let ip = std::net::Ipv6Addr::from(sa_in6.sin6_addr.s6_addr); 27 | let port = u16::from_be(sa_in6.sin6_port); 28 | Some(std::net::SocketAddr::new(ip.into(), port)) 29 | } 30 | _ => None, 31 | } 32 | } 33 | 34 | fn rs_addr_to_sockaddr(addr: std::net::SocketAddr) -> sockaddr_union { 35 | match addr { 36 | std::net::SocketAddr::V4(ipv4) => { 37 | let mut addr: sockaddr_union = unsafe { std::mem::zeroed() }; 38 | #[cfg(any(target_os = "freebsd", target_os = "macos"))] 39 | { 40 | addr.addr4.sin_len = std::mem::size_of::() as u8; 41 | } 42 | addr.addr4.sin_family = libc::AF_INET as libc::sa_family_t; 43 | addr.addr4.sin_addr.s_addr = u32::from_ne_bytes(ipv4.ip().octets()); 44 | addr.addr4.sin_port = ipv4.port().to_be(); 45 | addr 46 | } 47 | std::net::SocketAddr::V6(ipv6) => { 48 | let mut addr: sockaddr_union = unsafe { std::mem::zeroed() }; 49 | #[cfg(any(target_os = "freebsd", target_os = "macos"))] 50 | { 51 | addr.addr6.sin6_len = std::mem::size_of::() as u8; 52 | } 53 | addr.addr6.sin6_family = libc::AF_INET6 as libc::sa_family_t; 54 | addr.addr6.sin6_addr.s6_addr = ipv6.ip().octets(); 55 | addr.addr6.sin6_port = ipv6.port().to_be(); 56 | addr 57 | } 58 | } 59 | } 60 | 61 | /// # Safety 62 | /// Fill the `addr` with the `src_addr` and `src_port`, the `size` should be the size of overwriting 63 | #[cfg(any(target_os = "linux", target_os = "macos"))] 64 | pub(crate) unsafe fn ipaddr_to_sockaddr( 65 | src_addr: T, 66 | src_port: u16, 67 | addr: &mut libc::sockaddr, 68 | size: usize, 69 | ) where 70 | T: Into, 71 | { 72 | let sa = rs_addr_to_sockaddr((src_addr.into(), src_port).into()); 73 | std::ptr::copy_nonoverlapping( 74 | &sa as *const _ as *const libc::c_void, 75 | addr as *mut _ as *mut libc::c_void, 76 | size.min(std::mem::size_of::()), 77 | ); 78 | } 79 | 80 | #[repr(C)] 81 | #[derive(Clone, Copy)] 82 | pub union sockaddr_union { 83 | pub addr_stor: libc::sockaddr_storage, 84 | pub addr6: libc::sockaddr_in6, 85 | pub addr4: libc::sockaddr_in, 86 | pub addr: libc::sockaddr, 87 | } 88 | 89 | impl From for sockaddr_union { 90 | fn from(addr: libc::sockaddr_storage) -> Self { 91 | sockaddr_union { addr_stor: addr } 92 | } 93 | } 94 | 95 | impl From for sockaddr_union { 96 | fn from(addr: libc::sockaddr_in6) -> Self { 97 | sockaddr_union { addr6: addr } 98 | } 99 | } 100 | 101 | impl From for sockaddr_union { 102 | fn from(addr: libc::sockaddr_in) -> Self { 103 | sockaddr_union { addr4: addr } 104 | } 105 | } 106 | 107 | impl From for sockaddr_union { 108 | fn from(addr: libc::sockaddr) -> Self { 109 | sockaddr_union { addr } 110 | } 111 | } 112 | 113 | impl From for sockaddr_union { 114 | fn from(addr: std::net::SocketAddr) -> Self { 115 | rs_addr_to_sockaddr(addr) 116 | } 117 | } 118 | 119 | impl TryFrom for std::net::SocketAddr { 120 | type Error = std::io::Error; 121 | 122 | fn try_from(addr: sockaddr_union) -> Result { 123 | unsafe { sockaddr_to_rs_addr(&addr).ok_or(std::io::ErrorKind::InvalidInput.into()) } 124 | } 125 | } 126 | 127 | impl> From<(T, u16)> for sockaddr_union { 128 | fn from((ip, port): (T, u16)) -> Self { 129 | let ip: std::net::IpAddr = ip.into(); 130 | rs_addr_to_sockaddr(std::net::SocketAddr::new(ip, port)) 131 | } 132 | } 133 | 134 | #[test] 135 | fn test_conversion() { 136 | let old = std::net::SocketAddr::new([127, 0, 0, 1].into(), 0x0208); 137 | let addr = rs_addr_to_sockaddr(old); 138 | unsafe { 139 | if cfg!(target_endian = "big") { 140 | assert_eq!(0x7f000001, addr.addr4.sin_addr.s_addr); 141 | assert_eq!(0x0208, addr.addr4.sin_port); 142 | } else if cfg!(target_endian = "little") { 143 | assert_eq!(0x0100007f, addr.addr4.sin_addr.s_addr); 144 | assert_eq!(0x0802, addr.addr4.sin_port); 145 | } else { 146 | unreachable!(); 147 | } 148 | }; 149 | let ip = unsafe { sockaddr_to_rs_addr(&addr).unwrap() }; 150 | assert_eq!(ip, old); 151 | 152 | let old = std::net::SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0x0208); 153 | let addr = rs_addr_to_sockaddr(old); 154 | let ip = unsafe { sockaddr_to_rs_addr(&addr).unwrap() }; 155 | assert_eq!(ip, old); 156 | 157 | let old = std::net::IpAddr::V4([10, 0, 0, 33].into()); 158 | let mut addr: sockaddr_union = unsafe { std::mem::zeroed() }; 159 | let size = std::mem::size_of::(); 160 | unsafe { ipaddr_to_sockaddr(old, 0x0208, &mut addr.addr, size) }; 161 | let ip = unsafe { sockaddr_to_rs_addr(&addr).unwrap() }; 162 | assert_eq!(ip, std::net::SocketAddr::new(old, 0x0208)); 163 | } 164 | -------------------------------------------------------------------------------- /src/platform/posix/split.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use crate::platform::posix::Fd; 16 | use crate::PACKET_INFORMATION_LENGTH as PIL; 17 | use bytes::BufMut; 18 | use std::io::{Read, Write}; 19 | use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; 20 | use std::sync::Arc; 21 | 22 | /// Infer the protocol based on the first nibble in the packet buffer. 23 | pub(crate) fn is_ipv6(buf: &[u8]) -> std::io::Result { 24 | use std::io::{Error, ErrorKind::InvalidData}; 25 | if buf.is_empty() { 26 | return Err(Error::new(InvalidData, "Zero-length data")); 27 | } 28 | match buf[0] >> 4 { 29 | 4 => Ok(false), 30 | 6 => Ok(true), 31 | p => Err(Error::new(InvalidData, format!("IP version {}", p))), 32 | } 33 | } 34 | 35 | pub(crate) fn generate_packet_information( 36 | _packet_information: bool, 37 | _ipv6: bool, 38 | ) -> Option<[u8; PIL]> { 39 | #[cfg(any(target_os = "linux", target_os = "android"))] 40 | const TUN_PROTO_IP6: [u8; PIL] = (libc::ETH_P_IPV6 as u32).to_be_bytes(); 41 | #[cfg(any(target_os = "linux", target_os = "android"))] 42 | const TUN_PROTO_IP4: [u8; PIL] = (libc::ETH_P_IP as u32).to_be_bytes(); 43 | 44 | #[cfg(any(target_os = "macos", target_os = "ios"))] 45 | const TUN_PROTO_IP6: [u8; PIL] = (libc::AF_INET6 as u32).to_be_bytes(); 46 | #[cfg(any(target_os = "macos", target_os = "ios"))] 47 | const TUN_PROTO_IP4: [u8; PIL] = (libc::AF_INET as u32).to_be_bytes(); 48 | 49 | // FIXME: Currently, the FreeBSD we test (FreeBSD-14.0-RELEASE) seems to have no PI. Here just a dummy. 50 | #[cfg(target_os = "freebsd")] 51 | const TUN_PROTO_IP6: [u8; PIL] = 0x86DD_u32.to_be_bytes(); 52 | #[cfg(target_os = "freebsd")] 53 | const TUN_PROTO_IP4: [u8; PIL] = 0x0800_u32.to_be_bytes(); 54 | 55 | #[cfg(unix)] 56 | if _packet_information { 57 | if _ipv6 { 58 | return Some(TUN_PROTO_IP6); 59 | } else { 60 | return Some(TUN_PROTO_IP4); 61 | } 62 | } 63 | None 64 | } 65 | 66 | /// Read-only end for a file descriptor. 67 | pub struct Reader { 68 | pub(crate) fd: Arc, 69 | pub(crate) offset: usize, 70 | pub(crate) buf: Vec, 71 | pub(crate) mtu: u16, 72 | } 73 | 74 | impl Reader { 75 | pub(crate) fn set_mtu(&mut self, value: u16) { 76 | self.mtu = value; 77 | self.buf.resize(value as usize + self.offset, 0); 78 | } 79 | 80 | pub(crate) fn recv(&self, mut in_buf: &mut [u8]) -> std::io::Result { 81 | const STACK_BUF_LEN: usize = crate::DEFAULT_MTU as usize + PIL; 82 | let in_buf_len = in_buf.len() + self.offset; 83 | 84 | // The following logic is to prevent dynamically allocating Vec on every recv 85 | // As long as the MTU is set to value lesser than 1500, this api uses `stack_buf` 86 | // and avoids `Vec` allocation 87 | 88 | let mut dynamic_buf: Vec; 89 | let mut fixed_buf: [u8; STACK_BUF_LEN]; 90 | let local_buf = if in_buf_len > STACK_BUF_LEN && self.offset != 0 { 91 | dynamic_buf = vec![0u8; in_buf_len]; 92 | &mut dynamic_buf[..] 93 | } else { 94 | fixed_buf = [0u8; STACK_BUF_LEN]; 95 | &mut fixed_buf 96 | }; 97 | 98 | let either_buf = if self.offset != 0 { 99 | &mut *local_buf 100 | } else { 101 | &mut *in_buf 102 | }; 103 | let amount = self.fd.read(either_buf)?; 104 | if self.offset != 0 { 105 | in_buf.put_slice(&local_buf[self.offset..amount]); 106 | } 107 | Ok(amount - self.offset) 108 | } 109 | } 110 | 111 | impl Read for Reader { 112 | fn read(&mut self, mut buf: &mut [u8]) -> std::io::Result { 113 | let either_buf = if self.offset != 0 { 114 | let len = buf.len() + self.offset; 115 | if len > self.buf.len() { 116 | self.buf.resize(len, 0_u8); 117 | } 118 | &mut self.buf[..len] 119 | } else { 120 | &mut *buf 121 | }; 122 | let amount = self.fd.read(either_buf)?; 123 | if self.offset != 0 { 124 | buf.put_slice(&self.buf[self.offset..amount]); 125 | } 126 | Ok(amount - self.offset) 127 | } 128 | } 129 | 130 | impl AsRawFd for Reader { 131 | fn as_raw_fd(&self) -> RawFd { 132 | self.fd.as_raw_fd() 133 | } 134 | } 135 | 136 | /// Write-only end for a file descriptor. 137 | pub struct Writer { 138 | pub(crate) fd: Arc, 139 | pub(crate) offset: usize, 140 | pub(crate) buf: Vec, 141 | pub(crate) mtu: u16, 142 | } 143 | 144 | impl Writer { 145 | pub(crate) fn set_mtu(&mut self, value: u16) { 146 | self.mtu = value; 147 | self.buf.resize(value as usize + self.offset, 0); 148 | } 149 | 150 | pub(crate) fn send(&self, in_buf: &[u8]) -> std::io::Result { 151 | const STACK_BUF_LEN: usize = crate::DEFAULT_MTU as usize + PIL; 152 | let in_buf_len = in_buf.len() + self.offset; 153 | 154 | // The following logic is to prevent dynamically allocating Vec on every send 155 | // As long as the MTU is set to value lesser than 1500, this api uses `stack_buf` 156 | // and avoids `Vec` allocation 157 | let mut dynamic_buf: Vec; 158 | let mut fixed_buf: [u8; STACK_BUF_LEN]; 159 | let local_buf = if in_buf_len > STACK_BUF_LEN && self.offset != 0 { 160 | dynamic_buf = vec![0_u8; in_buf_len]; 161 | &mut dynamic_buf[..] 162 | } else { 163 | fixed_buf = [0_u8; STACK_BUF_LEN]; 164 | &mut fixed_buf 165 | }; 166 | 167 | let either_buf = if self.offset != 0 { 168 | let ipv6 = is_ipv6(in_buf)?; 169 | if let Some(header) = generate_packet_information(true, ipv6) { 170 | (&mut local_buf[..self.offset]).put_slice(header.as_ref()); 171 | (&mut local_buf[self.offset..in_buf_len]).put_slice(in_buf); 172 | local_buf 173 | } else { 174 | in_buf 175 | } 176 | } else { 177 | in_buf 178 | }; 179 | let amount = self.fd.write(either_buf)?; 180 | Ok(amount - self.offset) 181 | } 182 | } 183 | 184 | impl Write for Writer { 185 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 186 | let buf = if self.offset != 0 { 187 | let ipv6 = is_ipv6(buf)?; 188 | if let Some(header) = generate_packet_information(true, ipv6) { 189 | let len = self.offset + buf.len(); 190 | if len > self.buf.len() { 191 | self.buf.resize(len, 0_u8); 192 | } 193 | (&mut self.buf[..self.offset]).put_slice(header.as_ref()); 194 | (&mut self.buf[self.offset..len]).put_slice(buf); 195 | &self.buf[..len] 196 | } else { 197 | buf 198 | } 199 | } else { 200 | buf 201 | }; 202 | let amount = self.fd.write(buf)?; 203 | Ok(amount - self.offset) 204 | } 205 | 206 | fn flush(&mut self) -> std::io::Result<()> { 207 | Ok(()) 208 | } 209 | } 210 | 211 | impl AsRawFd for Writer { 212 | fn as_raw_fd(&self) -> RawFd { 213 | self.fd.as_raw_fd() 214 | } 215 | } 216 | 217 | pub struct Tun { 218 | pub(crate) reader: Reader, 219 | pub(crate) writer: Writer, 220 | pub(crate) mtu: u16, 221 | pub(crate) packet_information: bool, 222 | } 223 | 224 | impl Tun { 225 | pub(crate) fn new(fd: Fd, mtu: u16, packet_information: bool) -> Self { 226 | let fd = Arc::new(fd); 227 | let offset = if packet_information { PIL } else { 0 }; 228 | Self { 229 | reader: Reader { 230 | fd: fd.clone(), 231 | offset, 232 | buf: vec![0; mtu as usize + offset], 233 | mtu, 234 | }, 235 | writer: Writer { 236 | fd, 237 | offset, 238 | buf: vec![0; mtu as usize + offset], 239 | mtu, 240 | }, 241 | mtu, 242 | packet_information, 243 | } 244 | } 245 | 246 | pub fn set_nonblock(&self) -> std::io::Result<()> { 247 | self.reader.fd.set_nonblock() 248 | } 249 | 250 | pub fn set_mtu(&mut self, value: u16) { 251 | self.mtu = value; 252 | self.reader.set_mtu(value); 253 | self.writer.set_mtu(value); 254 | } 255 | 256 | pub fn mtu(&self) -> u16 { 257 | self.mtu 258 | } 259 | 260 | pub fn packet_information(&self) -> bool { 261 | self.packet_information 262 | } 263 | 264 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 265 | self.reader.recv(buf) 266 | } 267 | 268 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 269 | self.writer.send(buf) 270 | } 271 | } 272 | 273 | impl Read for Tun { 274 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 275 | self.reader.read(buf) 276 | } 277 | } 278 | 279 | impl Write for Tun { 280 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 281 | self.writer.write(buf) 282 | } 283 | 284 | fn flush(&mut self) -> std::io::Result<()> { 285 | self.writer.flush() 286 | } 287 | } 288 | 289 | impl AsRawFd for Tun { 290 | fn as_raw_fd(&self) -> RawFd { 291 | self.reader.as_raw_fd() 292 | } 293 | } 294 | 295 | impl IntoRawFd for Tun { 296 | fn into_raw_fd(self) -> RawFd { 297 | drop(self.writer); 298 | // guarantee fd is the unique owner such that Arc::into_inner can return some 299 | let fd = Arc::into_inner(self.reader.fd).unwrap(); // panic if accident 300 | fd.into_raw_fd() 301 | } 302 | } 303 | -------------------------------------------------------------------------------- /src/platform/windows/device.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | use std::io::{Read, Write}; 16 | use std::net::{IpAddr, Ipv4Addr}; 17 | use std::sync::Arc; 18 | 19 | use crate::configuration::Configuration; 20 | use crate::device::AbstractDevice; 21 | use crate::error::{Error, Result}; 22 | use crate::run_command::run_command; 23 | use crate::Layer; 24 | use wintun_bindings::{load_from_path, Adapter, Session, MAX_RING_CAPACITY}; 25 | 26 | pub enum Driver { 27 | Tun(Tun), 28 | #[allow(dead_code)] 29 | Tap(()), 30 | } 31 | /// A TUN device using the wintun driver. 32 | pub struct Device { 33 | pub(crate) driver: Driver, 34 | mtu: u16, 35 | } 36 | 37 | impl Device { 38 | /// Create a new `Device` for the given `Configuration`. 39 | pub fn new(config: &Configuration) -> Result { 40 | let layer = config.layer.unwrap_or(Layer::L3); 41 | if layer == Layer::L3 { 42 | let wintun_file = &config.platform_config.wintun_file; 43 | let wintun = unsafe { load_from_path(wintun_file)? }; 44 | let tun_name = config.tun_name.as_deref().unwrap_or("wintun"); 45 | let guid = config.platform_config.device_guid; 46 | let adapter = match Adapter::open(&wintun, tun_name) { 47 | Ok(a) => a, 48 | Err(_) => Adapter::create(&wintun, tun_name, tun_name, guid)?, 49 | }; 50 | if let Some(metric) = config.metric { 51 | // command: netsh interface ip set interface {index} metric={metric} 52 | let i = adapter.get_adapter_index()?.to_string(); 53 | let m = format!("metric={}", metric); 54 | run_command("netsh", &["interface", "ip", "set", "interface", &i, &m])?; 55 | } 56 | let address = config 57 | .address 58 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 2))); 59 | let mask = config 60 | .netmask 61 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 0))); 62 | let gateway = config.destination.map(IpAddr::from); 63 | adapter.set_network_addresses_tuple(address, mask, gateway)?; 64 | if let Some(dns_servers) = &config.platform_config.dns_servers { 65 | adapter.set_dns_servers(dns_servers)?; 66 | } 67 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 68 | 69 | let capacity = config.ring_capacity.unwrap_or(MAX_RING_CAPACITY); 70 | let session = adapter.start_session(capacity)?; 71 | adapter.set_mtu(mtu as _)?; 72 | let mut device = Device { 73 | driver: Driver::Tun(Tun { session }), 74 | mtu, 75 | }; 76 | 77 | // This is not needed since we use netsh to set the address. 78 | device.configure(config)?; 79 | 80 | Ok(device) 81 | } else if layer == Layer::L2 { 82 | todo!() 83 | } else { 84 | panic!("unknow layer {:?}", layer); 85 | } 86 | } 87 | 88 | pub fn split(self) -> (Reader, Writer) { 89 | match self.driver { 90 | Driver::Tun(tun) => { 91 | let tun = Arc::new(tun); 92 | (Reader(tun.clone()), Writer(tun)) 93 | } 94 | Driver::Tap(_) => unimplemented!(), 95 | } 96 | } 97 | 98 | /// Recv a packet from tun device 99 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 100 | match &self.driver { 101 | Driver::Tun(tun) => tun.recv(buf), 102 | Driver::Tap(_tap) => unimplemented!(), 103 | } 104 | } 105 | 106 | /// Send a packet to tun device 107 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 108 | match &self.driver { 109 | Driver::Tun(tun) => tun.send(buf), 110 | Driver::Tap(_tap) => unimplemented!(), 111 | } 112 | } 113 | } 114 | 115 | impl Read for Device { 116 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 117 | match &mut self.driver { 118 | Driver::Tun(tun) => tun.read(buf), 119 | Driver::Tap(_tap) => unimplemented!(), 120 | } 121 | } 122 | } 123 | 124 | impl Write for Device { 125 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 126 | match &mut self.driver { 127 | Driver::Tun(tun) => tun.write(buf), 128 | Driver::Tap(_tap) => unimplemented!(), 129 | } 130 | } 131 | 132 | fn flush(&mut self) -> std::io::Result<()> { 133 | match &mut self.driver { 134 | Driver::Tun(tun) => tun.flush(), 135 | Driver::Tap(_tap) => unimplemented!(), 136 | } 137 | } 138 | } 139 | 140 | impl AbstractDevice for Device { 141 | fn tun_index(&self) -> Result { 142 | match &self.driver { 143 | Driver::Tun(tun) => Ok(tun.session.get_adapter().get_adapter_index()? as i32), 144 | Driver::Tap(_tap) => Err(Error::NotImplemented), 145 | } 146 | } 147 | 148 | fn tun_name(&self) -> Result { 149 | match &self.driver { 150 | Driver::Tun(tun) => Ok(tun.session.get_adapter().get_name()?), 151 | Driver::Tap(_tap) => unimplemented!(), 152 | } 153 | } 154 | 155 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 156 | match &self.driver { 157 | Driver::Tun(tun) => { 158 | tun.session.get_adapter().set_name(value)?; 159 | Ok(()) 160 | } 161 | Driver::Tap(_tap) => unimplemented!(), 162 | } 163 | } 164 | 165 | fn enabled(&mut self, _value: bool) -> Result<()> { 166 | Ok(()) 167 | } 168 | 169 | fn address(&self) -> Result { 170 | match &self.driver { 171 | Driver::Tun(tun) => { 172 | let addresses = tun.session.get_adapter().get_addresses()?; 173 | addresses 174 | .iter() 175 | .find_map(|a| match a { 176 | std::net::IpAddr::V4(a) => Some(std::net::IpAddr::V4(*a)), 177 | _ => None, 178 | }) 179 | .ok_or(Error::InvalidConfig) 180 | } 181 | Driver::Tap(_tap) => unimplemented!(), 182 | } 183 | } 184 | 185 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 186 | let IpAddr::V4(value) = value else { 187 | unimplemented!("do not support IPv6 yet") 188 | }; 189 | match &self.driver { 190 | Driver::Tun(tun) => { 191 | tun.session.get_adapter().set_address(value)?; 192 | Ok(()) 193 | } 194 | Driver::Tap(_tap) => unimplemented!(), 195 | } 196 | } 197 | 198 | fn destination(&self) -> Result { 199 | // It's just the default gateway in windows. 200 | match &self.driver { 201 | Driver::Tun(tun) => tun 202 | .session 203 | .get_adapter() 204 | .get_gateways()? 205 | .iter() 206 | .find_map(|a| match a { 207 | std::net::IpAddr::V4(a) => Some(std::net::IpAddr::V4(*a)), 208 | _ => None, 209 | }) 210 | .ok_or(Error::InvalidConfig), 211 | Driver::Tap(_tap) => unimplemented!(), 212 | } 213 | } 214 | 215 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 216 | let IpAddr::V4(value) = value else { 217 | unimplemented!("do not support IPv6 yet") 218 | }; 219 | // It's just set the default gateway in windows. 220 | match &self.driver { 221 | Driver::Tun(tun) => { 222 | tun.session.get_adapter().set_gateway(Some(value))?; 223 | Ok(()) 224 | } 225 | Driver::Tap(_tap) => unimplemented!(), 226 | } 227 | } 228 | 229 | fn broadcast(&self) -> Result { 230 | Err(Error::NotImplemented) 231 | } 232 | 233 | fn set_broadcast(&mut self, value: IpAddr) -> Result<()> { 234 | log::debug!("set_broadcast {} is not need", value); 235 | Ok(()) 236 | } 237 | 238 | fn netmask(&self) -> Result { 239 | let current_addr = self.address()?; 240 | match &self.driver { 241 | Driver::Tun(tun) => tun 242 | .session 243 | .get_adapter() 244 | .get_netmask_of_address(¤t_addr) 245 | .map_err(Error::WintunError), 246 | Driver::Tap(_tap) => unimplemented!(), 247 | } 248 | } 249 | 250 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 251 | let IpAddr::V4(value) = value else { 252 | unimplemented!("do not support IPv6 yet") 253 | }; 254 | match &self.driver { 255 | Driver::Tun(tun) => { 256 | tun.session.get_adapter().set_netmask(value)?; 257 | Ok(()) 258 | } 259 | Driver::Tap(_tap) => unimplemented!(), 260 | } 261 | } 262 | 263 | /// The return value is always `Ok(65535)` due to wintun 264 | fn mtu(&self) -> Result { 265 | Ok(self.mtu) 266 | } 267 | 268 | /// This setting has no effect since the mtu of wintun is always 65535 269 | fn set_mtu(&mut self, mtu: u16) -> Result<()> { 270 | match &self.driver { 271 | Driver::Tun(tun) => { 272 | tun.session.get_adapter().set_mtu(mtu as _)?; 273 | self.mtu = mtu; 274 | Ok(()) 275 | } 276 | Driver::Tap(_tap) => unimplemented!(), 277 | } 278 | } 279 | 280 | fn packet_information(&self) -> bool { 281 | // Note: wintun does not support packet information 282 | false 283 | } 284 | } 285 | 286 | pub struct Tun { 287 | session: Arc, 288 | } 289 | 290 | impl Tun { 291 | pub fn get_session(&self) -> Arc { 292 | self.session.clone() 293 | } 294 | fn read_by_ref(&self, mut buf: &mut [u8]) -> std::io::Result { 295 | use std::io::{Error, ErrorKind::ConnectionAborted}; 296 | match self.session.receive_blocking() { 297 | Ok(pkt) => match std::io::copy(&mut pkt.bytes(), &mut buf) { 298 | Ok(n) => Ok(n as usize), 299 | Err(e) => Err(e), 300 | }, 301 | Err(e) => Err(Error::new(ConnectionAborted, e)), 302 | } 303 | } 304 | fn write_by_ref(&self, mut buf: &[u8]) -> std::io::Result { 305 | use std::io::{Error, ErrorKind::OutOfMemory}; 306 | let size = buf.len(); 307 | match self.session.allocate_send_packet(size as u16) { 308 | Err(e) => Err(Error::new(OutOfMemory, e)), 309 | Ok(mut packet) => match std::io::copy(&mut buf, &mut packet.bytes_mut()) { 310 | Ok(s) => { 311 | self.session.send_packet(packet); 312 | Ok(s as usize) 313 | } 314 | Err(e) => Err(e), 315 | }, 316 | } 317 | } 318 | 319 | /// Recv a packet from tun device 320 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 321 | self.read_by_ref(buf) 322 | } 323 | 324 | /// Send a packet to tun device 325 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 326 | self.write_by_ref(buf) 327 | } 328 | } 329 | 330 | impl Read for Tun { 331 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 332 | self.read_by_ref(buf) 333 | } 334 | } 335 | 336 | impl Write for Tun { 337 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 338 | self.write_by_ref(buf) 339 | } 340 | 341 | fn flush(&mut self) -> std::io::Result<()> { 342 | Ok(()) 343 | } 344 | } 345 | 346 | // impl Drop for Tun { 347 | // fn drop(&mut self) { 348 | // // The session has implemented drop 349 | // if let Err(err) = self.session.shutdown() { 350 | // log::error!("failed to shutdown session: {:?}", err); 351 | // } 352 | // } 353 | // } 354 | 355 | #[repr(transparent)] 356 | pub struct Reader(Arc); 357 | 358 | impl Read for Reader { 359 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 360 | self.0.read_by_ref(buf) 361 | } 362 | } 363 | 364 | #[repr(transparent)] 365 | pub struct Writer(Arc); 366 | 367 | impl Write for Writer { 368 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 369 | self.0.write_by_ref(buf) 370 | } 371 | 372 | fn flush(&mut self) -> std::io::Result<()> { 373 | Ok(()) 374 | } 375 | } 376 | -------------------------------------------------------------------------------- /src/platform/windows/mod.rs: -------------------------------------------------------------------------------- 1 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 2 | // Version 2, December 2004 3 | // 4 | // Copyleft (ↄ) meh. | http://meh.schizofreni.co 5 | // 6 | // Everyone is permitted to copy and distribute verbatim or modified 7 | // copies of this license document, and changing it is allowed as long 8 | // as the name is changed. 9 | // 10 | // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 11 | // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 12 | // 13 | // 0. You just DO WHAT THE FUCK YOU WANT TO. 14 | 15 | //! Windows specific functionality. 16 | 17 | mod device; 18 | 19 | use crate::configuration::Configuration; 20 | use crate::error::Result; 21 | #[cfg(feature = "async")] 22 | pub use device::Driver; 23 | pub use device::{Device, Tun}; 24 | use std::ffi::OsString; 25 | 26 | /// Windows-only interface configuration. 27 | #[derive(Clone, Debug)] 28 | pub struct PlatformConfig { 29 | pub(crate) device_guid: Option, 30 | pub(crate) wintun_file: OsString, 31 | pub(crate) dns_servers: Option>, 32 | } 33 | 34 | impl Default for PlatformConfig { 35 | fn default() -> Self { 36 | Self { 37 | device_guid: None, 38 | wintun_file: "wintun.dll".into(), 39 | dns_servers: None, 40 | } 41 | } 42 | } 43 | 44 | impl PlatformConfig { 45 | pub fn device_guid(&mut self, device_guid: u128) { 46 | log::trace!("Windows configuration device GUID"); 47 | self.device_guid = Some(device_guid); 48 | } 49 | 50 | /// Use a custom path to the wintun.dll instead of looking in the working directory. 51 | /// Security note: It is up to the caller to ensure that the library can be safely loaded from 52 | /// the indicated path. 53 | /// 54 | /// [`wintun_file`](PlatformConfig::wintun_file) likes "path/to/wintun" or "path/to/wintun.dll". 55 | pub fn wintun_file>(&mut self, wintun_file: S) { 56 | self.wintun_file = wintun_file.into(); 57 | } 58 | 59 | pub fn dns_servers(&mut self, dns_servers: &[std::net::IpAddr]) { 60 | self.dns_servers = Some(dns_servers.to_vec()); 61 | } 62 | } 63 | 64 | /// Create a TUN device with the given name. 65 | pub fn create(configuration: &Configuration) -> Result { 66 | Device::new(configuration) 67 | } 68 | -------------------------------------------------------------------------------- /src/run_command.rs: -------------------------------------------------------------------------------- 1 | /// Runs a command and returns an error if the command fails, just convenience for users. 2 | #[doc(hidden)] 3 | #[allow(dead_code)] 4 | pub fn run_command(command: &str, args: &[&str]) -> std::io::Result> { 5 | let full_cmd = format!("{} {}", command, args.join(" ")); 6 | log::debug!("Running command: \"{full_cmd}\"..."); 7 | let out = match std::process::Command::new(command).args(args).output() { 8 | Ok(out) => out, 9 | Err(e) => { 10 | log::error!("Run command: \"{full_cmd}\" failed with: {e}"); 11 | return Err(e); 12 | } 13 | }; 14 | if !out.status.success() { 15 | let err = String::from_utf8_lossy(if out.stderr.is_empty() { 16 | &out.stdout 17 | } else { 18 | &out.stderr 19 | }); 20 | let info = format!("Run command: \"{full_cmd}\" failed with {err}"); 21 | log::error!("{}", info); 22 | return Err(std::io::Error::new(std::io::ErrorKind::Other, info)); 23 | } 24 | Ok(out.stdout) 25 | } 26 | --------------------------------------------------------------------------------