├── .cargo └── config.toml ├── .github ├── dependabot.yml └── workflows │ ├── freebsd.yml │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── README.md ├── examples ├── dev-config.rs ├── ping-tun.rs ├── read-async-codec.rs ├── read-async.rs ├── read.rs ├── split-async.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 ├── ohos │ ├── device.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 = ["aarch64-apple-tvos"] 6 | # target = ["x86_64-unknown-linux-musl"] 7 | # target = ["x86_64-unknown-linux-gnu"] 8 | # target = ["aarch64-linux-android"] # arm64-v8a 9 | # target = ["armv7-linux-androideabi"] # armeabi-v7a 10 | # target = ["i686-linux-android"] # x86 11 | # target = ["x86_64-linux-android"] # x86_64 12 | # target = ["aarch64-apple-ios"] 13 | # target = ["x86_64-pc-windows-msvc"] 14 | # target = ["x86_64-apple-darwin"] 15 | # target = ["x86_64-unknown-freebsd"] 16 | -------------------------------------------------------------------------------- /.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/freebsd.yml: -------------------------------------------------------------------------------- 1 | name: TestFreeBSD 2 | 3 | on: 4 | [push, pull_request] 5 | 6 | concurrency: 7 | group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }} 8 | cancel-in-progress: true 9 | 10 | jobs: 11 | test: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | toolchain: ["stable"] # ["nightly", "beta", "stable"] # 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Test in FreeBSD 19 | id: test 20 | uses: vmactions/freebsd-vm@v1 21 | with: 22 | usesh: true 23 | sync: rsync 24 | copyback: false 25 | prepare: | 26 | pkg install -y curl pkgconf glib 27 | curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf > install.sh 28 | chmod +x install.sh 29 | ./install.sh -y --default-toolchain ${{ matrix.toolchain }} 30 | run: | 31 | . "$HOME/.cargo/env" 32 | set -ex 33 | 34 | # Add feature "nightly" if toolchain is nightly 35 | if [ "${{ matrix.toolchain }}" = "nightly" ]; then 36 | ARGS="$ARGS --features nightly" 37 | fi 38 | 39 | rustup show 40 | 41 | RUST_BACKTRACE=1 cargo +${{ matrix.toolchain }} fmt --all -- --check 42 | RUST_BACKTRACE=1 cargo +${{ matrix.toolchain }} clippy --all-features -- -D warnings 43 | RUST_BACKTRACE=1 cargo +${{ matrix.toolchain }} build --all-features 44 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Push or PR 2 | 3 | on: 4 | [push, pull_request, workflow_dispatch] 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 | - uses: dtolnay/rust-toolchain@stable 21 | - name: rustfmt 22 | if: ${{ !cancelled() }} 23 | run: cargo fmt --all -- --check 24 | - name: check 25 | if: ${{ !cancelled() }} 26 | run: cargo check --verbose 27 | - name: clippy 28 | if: ${{ !cancelled() }} 29 | run: cargo clippy --all-targets --all-features -- -D warnings 30 | - name: Build 31 | if: ${{ !cancelled() }} 32 | run: | 33 | cargo build --verbose --examples --tests --all-features --features="async tokio/rt-multi-thread" 34 | cargo clean 35 | cargo build --verbose --examples --tests --no-default-features 36 | - name: Abort on error 37 | if: ${{ failure() }} 38 | run: echo "Some of jobs failed" && false 39 | 40 | build_n_test_android: 41 | strategy: 42 | fail-fast: false 43 | runs-on: ubuntu-latest 44 | 45 | steps: 46 | - uses: actions/checkout@v4 47 | - uses: dtolnay/rust-toolchain@stable 48 | - name: Install cargo ndk and rust compiler for android target 49 | if: ${{ !cancelled() }} 50 | run: | 51 | cargo install --locked cargo-ndk 52 | rustup target add x86_64-linux-android 53 | - name: clippy 54 | if: ${{ !cancelled() }} 55 | run: cargo ndk -t x86_64 clippy --all-features --features="async tokio/rt-multi-thread" -- -D warnings 56 | - name: Build 57 | if: ${{ !cancelled() }} 58 | run: | 59 | cargo ndk -t x86_64 rustc --verbose --all-features --features="async tokio/rt-multi-thread" --lib --crate-type=cdylib 60 | - name: Abort on error 61 | if: ${{ failure() }} 62 | run: echo "Android build job failed" && false 63 | 64 | build_n_test_ios: 65 | strategy: 66 | fail-fast: false 67 | runs-on: macos-latest 68 | 69 | steps: 70 | - uses: actions/checkout@v4 71 | - uses: dtolnay/rust-toolchain@stable 72 | - name: Install cargo lipo and rust compiler for ios target 73 | if: ${{ !cancelled() }} 74 | run: | 75 | cargo install --locked cargo-lipo 76 | rustup target add x86_64-apple-ios aarch64-apple-ios 77 | - name: clippy 78 | if: ${{ !cancelled() }} 79 | run: cargo clippy --target x86_64-apple-ios --all-features --features="async tokio/rt-multi-thread" -- -D warnings 80 | - name: Build 81 | if: ${{ !cancelled() }} 82 | run: | 83 | cargo lipo --verbose --all-features --features="async tokio/rt-multi-thread" 84 | - name: Abort on error 85 | if: ${{ failure() }} 86 | run: echo "iOS build job failed" && false 87 | 88 | build_n_test_tvos: 89 | strategy: 90 | matrix: 91 | target: [aarch64-apple-tvos, aarch64-apple-tvos-sim, x86_64-apple-tvos] 92 | fail-fast: false 93 | runs-on: macos-latest 94 | 95 | steps: 96 | - uses: actions/checkout@v4 97 | - uses: dtolnay/rust-toolchain@nightly 98 | with: 99 | components: clippy, rust-src 100 | - name: clippy 101 | if: ${{ !cancelled() }} 102 | run: cargo +nightly clippy -Zbuild-std --target ${{matrix.target}} --all-features --features="async tokio/rt-multi-thread" -- -D warnings 103 | - name: Build 104 | if: ${{ !cancelled() }} 105 | run: | 106 | cargo +nightly build -Zbuild-std --verbose --target ${{matrix.target}} --all-features --features="async tokio/rt-multi-thread" 107 | - name: Abort on error 108 | if: ${{ failure() }} 109 | run: echo "tvOS build job failed" && false 110 | 111 | build_n_test_openharmony: 112 | strategy: 113 | matrix: 114 | target: [aarch64-unknown-linux-ohos, armv7-unknown-linux-ohos, x86_64-unknown-linux-ohos] 115 | fail-fast: false 116 | runs-on: ubuntu-latest 117 | 118 | steps: 119 | - uses: actions/checkout@v4 120 | - uses: openharmony-rs/setup-ohos-sdk@v0.2.1 121 | id: setup-ohos 122 | with: 123 | version: "5.0.1" 124 | - name: Install ohrs and rust compiler for ohos target 125 | if: ${{ !cancelled() }} 126 | run: | 127 | cargo install --locked ohrs 128 | rustup target add ${{ matrix.target }} 129 | - name: fmt & clippy 130 | if: ${{ !cancelled() }} 131 | run: | 132 | cargo fmt --all -- --check 133 | ohrs cargo --disable-target -- clippy --target ${{matrix.target}} --all-features --features="async tokio/rt-multi-thread" -- -D warnings 134 | - name: Build 135 | if: ${{ !cancelled() }} 136 | run: | 137 | ohrs cargo --disable-target -- rustc --target ${{matrix.target}} --verbose --all-features --features="async tokio/rt-multi-thread" --lib --crate-type=cdylib 138 | - name: Abort on error 139 | if: ${{ failure() }} 140 | run: echo "OpenHarmony build job failed" && false 141 | 142 | semver: 143 | name: Check semver 144 | strategy: 145 | fail-fast: false 146 | matrix: 147 | os: [ubuntu-latest, macos-latest, windows-latest] 148 | runs-on: ${{ matrix.os }} 149 | steps: 150 | - uses: actions/checkout@v4 151 | - uses: dtolnay/rust-toolchain@stable 152 | - name: Check semver 153 | if: ${{ !cancelled() }} 154 | uses: obi1kenobi/cargo-semver-checks-action@v2 155 | - name: Abort on error 156 | if: ${{ failure() }} 157 | run: echo "Semver check failed" && false 158 | -------------------------------------------------------------------------------- /.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 = "tun" 3 | version = "0.8.0" 4 | edition = "2024" 5 | authors = ["meh. ", "@ssrlive"] 6 | license = "WTFPL" 7 | description = "TUN device creation and handling." 8 | repository = "https://github.com/meh/rust-tun" 9 | keywords = ["tun", "network", "tunnel", "bindings"] 10 | # rust-version = "1.85" 11 | 12 | [package.metadata.docs.rs] 13 | all-features = true 14 | 15 | [lib] 16 | crate-type = ["staticlib", "lib"] 17 | 18 | [features] 19 | # default = ["async"] 20 | async = [ 21 | "tokio", 22 | "futures-core", 23 | "futures", 24 | "tokio-util", 25 | "wintun-bindings/async", 26 | ] 27 | 28 | [dependencies] 29 | bytes = { version = "1" } 30 | cfg-if = "1" 31 | futures-core = { version = "0.3", optional = true } 32 | libc = { version = "0.2", features = ["extra_traits"] } 33 | log = "0.4" 34 | thiserror = "2" 35 | tokio = { version = "1", features = [ 36 | "net", 37 | "macros", 38 | "io-util", 39 | ], optional = true } 40 | tokio-util = { version = "0.7", features = ["codec"], optional = true } 41 | 42 | [target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies] 43 | ipnet = "2" 44 | 45 | [target.'cfg(target_os = "windows")'.dependencies] 46 | futures = { version = "0.3", optional = true } 47 | windows-sys = { version = "0.59", features = [ 48 | "Win32_Foundation", 49 | "Win32_Security", 50 | "Win32_Security_WinTrust", 51 | "Win32_Security_Cryptography", 52 | "Win32_System_Threading", 53 | "Win32_UI_WindowsAndMessaging", 54 | "Win32_System_LibraryLoader", 55 | ] } 56 | wintun-bindings = { version = "^0.7.7", features = [ 57 | "panic_on_unsent_packets", 58 | "verify_binary_signature", 59 | "async", 60 | "enable_inner_logging", 61 | "winreg", 62 | ] } 63 | 64 | [target.'cfg(unix)'.dependencies] 65 | nix = { version = "0.30", features = ["ioctl"] } 66 | 67 | [dev-dependencies] 68 | ctrlc2 = { version = "3", features = ["tokio", "termination"] } 69 | env_logger = "0.11" 70 | futures = "0.3" 71 | packet = "0.1" 72 | serde_json = "1" 73 | tokio = { version = "1", features = ["rt-multi-thread"] } 74 | tokio-util = { version = "0.7", features = [] } 75 | 76 | [target.'cfg(unix)'.dev-dependencies] 77 | futures = "0.3" 78 | nix = { version = "0.30", features = ["ioctl"] } 79 | 80 | [[example]] 81 | name = "read-async" 82 | required-features = ["async"] 83 | 84 | [[example]] 85 | name = "read-async-codec" 86 | required-features = ["async"] 87 | 88 | [[example]] 89 | name = "ping-tun" 90 | required-features = ["async"] 91 | 92 | [[example]] 93 | name = "split-async" 94 | required-features = ["async"] 95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | TUN interfaces 2 | ============== 3 | [![Crates.io](https://img.shields.io/crates/v/tun.svg)](https://crates.io/crates/tun) 4 | [![tun](https://docs.rs/tun/badge.svg)](https://docs.rs/tun/latest/tun/) 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 | Usage 10 | ----- 11 | First, add the following to your `Cargo.toml`: 12 | 13 | ```toml 14 | [dependencies] 15 | tun = "0.7" 16 | ``` 17 | 18 | If you want to use the TUN interface with mio/tokio, you need to enable the `async` feature: 19 | 20 | ```toml 21 | [dependencies] 22 | tun = { version = "0.7", features = ["async"] } 23 | ``` 24 | 25 | Example 26 | ------- 27 | The following example creates and configures a TUN interface and starts reading 28 | packets from it. 29 | 30 | ```rust 31 | use std::io::Read; 32 | 33 | fn main() -> Result<(), Box> { 34 | let mut config = tun::Configuration::default(); 35 | config 36 | .address((10, 0, 0, 9)) 37 | .netmask((255, 255, 255, 0)) 38 | .destination((10, 0, 0, 1)) 39 | .up(); 40 | 41 | #[cfg(target_os = "linux")] 42 | config.platform_config(|config| { 43 | // requiring root privilege to acquire complete functions 44 | config.ensure_root_privileges(true); 45 | }); 46 | 47 | let mut dev = tun::create(&config)?; 48 | let mut buf = [0; 4096]; 49 | 50 | loop { 51 | let amount = dev.read(&mut buf)?; 52 | println!("{:?}", &buf[0..amount]); 53 | } 54 | } 55 | ``` 56 | 57 | Platforms 58 | ========= 59 | ## Supported Platforms 60 | 61 | - [x] Windows 62 | - [x] Linux 63 | - [x] macOS 64 | - [x] FreeBSD 65 | - [x] Android 66 | - [x] iOS 67 | - [x] tvOS 68 | - [x] OpenHarmony 69 | 70 | 71 | Linux 72 | ----- 73 | You will need the `tun` module to be loaded and root is required to create 74 | interfaces. 75 | 76 | macOS & FreeBSD 77 | ----- 78 | `tun` will automatically set up a route according to the provided configuration, which does a similar thing like this: 79 | > sudo route -n add -net 10.0.0.0/24 10.0.0.1 80 | 81 | 82 | iOS 83 | ---- 84 | You can pass the file descriptor of the TUN device to `tun` to create the interface. 85 | 86 | Here is an example to create the TUN device on iOS and pass the `fd` to `tun`: 87 | ```swift 88 | // Swift 89 | class PacketTunnelProvider: NEPacketTunnelProvider { 90 | override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { 91 | let tunnelNetworkSettings = createTunnelSettings() // Configure TUN address, DNS, mtu, routing... 92 | setTunnelNetworkSettings(tunnelNetworkSettings) { [weak self] error in 93 | // The tunnel of this tunFd is contains `Packet Information` prifix. 94 | let tunFd = self?.packetFlow.value(forKeyPath: "socket.fileDescriptor") as! Int32 95 | DispatchQueue.global(qos: .default).async { 96 | start_tun(tunFd) 97 | } 98 | completionHandler(nil) 99 | } 100 | } 101 | } 102 | ``` 103 | 104 | ```rust 105 | #[no_mangle] 106 | pub extern "C" fn start_tun(fd: std::os::raw::c_int) { 107 | let mut rt = tokio::runtime::Runtime::new().unwrap(); 108 | rt.block_on(async { 109 | let mut cfg = tun::Configuration::default(); 110 | cfg.raw_fd(fd); 111 | #[cfg(target_os = "ios")] 112 | cfg.platform_config(|p_cfg| { 113 | p_cfg.packet_information(true); 114 | }); 115 | let mut tun = tun::create_as_async(&cfg).unwrap(); 116 | let mut framed = tun.into_framed(); 117 | while let Some(packet) = framed.next().await { 118 | ... 119 | } 120 | }); 121 | } 122 | ``` 123 | 124 | Windows 125 | ----- 126 | You need to copy the [wintun.dll](https://wintun.net/) file which matches your architecture to 127 | the same directory as your executable and run your program as administrator. 128 | 129 | 130 | OpenHarmony 131 | ----- 132 | You can pass the file descriptor of the TUN device to `tun` to create the interface. You can see the detail [VPN document](https://developer.huawei.com/consumer/en/doc/harmonyos-references-V5/js-apis-net-vpnextension-V5). 133 | 134 | Here is an example to create the TUN device on OpenHarmony/HarmonyNext and pass the `fd` to `tun`: 135 | ```ts 136 | // ArkTS 137 | import vpnExtension from '@ohos.net.vpnExtension'; 138 | import vpnClient from 'libvpn_client.so'; 139 | 140 | const VpnConnection: vpnExtension.VpnConnection = vpnExtension.createVpnConnection(this.context); 141 | 142 | async function setup() { 143 | const fd = await VpnConnection.create(config); 144 | vpnClient.setup(fd); 145 | } 146 | ``` 147 | 148 | ```rust 149 | // use ohos-rs to bind rust for arkts 150 | use napi_derive_ohos::napi; 151 | 152 | #[napi] 153 | async fn setup(fd: i32) { 154 | let mut rt = tokio::runtime::Runtime::new().unwrap(); 155 | rt.block_on(async { 156 | let mut cfg = tun::Configuration::default(); 157 | cfg.raw_fd(fd); 158 | let mut tun = tun::create_as_async(&cfg).unwrap(); 159 | let mut framed = tun.into_framed(); 160 | while let Some(packet) = framed.next().await { 161 | ... 162 | } 163 | }); 164 | } 165 | ``` 166 | 167 | ## Contributors ✨ 168 | Thanks goes to these wonderful people: 169 | 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /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::{Packet, builder::Builder, icmp, ip}; 16 | use std::io::{Read, Write}; 17 | use std::{net::Ipv4Addr, sync::mpsc::Receiver}; 18 | use tun::{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 = tun::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 = tun::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::{Packet, builder::Builder, icmp, ip}; 17 | use tokio::sync::mpsc::Receiver; 18 | use tun::{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 = tun::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::{Error, ip::Packet}; 18 | use tokio::sync::mpsc::Receiver; 19 | use tokio_util::codec::{Decoder, FramedRead}; 20 | use tun::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 = tun::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 = tun::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 tun::{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 = tun::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(tun::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 = tun::create_as_async(&config)?; 49 | let size = dev.mtu()? as usize + tun::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 tun::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 = tun::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 = tun::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-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 | // You can test this example with command `ping 10.0.3.1`. 16 | 17 | use packet::{Packet, builder::Builder, icmp, ip}; 18 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; 19 | use tun::BoxError; 20 | 21 | #[tokio::main] 22 | async fn main() -> Result<(), BoxError> { 23 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 24 | 25 | let cancel_token = tokio_util::sync::CancellationToken::new(); 26 | let cancel_token_clone = cancel_token.clone(); 27 | 28 | let handle = ctrlc2::set_async_handler(async move { 29 | cancel_token_clone.cancel(); 30 | }) 31 | .await; 32 | 33 | main_entry(cancel_token).await?; 34 | handle.await?; 35 | Ok(()) 36 | } 37 | 38 | async fn main_entry(cancel_token: tokio_util::sync::CancellationToken) -> Result<(), BoxError> { 39 | let mut config = tun::Configuration::default(); 40 | 41 | config 42 | .address((10, 0, 3, 9)) 43 | .netmask((255, 255, 255, 0)) 44 | .destination((10, 0, 3, 1)) 45 | .up(); 46 | 47 | #[cfg(target_os = "linux")] 48 | config.platform_config(|config| { 49 | config.ensure_root_privileges(true); 50 | }); 51 | 52 | let dev = tun::create_as_async(&config)?; 53 | let (mut writer, mut reader) = dev.split()?; 54 | 55 | let (tx, mut rx) = tokio::sync::mpsc::channel(1); 56 | let t1_token = cancel_token.clone(); 57 | let t2_token = cancel_token.clone(); 58 | 59 | let t1 = tokio::spawn(async move { 60 | let mut buf = [0; 4096]; 61 | loop { 62 | let size = tokio::select! { 63 | _ = t1_token.cancelled() => break, 64 | res = reader.read(&mut buf) => res?, 65 | }; 66 | let pkt = &buf[..size]; 67 | tx.send(pkt.to_vec()).await.map_err(std::io::Error::other)?; 68 | } 69 | Ok::<(), std::io::Error>(()) 70 | }); 71 | 72 | let t2 = tokio::spawn(async move { 73 | loop { 74 | let pkt = tokio::select! { 75 | _ = t2_token.cancelled() => break, 76 | opt = rx.recv() => opt.ok_or(packet::Error::Io(std::io::Error::other("Channel closed")))?, 77 | }; 78 | match ip::Packet::new(pkt.as_slice()) { 79 | Ok(ip::Packet::V4(pkt)) => { 80 | if let Ok(icmp) = icmp::Packet::new(pkt.payload()) { 81 | if let Ok(icmp) = icmp.echo() { 82 | println!("{:?} - {:?}", icmp.sequence(), pkt.destination()); 83 | let reply = ip::v4::Builder::default() 84 | .id(0x42)? 85 | .ttl(64)? 86 | .source(pkt.destination())? 87 | .destination(pkt.source())? 88 | .icmp()? 89 | .echo()? 90 | .reply()? 91 | .identifier(icmp.identifier())? 92 | .sequence(icmp.sequence())? 93 | .payload(icmp.payload())? 94 | .build()?; 95 | writer.write_all(&reply[..]).await?; 96 | } 97 | } 98 | } 99 | Err(err) => println!("Received an invalid packet: {:?}", err), 100 | _ => println!("receive pkt {:?}", pkt), 101 | } 102 | } 103 | Ok::<(), packet::Error>(()) 104 | }); 105 | let v = tokio::join!(t1, t2); 106 | println!("Exiting... {v:?}"); 107 | Ok(()) 108 | } 109 | -------------------------------------------------------------------------------- /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 | // You can test this example with command `ping 10.0.3.1`. 16 | 17 | use packet::{Packet, builder::Builder, icmp, ip}; 18 | use std::io::{Read, Write}; 19 | use std::sync::mpsc::Receiver; 20 | use tun::BoxError; 21 | 22 | fn main() -> Result<(), BoxError> { 23 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init(); 24 | let (tx, rx) = std::sync::mpsc::channel(); 25 | 26 | let handle = ctrlc2::set_handler(move || { 27 | tx.send(()).expect("Signal error."); 28 | true 29 | }) 30 | .expect("Error setting Ctrl-C handler"); 31 | 32 | main_entry(rx)?; 33 | handle.join().unwrap(); 34 | Ok(()) 35 | } 36 | 37 | fn main_entry(quit: Receiver<()>) -> Result<(), BoxError> { 38 | let mut config = tun::Configuration::default(); 39 | 40 | config 41 | .address((10, 0, 3, 9)) 42 | .netmask((255, 255, 255, 0)) 43 | .destination((10, 0, 3, 1)) 44 | .up(); 45 | 46 | #[cfg(target_os = "linux")] 47 | config.platform_config(|config| { 48 | config.ensure_root_privileges(true); 49 | }); 50 | 51 | let dev = tun::create(&config)?; 52 | let (mut reader, mut writer) = dev.split(); 53 | 54 | let (tx, rx) = std::sync::mpsc::channel(); 55 | 56 | let _t1 = std::thread::spawn(move || { 57 | let mut buf = [0; 4096]; 58 | loop { 59 | let size = reader.read(&mut buf)?; 60 | let pkt = &buf[..size]; 61 | tx.send(pkt.to_vec()).map_err(std::io::Error::other)?; 62 | } 63 | #[allow(unreachable_code)] 64 | Ok::<(), std::io::Error>(()) 65 | }); 66 | 67 | let _t2 = std::thread::spawn(move || { 68 | loop { 69 | if let Ok(pkt) = rx.recv() { 70 | match ip::Packet::new(pkt.as_slice()) { 71 | Ok(ip::Packet::V4(pkt)) => { 72 | if let Ok(icmp) = icmp::Packet::new(pkt.payload()) { 73 | if let Ok(icmp) = icmp.echo() { 74 | println!("{:?} - {:?}", icmp.sequence(), pkt.destination()); 75 | let reply = ip::v4::Builder::default() 76 | .id(0x42)? 77 | .ttl(64)? 78 | .source(pkt.destination())? 79 | .destination(pkt.source())? 80 | .icmp()? 81 | .echo()? 82 | .reply()? 83 | .identifier(icmp.identifier())? 84 | .sequence(icmp.sequence())? 85 | .payload(icmp.payload())? 86 | .build()?; 87 | writer.write_all(&reply[..])?; 88 | } 89 | } 90 | } 91 | Err(err) => println!("Received an invalid packet: {:?}", err), 92 | _ => { 93 | println!("receive pkt {:?}", pkt); 94 | } 95 | } 96 | } 97 | } 98 | #[allow(unreachable_code)] 99 | Ok::<(), packet::Error>(()) 100 | }); 101 | quit.recv().expect("Quit error."); 102 | Ok(()) 103 | } 104 | -------------------------------------------------------------------------------- /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::{Packet, builder::Builder, icmp, ip}; 16 | use std::io::{Read, Write}; 17 | use std::sync::mpsc::Receiver; 18 | use tun::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 = tun::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 = tun::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 ToAddress for &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 ToAddress for &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 ToAddress for &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 ToAddress for &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 ToAddress for &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 ToAddress for &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::Interest; 20 | use tokio::io::unix::AsyncFd; 21 | use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; 22 | use tokio_util::codec::Framed; 23 | 24 | use crate::r#async::TunPacketCodec; 25 | use crate::device::AbstractDevice; 26 | use crate::platform::Device; 27 | 28 | /// An async TUN device wrapper around a TUN device. 29 | pub struct AsyncDevice { 30 | inner: AsyncFd, 31 | } 32 | 33 | /// Returns a shared reference to the underlying Device object. 34 | impl core::ops::Deref for AsyncDevice { 35 | type Target = Device; 36 | 37 | fn deref(&self) -> &Self::Target { 38 | self.inner.get_ref() 39 | } 40 | } 41 | 42 | /// Returns a mutable reference to the underlying Device object. 43 | impl core::ops::DerefMut for AsyncDevice { 44 | fn deref_mut(&mut self) -> &mut Self::Target { 45 | self.inner.get_mut() 46 | } 47 | } 48 | 49 | impl AsyncDevice { 50 | /// Create a new `AsyncDevice` wrapping around a `Device`. 51 | pub fn new(device: Device) -> std::io::Result { 52 | device.set_nonblock()?; 53 | Ok(AsyncDevice { 54 | inner: AsyncFd::new(device)?, 55 | }) 56 | } 57 | 58 | /// Consumes this AsyncDevice and return a Framed object (unified Stream and Sink interface) 59 | pub fn into_framed(self) -> Framed { 60 | let mtu = self.mtu().unwrap_or(crate::DEFAULT_MTU); 61 | let codec = TunPacketCodec::new(mtu as usize); 62 | // associate mtu with the capacity of ReadBuf 63 | Framed::with_capacity(self, codec, mtu as usize) 64 | } 65 | 66 | /// Split the device into a reader and writer 67 | pub fn split(self) -> std::io::Result<(DeviceWriter, DeviceReader)> { 68 | let device = self.inner.into_inner(); 69 | let reader = std::sync::Arc::new(AsyncFd::new(device)?); 70 | let writer = reader.clone(); 71 | Ok((DeviceWriter::new(writer)?, DeviceReader::new(reader)?)) 72 | } 73 | 74 | /// Recv a packet from tun device 75 | pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result { 76 | let guard = self.inner.readable().await?; 77 | guard 78 | .get_ref() 79 | .async_io(Interest::READABLE, |inner| inner.recv(buf)) 80 | .await 81 | } 82 | 83 | /// Send a packet to tun device 84 | pub async fn send(&self, buf: &[u8]) -> std::io::Result { 85 | let guard = self.inner.writable().await?; 86 | guard 87 | .get_ref() 88 | .async_io(Interest::WRITABLE, |inner| inner.send(buf)) 89 | .await 90 | } 91 | } 92 | 93 | impl AsyncRead for AsyncDevice { 94 | fn poll_read( 95 | mut self: Pin<&mut Self>, 96 | cx: &mut Context<'_>, 97 | buf: &mut ReadBuf, 98 | ) -> Poll> { 99 | loop { 100 | let mut guard = ready!(self.inner.poll_read_ready_mut(cx))?; 101 | let rbuf = buf.initialize_unfilled(); 102 | match guard.try_io(|inner| inner.get_mut().read(rbuf)) { 103 | Ok(res) => return Poll::Ready(res.map(|n| buf.advance(n))), 104 | Err(_wb) => continue, 105 | } 106 | } 107 | } 108 | } 109 | 110 | impl AsyncWrite for AsyncDevice { 111 | fn poll_write( 112 | mut self: Pin<&mut Self>, 113 | cx: &mut Context<'_>, 114 | buf: &[u8], 115 | ) -> Poll> { 116 | loop { 117 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 118 | match guard.try_io(|inner| inner.get_mut().write(buf)) { 119 | Ok(res) => return Poll::Ready(res), 120 | Err(_wb) => continue, 121 | } 122 | } 123 | } 124 | 125 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 126 | loop { 127 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 128 | match guard.try_io(|inner| inner.get_mut().flush()) { 129 | Ok(res) => return Poll::Ready(res), 130 | Err(_wb) => continue, 131 | } 132 | } 133 | } 134 | 135 | fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 136 | Poll::Ready(Ok(())) 137 | } 138 | 139 | fn poll_write_vectored( 140 | mut self: Pin<&mut Self>, 141 | cx: &mut Context<'_>, 142 | bufs: &[IoSlice<'_>], 143 | ) -> Poll> { 144 | loop { 145 | let mut guard = ready!(self.inner.poll_write_ready_mut(cx))?; 146 | match guard.try_io(|inner| inner.get_mut().write_vectored(bufs)) { 147 | Ok(res) => return Poll::Ready(res), 148 | Err(_wb) => continue, 149 | } 150 | } 151 | } 152 | 153 | fn is_write_vectored(&self) -> bool { 154 | true 155 | } 156 | } 157 | pub struct DeviceReader { 158 | inner: std::sync::Arc>, 159 | } 160 | impl DeviceReader { 161 | fn new(inner: std::sync::Arc>) -> std::io::Result { 162 | Ok(Self { inner }) 163 | } 164 | } 165 | impl AsyncRead for DeviceReader { 166 | fn poll_read( 167 | 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(cx))?; 173 | let rbuf = buf.initialize_unfilled(); 174 | match guard.try_io(|inner| inner.get_ref().recv(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: std::sync::Arc>, 184 | } 185 | impl DeviceWriter { 186 | fn new(inner: std::sync::Arc>) -> std::io::Result { 187 | Ok(Self { inner }) 188 | } 189 | } 190 | 191 | impl AsyncWrite for DeviceWriter { 192 | fn poll_write( 193 | self: Pin<&mut Self>, 194 | cx: &mut Context<'_>, 195 | buf: &[u8], 196 | ) -> Poll> { 197 | loop { 198 | let mut guard = ready!(self.inner.poll_write_ready(cx))?; 199 | match guard.try_io(|inner| inner.get_ref().send(buf)) { 200 | Ok(res) => return Poll::Ready(res), 201 | Err(_wb) => continue, 202 | } 203 | } 204 | } 205 | 206 | fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 207 | Poll::Ready(Ok(())) 208 | } 209 | 210 | fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { 211 | Poll::Ready(Ok(())) 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /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 crate::r#async::TunPacketCodec; 16 | use crate::device::AbstractDevice; 17 | use crate::platform::Device; 18 | use core::pin::Pin; 19 | use core::task::{Context, Poll}; 20 | use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; 21 | use tokio_util::codec::Framed; 22 | use wintun_bindings::AsyncSession; 23 | 24 | /// An async TUN device wrapper around a TUN device. 25 | pub struct AsyncDevice { 26 | inner: Device, 27 | session_reader: DeviceReader, 28 | session_writer: DeviceWriter, 29 | } 30 | 31 | /// Returns a shared reference to the underlying Device object. 32 | impl core::ops::Deref for AsyncDevice { 33 | type Target = Device; 34 | 35 | fn deref(&self) -> &Self::Target { 36 | &self.inner 37 | } 38 | } 39 | 40 | /// Returns a mutable reference to the underlying Device object. 41 | impl core::ops::DerefMut for AsyncDevice { 42 | fn deref_mut(&mut self) -> &mut Self::Target { 43 | &mut self.inner 44 | } 45 | } 46 | 47 | impl AsyncDevice { 48 | /// Create a new `AsyncDevice` wrapping around a `Device`. 49 | pub fn new(device: Device) -> std::io::Result { 50 | let session_reader = DeviceReader::new(device.tun.get_session().into())?; 51 | let session_writer = DeviceWriter::new(device.tun.get_session().into())?; 52 | Ok(AsyncDevice { 53 | inner: device, 54 | session_reader, 55 | session_writer, 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 | // guarantee to avoid the mtu of wintun may far away larger than the default provided capacity of ReadBuf of Framed 64 | Framed::with_capacity(self, codec, mtu as usize) 65 | } 66 | 67 | pub fn split(self) -> std::io::Result<(DeviceWriter, DeviceReader)> { 68 | Ok((self.session_writer, self.session_reader)) 69 | } 70 | 71 | /// Recv a packet from tun device - Not implemented for windows 72 | pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result { 73 | self.session_reader.session.recv(buf).await 74 | } 75 | 76 | /// Send a packet to tun device - Not implemented for windows 77 | pub async fn send(&self, buf: &[u8]) -> std::io::Result { 78 | self.session_writer.session.send(buf).await 79 | } 80 | } 81 | 82 | impl AsyncRead for AsyncDevice { 83 | fn poll_read( 84 | mut self: Pin<&mut Self>, 85 | cx: &mut Context<'_>, 86 | buf: &mut ReadBuf<'_>, 87 | ) -> Poll> { 88 | Pin::new(&mut self.session_reader).poll_read(cx, buf) 89 | } 90 | } 91 | 92 | impl AsyncWrite for AsyncDevice { 93 | fn poll_write( 94 | mut self: Pin<&mut Self>, 95 | cx: &mut Context<'_>, 96 | buf: &[u8], 97 | ) -> Poll> { 98 | Pin::new(&mut self.session_writer).poll_write(cx, buf) 99 | } 100 | 101 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 102 | Pin::new(&mut self.session_writer).poll_flush(cx) 103 | } 104 | 105 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 106 | Pin::new(&mut self.session_writer).poll_shutdown(cx) 107 | } 108 | } 109 | 110 | pub struct DeviceReader { 111 | session: AsyncSession, 112 | } 113 | 114 | impl DeviceReader { 115 | fn new(session: AsyncSession) -> std::io::Result { 116 | Ok(DeviceReader { session }) 117 | } 118 | } 119 | 120 | impl AsyncRead for DeviceReader { 121 | fn poll_read( 122 | mut self: Pin<&mut Self>, 123 | cx: &mut Context<'_>, 124 | buf: &mut ReadBuf<'_>, 125 | ) -> Poll> { 126 | let buf_ref = buf.initialize_unfilled(); 127 | match futures::AsyncRead::poll_read(Pin::new(&mut self.session), cx, buf_ref) { 128 | Poll::Ready(Ok(size)) => { 129 | buf.advance(size); 130 | Poll::Ready(Ok(())) 131 | } 132 | Poll::Ready(Err(err)) => Poll::Ready(Err(err)), 133 | Poll::Pending => Poll::Pending, 134 | } 135 | } 136 | } 137 | 138 | pub struct DeviceWriter { 139 | session: AsyncSession, 140 | } 141 | 142 | impl DeviceWriter { 143 | fn new(session: AsyncSession) -> std::io::Result { 144 | Ok(DeviceWriter { session }) 145 | } 146 | } 147 | 148 | impl AsyncWrite for DeviceWriter { 149 | fn poll_write( 150 | mut self: Pin<&mut Self>, 151 | cx: &mut Context<'_>, 152 | buf: &[u8], 153 | ) -> Poll> { 154 | futures::AsyncWrite::poll_write(Pin::new(&mut self.session), cx, buf) 155 | } 156 | 157 | fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 158 | futures::AsyncWrite::poll_flush(Pin::new(&mut self.session), cx) 159 | } 160 | 161 | fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 162 | futures::AsyncWrite::poll_close(Pin::new(&mut self.session), cx) 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /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 = "0.7.0", 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 = "0.7.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 tun 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 tun 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::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 crate::configuration::Configuration; 17 | use crate::device::AbstractDevice; 18 | use crate::error::{Error, Result}; 19 | use crate::platform::posix::{self, Fd, Tun}; 20 | use std::io::{Read, Write}; 21 | use std::net::IpAddr; 22 | use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; 23 | 24 | /// A TUN device for Android. 25 | pub struct Device { 26 | pub(crate) tun: Tun, 27 | pub(crate) address: Option, 28 | pub(crate) netmask: Option, 29 | } 30 | 31 | impl AsRef for Device { 32 | fn as_ref(&self) -> &(dyn AbstractDevice + 'static) { 33 | self 34 | } 35 | } 36 | 37 | impl AsMut for Device { 38 | fn as_mut(&mut self) -> &mut (dyn AbstractDevice + 'static) { 39 | self 40 | } 41 | } 42 | 43 | impl Device { 44 | /// Create a new `Device` for the given `Configuration`. 45 | pub fn new(config: &Configuration) -> Result { 46 | let close_fd_on_drop = config.close_fd_on_drop.unwrap_or(true); 47 | let fd = match config.raw_fd { 48 | Some(raw_fd) => raw_fd, 49 | _ => return Err(Error::InvalidConfig), 50 | }; 51 | let device = { 52 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 53 | let tun = Fd::new(fd, close_fd_on_drop).map_err(|_| std::io::Error::last_os_error())?; 54 | 55 | Device { 56 | tun: Tun::new(tun, mtu, false), 57 | address: config.address, 58 | netmask: config.netmask, 59 | } 60 | }; 61 | 62 | Ok(device) 63 | } 64 | 65 | /// Split the interface into a `Reader` and `Writer`. 66 | pub fn split(self) -> (posix::Reader, posix::Writer) { 67 | (self.tun.reader, self.tun.writer) 68 | } 69 | 70 | /// Set non-blocking mode 71 | #[allow(dead_code)] 72 | pub(crate) fn set_nonblock(&self) -> std::io::Result<()> { 73 | self.tun.set_nonblock() 74 | } 75 | 76 | /// Recv a packet from tun device 77 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 78 | self.tun.recv(buf) 79 | } 80 | 81 | /// Send a packet to tun device 82 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 83 | self.tun.send(buf) 84 | } 85 | } 86 | 87 | impl Read for Device { 88 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 89 | self.tun.read(buf) 90 | } 91 | } 92 | 93 | impl Write for Device { 94 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 95 | self.tun.write(buf) 96 | } 97 | 98 | fn flush(&mut self) -> std::io::Result<()> { 99 | self.tun.flush() 100 | } 101 | } 102 | 103 | impl AbstractDevice for Device { 104 | fn tun_index(&self) -> Result { 105 | Err(Error::NotImplemented) 106 | } 107 | 108 | fn tun_name(&self) -> Result { 109 | Ok("".to_string()) 110 | } 111 | 112 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 113 | Err(Error::NotImplemented) 114 | } 115 | 116 | fn enabled(&mut self, value: bool) -> Result<()> { 117 | Ok(()) 118 | } 119 | 120 | fn address(&self) -> Result { 121 | self.address.ok_or(Error::NotImplemented) 122 | } 123 | 124 | fn set_address(&mut self, _value: IpAddr) -> Result<()> { 125 | Ok(()) 126 | } 127 | 128 | fn destination(&self) -> Result { 129 | Err(Error::NotImplemented) 130 | } 131 | 132 | fn set_destination(&mut self, _value: IpAddr) -> Result<()> { 133 | Ok(()) 134 | } 135 | 136 | fn broadcast(&self) -> Result { 137 | Err(Error::NotImplemented) 138 | } 139 | 140 | fn set_broadcast(&mut self, _value: IpAddr) -> Result<()> { 141 | Ok(()) 142 | } 143 | 144 | fn netmask(&self) -> Result { 145 | self.netmask.ok_or(Error::NotImplemented) 146 | } 147 | 148 | fn set_netmask(&mut self, _value: IpAddr) -> Result<()> { 149 | Ok(()) 150 | } 151 | 152 | fn mtu(&self) -> Result { 153 | // TODO: must get the mtu from the underlying device driver 154 | Ok(self.tun.mtu()) 155 | } 156 | 157 | fn set_mtu(&mut self, value: u16) -> Result<()> { 158 | // TODO: must set the mtu to the underlying device driver 159 | self.tun.set_mtu(value); 160 | Ok(()) 161 | } 162 | 163 | fn packet_information(&self) -> bool { 164 | self.tun.packet_information() 165 | } 166 | } 167 | 168 | impl AsRawFd for Device { 169 | fn as_raw_fd(&self) -> RawFd { 170 | self.tun.as_raw_fd() 171 | } 172 | } 173 | 174 | impl IntoRawFd for Device { 175 | fn into_raw_fd(self) -> RawFd { 176 | self.tun.into_raw_fd() 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /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, AF_INET, IFF_RUNNING, IFF_UP, IFNAMSIZ, O_RDWR, SOCK_DGRAM, c_char, c_short, ifreq, 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, Fd, Tun, sockaddr_union}, 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 | pub(crate) 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))); 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, 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 = unsafe { mem::zeroed() }; 189 | unsafe { 190 | ptr::copy_nonoverlapping( 191 | self.tun_name.as_ptr() as *const c_char, 192 | req.ifr_name.as_mut_ptr(), 193 | self.tun_name.len(), 194 | ) 195 | }; 196 | 197 | req 198 | } 199 | 200 | /// Split the interface into a `Reader` and `Writer`. 201 | pub fn split(self) -> (posix::Reader, posix::Writer) { 202 | (self.tun.reader, self.tun.writer) 203 | } 204 | 205 | /// Set non-blocking mode 206 | #[allow(dead_code)] 207 | pub(crate) fn set_nonblock(&self) -> std::io::Result<()> { 208 | self.tun.set_nonblock() 209 | } 210 | 211 | fn set_route(&mut self, route: Route) -> Result<()> { 212 | // if let Some(v) = &self.route { 213 | // let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(v.netmask)) 214 | // .map_err(|_| Error::InvalidConfig)?; 215 | // let network = ipnet::Ipv4Net::new(v.addr, prefix_len) 216 | // .map_err(|e| Error::InvalidConfig)? 217 | // .network(); 218 | // // command: route -n delete -net 10.0.0.0/24 10.0.0.1 219 | // let args = [ 220 | // "-n", 221 | // "delete", 222 | // "-net", 223 | // &format!("{}/{}", network, prefix_len), 224 | // &v.dest.to_string(), 225 | // ]; 226 | // println!("{args:?}"); 227 | // run_command("route", &args); 228 | // log::info!("route {}", args.join(" ")); 229 | // } 230 | 231 | // command: route -n add -net 10.0.0.9/24 10.0.0.1 232 | let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(route.netmask)) 233 | .map_err(|_| Error::InvalidConfig)?; 234 | let args = [ 235 | "-n", 236 | "add", 237 | "-net", 238 | &format!("{}/{}", route.addr, prefix_len), 239 | &route.dest.to_string(), 240 | ]; 241 | run_command("route", &args)?; 242 | log::info!("route {}", args.join(" ")); 243 | self.route = Some(route); 244 | Ok(()) 245 | } 246 | 247 | /// Recv a packet from tun device 248 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 249 | self.tun.recv(buf) 250 | } 251 | 252 | /// Send a packet to tun device 253 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 254 | self.tun.send(buf) 255 | } 256 | } 257 | 258 | impl Read for Device { 259 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 260 | self.tun.read(buf) 261 | } 262 | 263 | fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result { 264 | self.tun.read_vectored(bufs) 265 | } 266 | } 267 | 268 | impl Write for Device { 269 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 270 | self.tun.write(buf) 271 | } 272 | 273 | fn flush(&mut self) -> std::io::Result<()> { 274 | self.tun.flush() 275 | } 276 | 277 | fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { 278 | self.tun.write_vectored(bufs) 279 | } 280 | } 281 | 282 | impl AbstractDevice for Device { 283 | fn tun_index(&self) -> Result { 284 | let name = self.tun_name()?; 285 | Ok(posix::tun_name_to_index(name)? as i32) 286 | } 287 | 288 | fn tun_name(&self) -> Result { 289 | Ok(self.tun_name.clone()) 290 | } 291 | 292 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 293 | use std::ffi::CString; 294 | unsafe { 295 | if value.len() > IFNAMSIZ { 296 | return Err(Error::NameTooLong); 297 | } 298 | let mut req = self.request(); 299 | let tun_name = CString::new(value)?; 300 | let mut tun_name: Vec = tun_name 301 | .into_bytes_with_nul() 302 | .into_iter() 303 | .map(|c| c as c_char) 304 | .collect::<_>(); 305 | req.ifr_ifru.ifru_data = tun_name.as_mut_ptr(); 306 | if let Err(err) = siocsifname(self.ctl.as_raw_fd(), &req) { 307 | return Err(std::io::Error::from(err).into()); 308 | } 309 | 310 | self.tun_name = value.to_string(); 311 | Ok(()) 312 | } 313 | } 314 | 315 | fn enabled(&mut self, value: bool) -> Result<()> { 316 | unsafe { 317 | let mut req = self.request(); 318 | 319 | if let Err(err) = siocgifflags(self.ctl.as_raw_fd(), &mut req) { 320 | return Err(std::io::Error::from(err).into()); 321 | } 322 | 323 | if value { 324 | req.ifr_ifru.ifru_flags[0] |= (IFF_UP | IFF_RUNNING) as c_short; 325 | } else { 326 | req.ifr_ifru.ifru_flags[0] &= !(IFF_UP as c_short); 327 | } 328 | 329 | if let Err(err) = siocsifflags(self.ctl.as_raw_fd(), &req) { 330 | return Err(std::io::Error::from(err).into()); 331 | } 332 | 333 | Ok(()) 334 | } 335 | } 336 | 337 | fn address(&self) -> Result { 338 | unsafe { 339 | let mut req = self.request(); 340 | if let Err(err) = siocgifaddr(self.ctl.as_raw_fd(), &mut req) { 341 | return Err(std::io::Error::from(err).into()); 342 | } 343 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 344 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 345 | } 346 | } 347 | 348 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 349 | unsafe { 350 | let req = self.request(); 351 | if let Err(err) = siocdifaddr(self.ctl.as_raw_fd(), &req) { 352 | return Err(std::io::Error::from(err).into()); 353 | } 354 | let previous = self.route.as_ref().ok_or(Error::InvalidConfig)?; 355 | self.set_alias( 356 | value, 357 | IpAddr::V4(previous.dest), 358 | IpAddr::V4(previous.netmask), 359 | )?; 360 | } 361 | Ok(()) 362 | } 363 | 364 | fn destination(&self) -> Result { 365 | unsafe { 366 | let mut req = self.request(); 367 | if let Err(err) = siocgifdstaddr(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_dstaddr); 371 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 372 | } 373 | } 374 | 375 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 376 | unsafe { 377 | let req = self.request(); 378 | if let Err(err) = siocdifaddr(self.ctl.as_raw_fd(), &req) { 379 | return Err(std::io::Error::from(err).into()); 380 | } 381 | let previous = self.route.as_ref().ok_or(Error::InvalidConfig)?; 382 | self.set_alias( 383 | IpAddr::V4(previous.addr), 384 | value, 385 | IpAddr::V4(previous.netmask), 386 | )?; 387 | } 388 | Ok(()) 389 | } 390 | 391 | fn broadcast(&self) -> Result { 392 | unsafe { 393 | let mut req = self.request(); 394 | if let Err(err) = siocgifbrdaddr(self.ctl.as_raw_fd(), &mut req) { 395 | return Err(std::io::Error::from(err).into()); 396 | } 397 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_broadaddr); 398 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 399 | } 400 | } 401 | 402 | fn set_broadcast(&mut self, _value: IpAddr) -> Result<()> { 403 | Ok(()) 404 | } 405 | 406 | fn netmask(&self) -> Result { 407 | unsafe { 408 | let mut req = self.request(); 409 | if let Err(err) = siocgifnetmask(self.ctl.as_raw_fd(), &mut req) { 410 | return Err(std::io::Error::from(err).into()); 411 | } 412 | // NOTE: Here should be `ifru_netmask` instead of `ifru_addr`, but `ifreq` does not define it. 413 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 414 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 415 | } 416 | } 417 | 418 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 419 | unsafe { 420 | let req = self.request(); 421 | if let Err(err) = siocdifaddr(self.ctl.as_raw_fd(), &req) { 422 | return Err(std::io::Error::from(err).into()); 423 | } 424 | let previous = self.route.as_ref().ok_or(Error::InvalidConfig)?; 425 | self.set_alias(IpAddr::V4(previous.addr), IpAddr::V4(previous.dest), value)?; 426 | } 427 | Ok(()) 428 | } 429 | 430 | fn mtu(&self) -> Result { 431 | unsafe { 432 | let mut req = self.request(); 433 | 434 | if let Err(err) = siocgifmtu(self.ctl.as_raw_fd(), &mut req) { 435 | return Err(std::io::Error::from(err).into()); 436 | } 437 | 438 | req.ifr_ifru 439 | .ifru_mtu 440 | .try_into() 441 | .map_err(|_| Error::TryFromIntError) 442 | } 443 | } 444 | 445 | fn set_mtu(&mut self, value: u16) -> Result<()> { 446 | unsafe { 447 | let mut req = self.request(); 448 | req.ifr_ifru.ifru_mtu = value as i32; 449 | 450 | if let Err(err) = siocsifmtu(self.ctl.as_raw_fd(), &req) { 451 | return Err(std::io::Error::from(err).into()); 452 | } 453 | self.tun.set_mtu(value); 454 | Ok(()) 455 | } 456 | } 457 | 458 | fn packet_information(&self) -> bool { 459 | self.tun.packet_information() 460 | } 461 | } 462 | 463 | impl AsRawFd for Device { 464 | fn as_raw_fd(&self) -> RawFd { 465 | self.tun.as_raw_fd() 466 | } 467 | } 468 | 469 | impl IntoRawFd for Device { 470 | fn into_raw_fd(self) -> RawFd { 471 | self.tun.into_raw_fd() 472 | } 473 | } 474 | 475 | impl From for c_short { 476 | fn from(layer: Layer) -> Self { 477 | match layer { 478 | Layer::L2 => 2, 479 | Layer::L3 => 3, 480 | } 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /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::{IFNAMSIZ, c_char, c_int, c_uint, ifreq, sockaddr}; 18 | use nix::{ioctl_readwrite, ioctl_write_ptr}; 19 | 20 | #[allow(non_camel_case_types, dead_code)] 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 | pub(crate) tun: Tun, 31 | pub(crate) address: Option, 32 | pub(crate) netmask: Option, 33 | pub(crate) tun_name: Option, 34 | } 35 | 36 | impl AsRef for Device { 37 | fn as_ref(&self) -> &(dyn AbstractDevice + 'static) { 38 | self 39 | } 40 | } 41 | 42 | impl AsMut for Device { 43 | fn as_mut(&mut self) -> &mut (dyn AbstractDevice + 'static) { 44 | self 45 | } 46 | } 47 | 48 | impl Device { 49 | /// Create a new `Device` for the given `Configuration`. 50 | pub fn new(config: &Configuration) -> Result { 51 | let close_fd_on_drop = config.close_fd_on_drop.unwrap_or(true); 52 | let fd = match config.raw_fd { 53 | Some(raw_fd) => raw_fd, 54 | _ => return Err(Error::InvalidConfig), 55 | }; 56 | let device = { 57 | let mtu = config.mtu.unwrap_or(crate::DEFAULT_MTU); 58 | let fd = Fd::new(fd, close_fd_on_drop).map_err(|_| std::io::Error::last_os_error())?; 59 | Device { 60 | tun: Tun::new(fd, mtu, config.platform_config.packet_information), 61 | address: config.address, 62 | netmask: config.netmask, 63 | tun_name: config.tun_name.clone(), 64 | } 65 | }; 66 | 67 | Ok(device) 68 | } 69 | 70 | /// Split the interface into a `Reader` and `Writer`. 71 | pub fn split(self) -> (posix::Reader, posix::Writer) { 72 | (self.tun.reader, self.tun.writer) 73 | } 74 | 75 | /// Set non-blocking mode 76 | #[allow(dead_code)] 77 | pub(crate) fn set_nonblock(&self) -> std::io::Result<()> { 78 | self.tun.set_nonblock() 79 | } 80 | 81 | /// Recv a packet from tun device 82 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 83 | self.tun.recv(buf) 84 | } 85 | 86 | /// Send a packet to tun device 87 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 88 | self.tun.send(buf) 89 | } 90 | } 91 | 92 | impl Read for Device { 93 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 94 | self.tun.read(buf) 95 | } 96 | 97 | fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result { 98 | self.tun.read_vectored(bufs) 99 | } 100 | } 101 | 102 | impl Write for Device { 103 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 104 | self.tun.write(buf) 105 | } 106 | 107 | fn flush(&mut self) -> std::io::Result<()> { 108 | self.tun.flush() 109 | } 110 | 111 | fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { 112 | self.tun.write_vectored(bufs) 113 | } 114 | } 115 | 116 | impl AbstractDevice for Device { 117 | fn tun_index(&self) -> Result { 118 | Err("no tun_index".into()) 119 | } 120 | 121 | fn tun_name(&self) -> Result { 122 | Ok(self.tun_name.clone().unwrap_or("".to_string())) 123 | } 124 | 125 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 126 | Err("set_tun_name".into()) 127 | } 128 | 129 | fn enabled(&mut self, value: bool) -> Result<()> { 130 | Ok(()) 131 | } 132 | 133 | fn address(&self) -> Result { 134 | self.address.ok_or("no address".into()) 135 | } 136 | 137 | fn set_address(&mut self, _value: IpAddr) -> Result<()> { 138 | Ok(()) 139 | } 140 | 141 | fn destination(&self) -> Result { 142 | Err("no destination".into()) 143 | } 144 | 145 | fn set_destination(&mut self, _value: IpAddr) -> Result<()> { 146 | Ok(()) 147 | } 148 | 149 | fn broadcast(&self) -> Result { 150 | Err("no broadcast".into()) 151 | } 152 | 153 | fn set_broadcast(&mut self, _value: IpAddr) -> Result<()> { 154 | Ok(()) 155 | } 156 | 157 | fn netmask(&self) -> Result { 158 | self.netmask.ok_or("no netmask".into()) 159 | } 160 | 161 | fn set_netmask(&mut self, _value: IpAddr) -> Result<()> { 162 | Ok(()) 163 | } 164 | 165 | fn mtu(&self) -> Result { 166 | // TODO: must get the mtu from the underlying device driver 167 | Ok(self.tun.mtu()) 168 | } 169 | 170 | fn set_mtu(&mut self, value: u16) -> Result<()> { 171 | // TODO: must set the mtu to the underlying device driver 172 | self.tun.set_mtu(value); 173 | Ok(()) 174 | } 175 | 176 | fn packet_information(&self) -> bool { 177 | self.tun.packet_information() 178 | } 179 | } 180 | 181 | impl AsRawFd for Device { 182 | fn as_raw_fd(&self) -> RawFd { 183 | self.tun.as_raw_fd() 184 | } 185 | } 186 | 187 | impl IntoRawFd for Device { 188 | fn into_raw_fd(self) -> RawFd { 189 | self.tun.into_raw_fd() 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /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, AF_INET, IFF_MULTI_QUEUE, IFF_NAPI, IFF_NO_PI, IFF_RUNNING, IFF_TAP, IFF_TUN, IFF_UP, 17 | IFF_VNET_HDR, IFNAMSIZ, O_RDWR, SOCK_DGRAM, c_char, c_short, ifreq, 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, Fd, Tun, ipaddr_to_sockaddr, sockaddr_union}, 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 | pub(crate) 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(c"/dev/net/tun".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 = unsafe { mem::zeroed() }; 154 | unsafe { 155 | ptr::copy_nonoverlapping( 156 | self.tun_name.as_ptr() as *const c_char, 157 | req.ifr_name.as_mut_ptr(), 158 | self.tun_name.len(), 159 | ) 160 | }; 161 | 162 | req 163 | } 164 | 165 | /// Make the device persistent. 166 | pub fn persist(&mut self) -> Result<()> { 167 | unsafe { 168 | if let Err(err) = tunsetpersist(self.as_raw_fd(), &1) { 169 | Err(std::io::Error::from(err).into()) 170 | } else { 171 | Ok(()) 172 | } 173 | } 174 | } 175 | 176 | /// Set the owner of the device. 177 | pub fn user(&mut self, value: i32) -> Result<()> { 178 | unsafe { 179 | if let Err(err) = tunsetowner(self.as_raw_fd(), &value) { 180 | Err(std::io::Error::from(err).into()) 181 | } else { 182 | Ok(()) 183 | } 184 | } 185 | } 186 | 187 | /// Set the group of the device. 188 | pub fn group(&mut self, value: i32) -> Result<()> { 189 | unsafe { 190 | if let Err(err) = tunsetgroup(self.as_raw_fd(), &value) { 191 | Err(std::io::Error::from(err).into()) 192 | } else { 193 | Ok(()) 194 | } 195 | } 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 | #[allow(dead_code)] 205 | pub(crate) fn set_nonblock(&self) -> std::io::Result<()> { 206 | self.tun.set_nonblock() 207 | } 208 | 209 | /// Recv a packet from tun device 210 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 211 | self.tun.recv(buf) 212 | } 213 | 214 | /// Send a packet to tun device 215 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 216 | self.tun.send(buf) 217 | } 218 | } 219 | 220 | impl Read for Device { 221 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 222 | self.tun.read(buf) 223 | } 224 | 225 | fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result { 226 | self.tun.read_vectored(bufs) 227 | } 228 | } 229 | 230 | impl Write for Device { 231 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 232 | self.tun.write(buf) 233 | } 234 | 235 | fn flush(&mut self) -> std::io::Result<()> { 236 | self.tun.flush() 237 | } 238 | 239 | fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { 240 | self.tun.write_vectored(bufs) 241 | } 242 | } 243 | 244 | impl AbstractDevice for Device { 245 | fn tun_index(&self) -> Result { 246 | let name = self.tun_name()?; 247 | Ok(posix::tun_name_to_index(name)? as i32) 248 | } 249 | 250 | fn tun_name(&self) -> Result { 251 | Ok(self.tun_name.clone()) 252 | } 253 | 254 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 255 | unsafe { 256 | let tun_name = CString::new(value)?; 257 | 258 | if tun_name.as_bytes_with_nul().len() > IFNAMSIZ { 259 | return Err(Error::NameTooLong); 260 | } 261 | 262 | let mut req = self.request(); 263 | ptr::copy_nonoverlapping( 264 | tun_name.as_ptr() as *const c_char, 265 | req.ifr_ifru.ifru_newname.as_mut_ptr(), 266 | value.len(), 267 | ); 268 | 269 | if let Err(err) = siocsifname(self.ctl.as_raw_fd(), &req) { 270 | return Err(std::io::Error::from(err).into()); 271 | } 272 | 273 | self.tun_name = value.into(); 274 | 275 | Ok(()) 276 | } 277 | } 278 | 279 | fn enabled(&mut self, value: bool) -> Result<()> { 280 | unsafe { 281 | let mut req = self.request(); 282 | 283 | if let Err(err) = siocgifflags(self.ctl.as_raw_fd(), &mut req) { 284 | return Err(std::io::Error::from(err).into()); 285 | } 286 | 287 | if value { 288 | req.ifr_ifru.ifru_flags |= (IFF_UP | IFF_RUNNING) as c_short; 289 | } else { 290 | req.ifr_ifru.ifru_flags &= !(IFF_UP as c_short); 291 | } 292 | 293 | if let Err(err) = siocsifflags(self.ctl.as_raw_fd(), &req) { 294 | return Err(std::io::Error::from(err).into()); 295 | } 296 | 297 | Ok(()) 298 | } 299 | } 300 | 301 | fn address(&self) -> Result { 302 | unsafe { 303 | let mut req = self.request(); 304 | if let Err(err) = siocgifaddr(self.ctl.as_raw_fd(), &mut req) { 305 | return Err(std::io::Error::from(err).into()); 306 | } 307 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 308 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 309 | } 310 | } 311 | 312 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 313 | unsafe { 314 | let mut req = self.request(); 315 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_addr, OVERWRITE_SIZE); 316 | if let Err(err) = siocsifaddr(self.ctl.as_raw_fd(), &req) { 317 | return Err(std::io::Error::from(err).into()); 318 | } 319 | Ok(()) 320 | } 321 | } 322 | 323 | fn destination(&self) -> Result { 324 | unsafe { 325 | let mut req = self.request(); 326 | if let Err(err) = siocgifdstaddr(self.ctl.as_raw_fd(), &mut req) { 327 | return Err(std::io::Error::from(err).into()); 328 | } 329 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_dstaddr); 330 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 331 | } 332 | } 333 | 334 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 335 | unsafe { 336 | let mut req = self.request(); 337 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_dstaddr, OVERWRITE_SIZE); 338 | if let Err(err) = siocsifdstaddr(self.ctl.as_raw_fd(), &req) { 339 | return Err(std::io::Error::from(err).into()); 340 | } 341 | Ok(()) 342 | } 343 | } 344 | 345 | fn broadcast(&self) -> Result { 346 | unsafe { 347 | let mut req = self.request(); 348 | if let Err(err) = siocgifbrdaddr(self.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_broadaddr); 352 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 353 | } 354 | } 355 | 356 | fn set_broadcast(&mut self, value: IpAddr) -> Result<()> { 357 | unsafe { 358 | let mut req = self.request(); 359 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_broadaddr, OVERWRITE_SIZE); 360 | if let Err(err) = siocsifbrdaddr(self.ctl.as_raw_fd(), &req) { 361 | return Err(std::io::Error::from(err).into()); 362 | } 363 | Ok(()) 364 | } 365 | } 366 | 367 | fn netmask(&self) -> Result { 368 | unsafe { 369 | let mut req = self.request(); 370 | if let Err(err) = siocgifnetmask(self.ctl.as_raw_fd(), &mut req) { 371 | return Err(std::io::Error::from(err).into()); 372 | } 373 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_netmask); 374 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 375 | } 376 | } 377 | 378 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 379 | unsafe { 380 | let mut req = self.request(); 381 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_netmask, OVERWRITE_SIZE); 382 | if let Err(err) = siocsifnetmask(self.ctl.as_raw_fd(), &req) { 383 | return Err(std::io::Error::from(err).into()); 384 | } 385 | Ok(()) 386 | } 387 | } 388 | 389 | fn mtu(&self) -> Result { 390 | unsafe { 391 | let mut req = self.request(); 392 | 393 | if let Err(err) = siocgifmtu(self.ctl.as_raw_fd(), &mut req) { 394 | return Err(std::io::Error::from(err).into()); 395 | } 396 | 397 | req.ifr_ifru 398 | .ifru_mtu 399 | .try_into() 400 | .map_err(|_| Error::TryFromIntError) 401 | } 402 | } 403 | 404 | fn set_mtu(&mut self, value: u16) -> Result<()> { 405 | unsafe { 406 | let mut req = self.request(); 407 | req.ifr_ifru.ifru_mtu = value as i32; 408 | 409 | if let Err(err) = siocsifmtu(self.ctl.as_raw_fd(), &req) { 410 | return Err(std::io::Error::from(err).into()); 411 | } 412 | self.tun.set_mtu(value); 413 | Ok(()) 414 | } 415 | } 416 | 417 | fn packet_information(&self) -> bool { 418 | self.tun.packet_information() 419 | } 420 | } 421 | 422 | impl AsRawFd for Device { 423 | fn as_raw_fd(&self) -> RawFd { 424 | self.tun.as_raw_fd() 425 | } 426 | } 427 | 428 | impl IntoRawFd for Device { 429 | fn into_raw_fd(self) -> RawFd { 430 | self.tun.into_raw_fd() 431 | } 432 | } 433 | 434 | impl From for c_short { 435 | fn from(layer: Layer) -> Self { 436 | match layer { 437 | Layer::L2 => IFF_TAP as c_short, 438 | Layer::L3 => IFF_TUN as c_short, 439 | } 440 | } 441 | } 442 | -------------------------------------------------------------------------------- /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 `tun` crate 57 | /// (i.e. the packets delivered from/to `tun` crate must always NOT contain packet information) -- end note]. 58 | #[deprecated( 59 | since = "0.7.0", 60 | note = "No effect applies to the packets delivered from/to tun since the packets always contain no header on all platforms." 61 | )] 62 | pub fn packet_information(&mut self, value: bool) -> &mut Self { 63 | self.packet_information = value; 64 | self 65 | } 66 | 67 | /// Indicated whether tun running in root privilege, 68 | /// since some operations need it such as assigning IP/netmask/destination etc. 69 | pub fn ensure_root_privileges(&mut self, value: bool) -> &mut Self { 70 | self.ensure_root_privileges = value; 71 | self 72 | } 73 | 74 | /// Enable / Disable IFF_NAPI flag. 75 | pub fn napi(&mut self, value: bool) -> &mut Self { 76 | self.napi = value; 77 | self 78 | } 79 | 80 | /// Enable / Disable IFF_VNET_HDR flag. 81 | pub fn vnet_hdr(&mut self, value: bool) -> &mut Self { 82 | self.vnet_hdr = value; 83 | self 84 | } 85 | } 86 | 87 | /// Create a TUN device with the given name. 88 | pub fn create(configuration: &Configuration) -> Result { 89 | Device::new(configuration) 90 | } 91 | -------------------------------------------------------------------------------- /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, Fd, ipaddr_to_sockaddr, sockaddr_union}, 23 | }, 24 | run_command::run_command, 25 | }; 26 | 27 | const OVERWRITE_SIZE: usize = std::mem::size_of::(); 28 | 29 | use libc::{ 30 | self, AF_INET, AF_SYS_CONTROL, AF_SYSTEM, IFF_RUNNING, IFF_UP, IFNAMSIZ, PF_SYSTEM, SOCK_DGRAM, 31 | SYSPROTO_CONTROL, UTUN_OPT_IFNAME, c_char, c_short, c_uint, c_void, sockaddr, socklen_t, 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 | pub(crate) 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 | config.platform_config.enable_routing, 176 | )?; 177 | 178 | Ok(device) 179 | } 180 | 181 | /// Prepare a new request. 182 | /// # Safety 183 | unsafe fn request(&self) -> Result { 184 | let tun_name = self.tun_name.as_ref().ok_or(Error::InvalidConfig)?; 185 | let mut req: libc::ifreq = unsafe { mem::zeroed() }; 186 | unsafe { 187 | ptr::copy_nonoverlapping( 188 | tun_name.as_ptr() as *const c_char, 189 | req.ifr_name.as_mut_ptr(), 190 | tun_name.len(), 191 | ) 192 | }; 193 | 194 | Ok(req) 195 | } 196 | 197 | /// Set the IPv4 alias of the device. 198 | fn set_alias( 199 | &mut self, 200 | addr: IpAddr, 201 | broadaddr: IpAddr, 202 | mask: IpAddr, 203 | enable_routing: bool, 204 | ) -> Result<()> { 205 | let IpAddr::V4(addr) = addr else { 206 | unimplemented!("do not support IPv6 yet") 207 | }; 208 | let IpAddr::V4(broadaddr) = broadaddr else { 209 | unimplemented!("do not support IPv6 yet") 210 | }; 211 | let IpAddr::V4(mask) = mask else { 212 | unimplemented!("do not support IPv6 yet") 213 | }; 214 | let tun_name = self.tun_name.as_ref().ok_or(Error::InvalidConfig)?; 215 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 216 | unsafe { 217 | let mut req: ifaliasreq = mem::zeroed(); 218 | ptr::copy_nonoverlapping( 219 | tun_name.as_ptr() as *const c_char, 220 | req.ifra_name.as_mut_ptr(), 221 | tun_name.len(), 222 | ); 223 | 224 | req.ifra_addr = sockaddr_union::from((addr, 0)).addr; 225 | req.ifra_broadaddr = sockaddr_union::from((broadaddr, 0)).addr; 226 | req.ifra_mask = sockaddr_union::from((mask, 0)).addr; 227 | 228 | if let Err(err) = siocaifaddr(ctl.as_raw_fd(), &req) { 229 | return Err(std::io::Error::from(err).into()); 230 | } 231 | if enable_routing { 232 | let route = Route { 233 | addr, 234 | netmask: mask, 235 | dest: broadaddr, 236 | }; 237 | if let Err(e) = self.set_route(route) { 238 | log::warn!("{e:?}"); 239 | } 240 | } 241 | Ok(()) 242 | } 243 | } 244 | 245 | /// Split the interface into a `Reader` and `Writer`. 246 | pub fn split(self) -> (posix::Reader, posix::Writer) { 247 | (self.tun.reader, self.tun.writer) 248 | } 249 | 250 | /// Set non-blocking mode 251 | #[allow(dead_code)] 252 | pub(crate) fn set_nonblock(&self) -> std::io::Result<()> { 253 | self.tun.set_nonblock() 254 | } 255 | 256 | fn set_route(&mut self, route: Route) -> Result<()> { 257 | if let Some(v) = &self.route { 258 | let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(v.netmask)) 259 | .map_err(|_| Error::InvalidConfig)?; 260 | let network = ipnet::Ipv4Net::new(v.addr, prefix_len) 261 | .map_err(|e| Error::InvalidConfig)? 262 | .network(); 263 | // command: route -n delete -net 10.0.0.0/24 10.0.0.1 264 | let args = [ 265 | "-n", 266 | "delete", 267 | "-net", 268 | &format!("{}/{}", network, prefix_len), 269 | &v.dest.to_string(), 270 | ]; 271 | run_command("route", &args)?; 272 | log::info!("route {}", args.join(" ")); 273 | } 274 | 275 | // command: route -n add -net 10.0.0.9/24 10.0.0.1 276 | let prefix_len = ipnet::ip_mask_to_prefix(IpAddr::V4(route.netmask)) 277 | .map_err(|_| Error::InvalidConfig)?; 278 | let args = [ 279 | "-n", 280 | "add", 281 | "-net", 282 | &format!("{}/{}", route.addr, prefix_len), 283 | &route.dest.to_string(), 284 | ]; 285 | run_command("route", &args)?; 286 | log::info!("route {}", args.join(" ")); 287 | self.route = Some(route); 288 | Ok(()) 289 | } 290 | 291 | /// Recv a packet from tun device 292 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 293 | self.tun.recv(buf) 294 | } 295 | 296 | /// Send a packet to tun device 297 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 298 | self.tun.send(buf) 299 | } 300 | } 301 | 302 | impl Read for Device { 303 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 304 | self.tun.read(buf) 305 | } 306 | } 307 | 308 | impl Write for Device { 309 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 310 | self.tun.write(buf) 311 | } 312 | 313 | fn flush(&mut self) -> std::io::Result<()> { 314 | self.tun.flush() 315 | } 316 | } 317 | 318 | impl AbstractDevice for Device { 319 | fn tun_index(&self) -> Result { 320 | let name = self.tun_name()?; 321 | Ok(posix::tun_name_to_index(&name)? as i32) 322 | } 323 | 324 | fn tun_name(&self) -> Result { 325 | self.tun_name.as_ref().cloned().ok_or(Error::InvalidConfig) 326 | } 327 | 328 | // XXX: Cannot set interface name on Darwin. 329 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 330 | Err(Error::InvalidName) 331 | } 332 | 333 | fn enabled(&mut self, value: bool) -> Result<()> { 334 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 335 | unsafe { 336 | let mut req = self.request()?; 337 | 338 | if let Err(err) = siocgifflags(ctl.as_raw_fd(), &mut req) { 339 | return Err(std::io::Error::from(err).into()); 340 | } 341 | 342 | if value { 343 | req.ifr_ifru.ifru_flags |= (IFF_UP | IFF_RUNNING) as c_short; 344 | } else { 345 | req.ifr_ifru.ifru_flags &= !(IFF_UP as c_short); 346 | } 347 | 348 | if let Err(err) = siocsifflags(ctl.as_raw_fd(), &req) { 349 | return Err(std::io::Error::from(err).into()); 350 | } 351 | 352 | Ok(()) 353 | } 354 | } 355 | 356 | fn address(&self) -> Result { 357 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 358 | unsafe { 359 | let mut req = self.request()?; 360 | if let Err(err) = siocgifaddr(ctl.as_raw_fd(), &mut req) { 361 | return Err(std::io::Error::from(err).into()); 362 | } 363 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 364 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 365 | } 366 | } 367 | 368 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 369 | let IpAddr::V4(value) = value else { 370 | unimplemented!("do not support IPv6 yet") 371 | }; 372 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 373 | unsafe { 374 | let mut req = self.request()?; 375 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_addr, OVERWRITE_SIZE); 376 | if let Err(err) = siocsifaddr(ctl.as_raw_fd(), &req) { 377 | return Err(std::io::Error::from(err).into()); 378 | } 379 | if let Some(mut route) = self.route { 380 | route.addr = value; 381 | self.set_route(route)?; 382 | } 383 | Ok(()) 384 | } 385 | } 386 | 387 | fn destination(&self) -> Result { 388 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 389 | unsafe { 390 | let mut req = self.request()?; 391 | if let Err(err) = siocgifdstaddr(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_dstaddr); 395 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 396 | } 397 | } 398 | 399 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 400 | let IpAddr::V4(value) = value else { 401 | unimplemented!("do not support IPv6 yet") 402 | }; 403 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 404 | unsafe { 405 | let mut req = self.request()?; 406 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_dstaddr, OVERWRITE_SIZE); 407 | if let Err(err) = siocsifdstaddr(ctl.as_raw_fd(), &req) { 408 | return Err(std::io::Error::from(err).into()); 409 | } 410 | if let Some(mut route) = self.route { 411 | route.dest = value; 412 | self.set_route(route)?; 413 | } 414 | Ok(()) 415 | } 416 | } 417 | 418 | /// Question on macOS 419 | fn broadcast(&self) -> Result { 420 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 421 | unsafe { 422 | let mut req = self.request()?; 423 | if let Err(err) = siocgifbrdaddr(ctl.as_raw_fd(), &mut req) { 424 | return Err(std::io::Error::from(err).into()); 425 | } 426 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_broadaddr); 427 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 428 | } 429 | } 430 | 431 | /// Question on macOS 432 | fn set_broadcast(&mut self, value: IpAddr) -> Result<()> { 433 | let IpAddr::V4(value) = value else { 434 | unimplemented!("do not support IPv6 yet") 435 | }; 436 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 437 | unsafe { 438 | let mut req = self.request()?; 439 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_broadaddr, OVERWRITE_SIZE); 440 | if let Err(err) = siocsifbrdaddr(ctl.as_raw_fd(), &req) { 441 | return Err(std::io::Error::from(err).into()); 442 | } 443 | Ok(()) 444 | } 445 | } 446 | 447 | fn netmask(&self) -> Result { 448 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 449 | unsafe { 450 | let mut req = self.request()?; 451 | if let Err(err) = siocgifnetmask(ctl.as_raw_fd(), &mut req) { 452 | return Err(std::io::Error::from(err).into()); 453 | } 454 | let sa = sockaddr_union::from(req.ifr_ifru.ifru_addr); 455 | Ok(std::net::SocketAddr::try_from(sa)?.ip()) 456 | } 457 | } 458 | 459 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 460 | let IpAddr::V4(value) = value else { 461 | unimplemented!("do not support IPv6 yet") 462 | }; 463 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 464 | unsafe { 465 | let mut req = self.request()?; 466 | // Note: Here should be `ifru_netmask`, but it is not defined in `ifreq`. 467 | ipaddr_to_sockaddr(value, 0, &mut req.ifr_ifru.ifru_addr, OVERWRITE_SIZE); 468 | if let Err(err) = siocsifnetmask(ctl.as_raw_fd(), &req) { 469 | return Err(std::io::Error::from(err).into()); 470 | } 471 | if let Some(mut route) = self.route { 472 | route.netmask = value; 473 | self.set_route(route)?; 474 | } 475 | Ok(()) 476 | } 477 | } 478 | 479 | fn mtu(&self) -> Result { 480 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 481 | unsafe { 482 | let mut req = self.request()?; 483 | 484 | if let Err(err) = siocgifmtu(ctl.as_raw_fd(), &mut req) { 485 | return Err(std::io::Error::from(err).into()); 486 | } 487 | 488 | req.ifr_ifru 489 | .ifru_mtu 490 | .try_into() 491 | .map_err(|_| Error::TryFromIntError) 492 | } 493 | } 494 | 495 | fn set_mtu(&mut self, value: u16) -> Result<()> { 496 | let ctl = self.ctl.as_ref().ok_or(Error::InvalidConfig)?; 497 | unsafe { 498 | let mut req = self.request()?; 499 | req.ifr_ifru.ifru_mtu = value as i32; 500 | 501 | if let Err(err) = siocsifmtu(ctl.as_raw_fd(), &req) { 502 | return Err(std::io::Error::from(err).into()); 503 | } 504 | self.tun.set_mtu(value); 505 | Ok(()) 506 | } 507 | } 508 | 509 | fn packet_information(&self) -> bool { 510 | self.tun.packet_information() 511 | } 512 | } 513 | 514 | impl AsRawFd for Device { 515 | fn as_raw_fd(&self) -> RawFd { 516 | self.tun.as_raw_fd() 517 | } 518 | } 519 | 520 | impl IntoRawFd for Device { 521 | fn into_raw_fd(self) -> RawFd { 522 | self.tun.into_raw_fd() 523 | } 524 | } 525 | -------------------------------------------------------------------------------- /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 | pub(crate) enable_routing: bool, 30 | } 31 | 32 | impl Default for PlatformConfig { 33 | fn default() -> Self { 34 | PlatformConfig { 35 | packet_information: true, // default is true in macOS 36 | enable_routing: true, 37 | } 38 | } 39 | } 40 | 41 | impl PlatformConfig { 42 | /// Enable or disable packet information, the first 4 bytes of 43 | /// each packet delivered from/to macOS underlying API is a header with flags and protocol type when enabled. 44 | /// 45 | /// - If we open an `utun` device, there always exist PI. 46 | /// 47 | /// - If we use `Network Extension` to build our App: 48 | /// 49 | /// - If get the fd from 50 | /// ```Objective-C 51 | /// int32_t tunFd = [[NEPacketTunnelProvider::packetFlow valueForKeyPath:@"socket.fileDescriptor"] intValue]; 52 | /// ``` 53 | /// there exist PI. 54 | /// 55 | /// - But if get packet from `[NEPacketTunnelProvider::packetFlow readPacketsWithCompletionHandler:]` 56 | /// and write packet via `[NEPacketTunnelProvider::packetFlow writePackets:withProtocols:]`, there is no PI. 57 | pub fn packet_information(&mut self, value: bool) -> &mut Self { 58 | self.packet_information = value; 59 | self 60 | } 61 | 62 | /// Do set or not setup route for utun interface automatically 63 | pub fn enable_routing(&mut self, value: bool) -> &mut Self { 64 | self.enable_routing = value; 65 | self 66 | } 67 | } 68 | 69 | /// Create a TUN device with the given name. 70 | pub fn create(configuration: &Configuration) -> Result { 71 | Device::new(configuration) 72 | } 73 | -------------------------------------------------------------------------------- /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::{IFNAMSIZ, c_char, c_uint, ifreq, sockaddr}; 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 | #[cfg(unix)] 20 | pub use posix::{Reader, Writer}; 21 | 22 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] 23 | pub(crate) mod linux; 24 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] 25 | pub use self::linux::{Device, PlatformConfig, create}; 26 | 27 | #[cfg(target_os = "freebsd")] 28 | pub(crate) mod freebsd; 29 | #[cfg(target_os = "freebsd")] 30 | pub use self::freebsd::{Device, PlatformConfig, create}; 31 | 32 | #[cfg(target_os = "macos")] 33 | pub(crate) mod macos; 34 | #[cfg(target_os = "macos")] 35 | pub use self::macos::{Device, PlatformConfig, create}; 36 | 37 | #[cfg(any(target_os = "ios", target_os = "tvos"))] 38 | pub(crate) mod ios; 39 | #[cfg(any(target_os = "ios", target_os = "tvos"))] 40 | pub use self::ios::{Device, PlatformConfig, create}; 41 | 42 | #[cfg(target_os = "android")] 43 | pub(crate) mod android; 44 | #[cfg(target_os = "android")] 45 | pub use self::android::{Device, PlatformConfig, create}; 46 | 47 | // Tip: OpenHarmony is a kind of Linux. 48 | #[cfg(target_env = "ohos")] 49 | pub(crate) mod ohos; 50 | #[cfg(target_env = "ohos")] 51 | pub use self::ohos::{Device, PlatformConfig, create}; 52 | 53 | #[cfg(target_os = "windows")] 54 | pub(crate) mod windows; 55 | #[cfg(target_os = "windows")] 56 | pub use self::windows::{Device, PlatformConfig, Reader, Tun, Writer, create}; 57 | 58 | #[cfg(test)] 59 | mod test { 60 | use crate::configuration::Configuration; 61 | use crate::device::AbstractDevice; 62 | use std::net::Ipv4Addr; 63 | 64 | #[test] 65 | fn create() { 66 | let dev = super::create( 67 | Configuration::default() 68 | .tun_name("utun6") 69 | .address("192.168.50.1") 70 | .netmask("255.255.0.0") 71 | .mtu(crate::DEFAULT_MTU) 72 | .up(), 73 | ) 74 | .unwrap(); 75 | 76 | assert_eq!( 77 | "192.168.50.1".parse::().unwrap(), 78 | dev.address().unwrap() 79 | ); 80 | 81 | assert_eq!( 82 | "255.255.0.0".parse::().unwrap(), 83 | dev.netmask().unwrap() 84 | ); 85 | 86 | assert_eq!(crate::DEFAULT_MTU, dev.mtu().unwrap()); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/platform/ohos/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 OpenHarmony. 26 | pub struct Device { 27 | pub(crate) 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 | #[allow(dead_code)] 69 | pub(crate) fn set_nonblock(&self) -> std::io::Result<()> { 70 | self.tun.set_nonblock() 71 | } 72 | 73 | /// Recv a packet from tun device 74 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 75 | self.tun.recv(buf) 76 | } 77 | 78 | /// Send a packet to tun device 79 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 80 | self.tun.send(buf) 81 | } 82 | } 83 | 84 | impl Read for Device { 85 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 86 | self.tun.read(buf) 87 | } 88 | } 89 | 90 | impl Write for Device { 91 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 92 | self.tun.write(buf) 93 | } 94 | 95 | fn flush(&mut self) -> std::io::Result<()> { 96 | self.tun.flush() 97 | } 98 | } 99 | 100 | impl AbstractDevice for Device { 101 | fn tun_index(&self) -> Result { 102 | Err(Error::NotImplemented) 103 | } 104 | 105 | fn tun_name(&self) -> Result { 106 | Ok("".to_string()) 107 | } 108 | 109 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 110 | Err(Error::NotImplemented) 111 | } 112 | 113 | fn enabled(&mut self, value: bool) -> Result<()> { 114 | Ok(()) 115 | } 116 | 117 | fn address(&self) -> Result { 118 | Err(Error::NotImplemented) 119 | } 120 | 121 | fn set_address(&mut self, _value: IpAddr) -> Result<()> { 122 | Ok(()) 123 | } 124 | 125 | fn destination(&self) -> Result { 126 | Err(Error::NotImplemented) 127 | } 128 | 129 | fn set_destination(&mut self, _value: IpAddr) -> Result<()> { 130 | Ok(()) 131 | } 132 | 133 | fn broadcast(&self) -> Result { 134 | Err(Error::NotImplemented) 135 | } 136 | 137 | fn set_broadcast(&mut self, _value: IpAddr) -> Result<()> { 138 | Ok(()) 139 | } 140 | 141 | fn netmask(&self) -> Result { 142 | Err(Error::NotImplemented) 143 | } 144 | 145 | fn set_netmask(&mut self, _value: IpAddr) -> Result<()> { 146 | Ok(()) 147 | } 148 | 149 | fn mtu(&self) -> Result { 150 | // TODO: must get the mtu from the underlying device driver 151 | Ok(self.tun.mtu()) 152 | } 153 | 154 | fn set_mtu(&mut self, value: u16) -> Result<()> { 155 | // TODO: must set the mtu to the underlying device driver 156 | self.tun.set_mtu(value); 157 | Ok(()) 158 | } 159 | 160 | fn packet_information(&self) -> bool { 161 | self.tun.packet_information() 162 | } 163 | } 164 | 165 | impl AsRawFd for Device { 166 | fn as_raw_fd(&self) -> RawFd { 167 | self.tun.as_raw_fd() 168 | } 169 | } 170 | 171 | impl IntoRawFd for Device { 172 | fn into_raw_fd(self) -> RawFd { 173 | self.tun.into_raw_fd() 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/platform/ohos/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 | //! OpenHarmony specific functionality. 16 | #![allow(unused_variables)] 17 | #![allow(dead_code)] 18 | mod device; 19 | pub use self::device::Device; 20 | 21 | use crate::configuration::Configuration; 22 | use crate::error::Result; 23 | 24 | /// OpenHarmony-only interface configuration. 25 | #[derive(Copy, Clone, Default, Debug)] 26 | pub struct PlatformConfig; 27 | 28 | impl PlatformConfig { 29 | /// Dummy functions for compatibility with Linux. 30 | pub fn packet_information(&mut self, _value: bool) -> &mut Self { 31 | self 32 | } 33 | 34 | /// Dummy functions for compatibility with Linux. 35 | pub fn ensure_root_privileges(&mut self, _value: bool) -> &mut Self { 36 | self 37 | } 38 | 39 | /// Dummy functions for compatibility with Linux. 40 | pub fn napi(&mut self, _value: bool) -> &mut Self { 41 | self 42 | } 43 | 44 | /// Dummy functions for compatibility with Linux. 45 | pub fn vnet_hdr(&mut self, _value: bool) -> &mut Self { 46 | self 47 | } 48 | } 49 | 50 | /// Create a TUN device with the given name. 51 | pub fn create(configuration: &Configuration) -> Result { 52 | Device::new(configuration) 53 | } 54 | -------------------------------------------------------------------------------- /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, F_GETFL, F_SETFL, O_NONBLOCK, fcntl}; 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(crate) 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 | #[inline] 45 | pub fn read(&self, buf: &mut [u8]) -> std::io::Result { 46 | let fd = self.as_raw_fd(); 47 | let amount = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) }; 48 | if amount < 0 { 49 | return Err(std::io::Error::last_os_error()); 50 | } 51 | Ok(amount as usize) 52 | } 53 | 54 | #[allow(dead_code)] 55 | #[inline] 56 | fn readv(&self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result { 57 | if bufs.len() > max_iov() { 58 | return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)); 59 | } 60 | let amount = unsafe { 61 | libc::readv( 62 | self.as_raw_fd(), 63 | bufs.as_mut_ptr() as *mut libc::iovec as *const libc::iovec, 64 | bufs.len() as libc::c_int, 65 | ) 66 | }; 67 | if amount < 0 { 68 | return Err(std::io::Error::last_os_error()); 69 | } 70 | Ok(amount as usize) 71 | } 72 | 73 | #[inline] 74 | pub fn write(&self, buf: &[u8]) -> std::io::Result { 75 | let fd = self.as_raw_fd(); 76 | let amount = unsafe { libc::write(fd, buf.as_ptr() as *const _, buf.len()) }; 77 | if amount < 0 { 78 | return Err(std::io::Error::last_os_error()); 79 | } 80 | Ok(amount as usize) 81 | } 82 | 83 | #[allow(dead_code)] 84 | #[inline] 85 | pub fn writev(&self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result { 86 | if bufs.len() > max_iov() { 87 | return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)); 88 | } 89 | let amount = unsafe { 90 | libc::writev( 91 | self.as_raw_fd(), 92 | bufs.as_ptr() as *const libc::iovec, 93 | bufs.len() as libc::c_int, 94 | ) 95 | }; 96 | if amount < 0 { 97 | return Err(std::io::Error::last_os_error()); 98 | } 99 | Ok(amount as usize) 100 | } 101 | } 102 | 103 | impl AsRawFd for Fd { 104 | fn as_raw_fd(&self) -> RawFd { 105 | self.inner 106 | } 107 | } 108 | 109 | impl IntoRawFd for Fd { 110 | fn into_raw_fd(mut self) -> RawFd { 111 | let fd = self.inner; 112 | self.inner = -1; 113 | fd 114 | } 115 | } 116 | 117 | impl Drop for Fd { 118 | fn drop(&mut self) { 119 | if self.close_fd_on_drop && self.inner >= 0 { 120 | unsafe { libc::close(self.inner) }; 121 | } 122 | } 123 | } 124 | 125 | #[cfg(any( 126 | target_os = "dragonfly", 127 | target_os = "freebsd", 128 | target_os = "netbsd", 129 | target_os = "openbsd", 130 | target_vendor = "apple", 131 | ))] 132 | pub(crate) const fn max_iov() -> usize { 133 | libc::IOV_MAX as usize 134 | } 135 | 136 | #[cfg(any( 137 | target_os = "android", 138 | target_os = "emscripten", 139 | target_os = "linux", 140 | target_os = "nto", 141 | ))] 142 | pub(crate) const fn max_iov() -> usize { 143 | libc::UIO_MAXIOV as usize 144 | } 145 | -------------------------------------------------------------------------------- /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 | #[allow(unused_imports)] 19 | pub(crate) use sockaddr::{ipaddr_to_sockaddr, sockaddr_union}; 20 | 21 | mod fd; 22 | pub(crate) use self::fd::Fd; 23 | 24 | mod split; 25 | pub(crate) use self::split::Tun; 26 | pub use self::split::{Reader, Writer}; 27 | 28 | #[allow(dead_code)] 29 | pub fn tun_name_to_index(name: impl AsRef) -> std::io::Result { 30 | let name_cstr = std::ffi::CString::new(name.as_ref()).map_err(|_| { 31 | std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid interface name") 32 | })?; 33 | let result = unsafe { libc::if_nametoindex(name_cstr.as_ptr()) }; 34 | if result == 0 { 35 | Err(std::io::Error::last_os_error()) 36 | } else { 37 | Ok(result as _) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /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 unsafe { sa.addr_stor }.ss_family as libc::c_int { 18 | libc::AF_INET => { 19 | let sa_in = unsafe { 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 = unsafe { 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 | #[allow(dead_code)] 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 | unsafe { 74 | std::ptr::copy_nonoverlapping( 75 | &sa as *const _ as *const libc::c_void, 76 | addr as *mut _ as *mut libc::c_void, 77 | size.min(std::mem::size_of::()), 78 | ) 79 | }; 80 | } 81 | 82 | #[repr(C)] 83 | #[derive(Clone, Copy)] 84 | pub union sockaddr_union { 85 | pub addr_stor: libc::sockaddr_storage, 86 | pub addr6: libc::sockaddr_in6, 87 | pub addr4: libc::sockaddr_in, 88 | pub addr: libc::sockaddr, 89 | } 90 | 91 | impl From for sockaddr_union { 92 | fn from(addr: libc::sockaddr_storage) -> Self { 93 | sockaddr_union { addr_stor: addr } 94 | } 95 | } 96 | 97 | impl From for sockaddr_union { 98 | fn from(addr: libc::sockaddr_in6) -> Self { 99 | sockaddr_union { addr6: addr } 100 | } 101 | } 102 | 103 | impl From for sockaddr_union { 104 | fn from(addr: libc::sockaddr_in) -> Self { 105 | sockaddr_union { addr4: addr } 106 | } 107 | } 108 | 109 | impl From for sockaddr_union { 110 | fn from(addr: libc::sockaddr) -> Self { 111 | sockaddr_union { addr } 112 | } 113 | } 114 | 115 | impl From for sockaddr_union { 116 | fn from(addr: std::net::SocketAddr) -> Self { 117 | rs_addr_to_sockaddr(addr) 118 | } 119 | } 120 | 121 | impl TryFrom for std::net::SocketAddr { 122 | type Error = std::io::Error; 123 | 124 | fn try_from(addr: sockaddr_union) -> Result { 125 | unsafe { sockaddr_to_rs_addr(&addr).ok_or(std::io::ErrorKind::InvalidInput.into()) } 126 | } 127 | } 128 | 129 | impl> From<(T, u16)> for sockaddr_union { 130 | fn from((ip, port): (T, u16)) -> Self { 131 | let ip: std::net::IpAddr = ip.into(); 132 | rs_addr_to_sockaddr(std::net::SocketAddr::new(ip, port)) 133 | } 134 | } 135 | 136 | #[test] 137 | fn test_conversion() { 138 | let old = std::net::SocketAddr::new([127, 0, 0, 1].into(), 0x0208); 139 | let addr = rs_addr_to_sockaddr(old); 140 | unsafe { 141 | if cfg!(target_endian = "big") { 142 | assert_eq!(0x7f000001, addr.addr4.sin_addr.s_addr); 143 | assert_eq!(0x0208, addr.addr4.sin_port); 144 | } else if cfg!(target_endian = "little") { 145 | assert_eq!(0x0100007f, addr.addr4.sin_addr.s_addr); 146 | assert_eq!(0x0802, addr.addr4.sin_port); 147 | } else { 148 | unreachable!(); 149 | } 150 | }; 151 | let ip = unsafe { sockaddr_to_rs_addr(&addr).unwrap() }; 152 | assert_eq!(ip, old); 153 | 154 | let old = std::net::SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0x0208); 155 | let addr = rs_addr_to_sockaddr(old); 156 | let ip = unsafe { sockaddr_to_rs_addr(&addr).unwrap() }; 157 | assert_eq!(ip, old); 158 | 159 | let old = std::net::IpAddr::V4([10, 0, 0, 33].into()); 160 | let mut addr: sockaddr_union = unsafe { std::mem::zeroed() }; 161 | let size = std::mem::size_of::(); 162 | unsafe { ipaddr_to_sockaddr(old, 0x0208, &mut addr.addr, size) }; 163 | let ip = unsafe { sockaddr_to_rs_addr(&addr).unwrap() }; 164 | assert_eq!(ip, std::net::SocketAddr::new(old, 0x0208)); 165 | } 166 | -------------------------------------------------------------------------------- /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::PACKET_INFORMATION_LENGTH as PIL; 16 | use crate::platform::posix::Fd; 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", target_os = "tvos"))] 45 | const TUN_PROTO_IP6: [u8; PIL] = (libc::AF_INET6 as u32).to_be_bytes(); 46 | #[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos"))] 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 amount < self.offset { 105 | let e = format!("Read amount {amount} is less than offset {}", self.offset); 106 | return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e)); 107 | } 108 | if self.offset != 0 { 109 | in_buf.put_slice(&local_buf[self.offset..amount]); 110 | } 111 | Ok(amount - self.offset) 112 | } 113 | } 114 | 115 | impl Read for Reader { 116 | fn read(&mut self, mut buf: &mut [u8]) -> std::io::Result { 117 | let either_buf = if self.offset != 0 { 118 | let len = buf.len() + self.offset; 119 | if len > self.buf.len() { 120 | self.buf.resize(len, 0_u8); 121 | } 122 | &mut self.buf[..len] 123 | } else { 124 | &mut *buf 125 | }; 126 | let amount = self.fd.read(either_buf)?; 127 | if amount < self.offset { 128 | let e = format!("Read amount {amount} is less than offset {}", self.offset); 129 | return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e)); 130 | } 131 | if self.offset != 0 { 132 | buf.put_slice(&self.buf[self.offset..amount]); 133 | } 134 | Ok(amount - self.offset) 135 | } 136 | } 137 | 138 | impl AsRawFd for Reader { 139 | fn as_raw_fd(&self) -> RawFd { 140 | self.fd.as_raw_fd() 141 | } 142 | } 143 | 144 | /// Write-only end for a file descriptor. 145 | pub struct Writer { 146 | pub(crate) fd: Arc, 147 | pub(crate) offset: usize, 148 | pub(crate) buf: Vec, 149 | pub(crate) mtu: u16, 150 | } 151 | 152 | impl Writer { 153 | pub(crate) fn set_mtu(&mut self, value: u16) { 154 | self.mtu = value; 155 | self.buf.resize(value as usize + self.offset, 0); 156 | } 157 | 158 | pub(crate) fn send(&self, in_buf: &[u8]) -> std::io::Result { 159 | const STACK_BUF_LEN: usize = crate::DEFAULT_MTU as usize + PIL; 160 | let in_buf_len = in_buf.len() + self.offset; 161 | 162 | // The following logic is to prevent dynamically allocating Vec on every send 163 | // As long as the MTU is set to value lesser than 1500, this api uses `stack_buf` 164 | // and avoids `Vec` allocation 165 | let mut dynamic_buf: Vec; 166 | let mut fixed_buf: [u8; STACK_BUF_LEN]; 167 | let local_buf = if in_buf_len > STACK_BUF_LEN && self.offset != 0 { 168 | dynamic_buf = vec![0_u8; in_buf_len]; 169 | &mut dynamic_buf[..] 170 | } else { 171 | fixed_buf = [0_u8; STACK_BUF_LEN]; 172 | &mut fixed_buf 173 | }; 174 | 175 | let either_buf = if self.offset != 0 { 176 | let ipv6 = is_ipv6(in_buf)?; 177 | if let Some(header) = generate_packet_information(true, ipv6) { 178 | (&mut local_buf[..self.offset]).put_slice(header.as_ref()); 179 | (&mut local_buf[self.offset..in_buf_len]).put_slice(in_buf); 180 | &local_buf[..in_buf_len] 181 | } else { 182 | in_buf 183 | } 184 | } else { 185 | in_buf 186 | }; 187 | let amount = self.fd.write(either_buf)?; 188 | if amount < self.offset { 189 | let e = format!("write returned {amount} less than offset {}", self.offset); 190 | return Err(std::io::Error::other(e)); 191 | } 192 | Ok(amount - self.offset) 193 | } 194 | } 195 | 196 | impl Write for Writer { 197 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 198 | let buf = if self.offset != 0 { 199 | let ipv6 = is_ipv6(buf)?; 200 | if let Some(header) = generate_packet_information(true, ipv6) { 201 | let len = self.offset + buf.len(); 202 | if len > self.buf.len() { 203 | self.buf.resize(len, 0_u8); 204 | } 205 | (&mut self.buf[..self.offset]).put_slice(header.as_ref()); 206 | (&mut self.buf[self.offset..len]).put_slice(buf); 207 | &self.buf[..len] 208 | } else { 209 | buf 210 | } 211 | } else { 212 | buf 213 | }; 214 | let amount = self.fd.write(buf)?; 215 | if amount < self.offset { 216 | let e = format!("write returned {amount} less than offset {}", self.offset); 217 | return Err(std::io::Error::other(e)); 218 | } 219 | Ok(amount - self.offset) 220 | } 221 | 222 | fn flush(&mut self) -> std::io::Result<()> { 223 | Ok(()) 224 | } 225 | } 226 | 227 | impl AsRawFd for Writer { 228 | fn as_raw_fd(&self) -> RawFd { 229 | self.fd.as_raw_fd() 230 | } 231 | } 232 | 233 | pub struct Tun { 234 | pub(crate) reader: Reader, 235 | pub(crate) writer: Writer, 236 | pub(crate) mtu: u16, 237 | pub(crate) packet_information: bool, 238 | } 239 | 240 | impl Tun { 241 | pub(crate) fn new(fd: Fd, mtu: u16, packet_information: bool) -> Self { 242 | let fd = Arc::new(fd); 243 | let offset = if packet_information { PIL } else { 0 }; 244 | Self { 245 | reader: Reader { 246 | fd: fd.clone(), 247 | offset, 248 | buf: vec![0; mtu as usize + offset], 249 | mtu, 250 | }, 251 | writer: Writer { 252 | fd, 253 | offset, 254 | buf: vec![0; mtu as usize + offset], 255 | mtu, 256 | }, 257 | mtu, 258 | packet_information, 259 | } 260 | } 261 | 262 | #[allow(dead_code)] 263 | pub(crate) fn set_nonblock(&self) -> std::io::Result<()> { 264 | self.reader.fd.set_nonblock() 265 | } 266 | 267 | pub fn set_mtu(&mut self, value: u16) { 268 | self.mtu = value; 269 | self.reader.set_mtu(value); 270 | self.writer.set_mtu(value); 271 | } 272 | 273 | #[allow(dead_code)] 274 | pub fn mtu(&self) -> u16 { 275 | self.mtu 276 | } 277 | 278 | pub fn packet_information(&self) -> bool { 279 | self.packet_information 280 | } 281 | 282 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 283 | self.reader.recv(buf) 284 | } 285 | 286 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 287 | self.writer.send(buf) 288 | } 289 | } 290 | 291 | impl Read for Tun { 292 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 293 | self.reader.read(buf) 294 | } 295 | } 296 | 297 | impl Write for Tun { 298 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 299 | self.writer.write(buf) 300 | } 301 | 302 | fn flush(&mut self) -> std::io::Result<()> { 303 | self.writer.flush() 304 | } 305 | } 306 | 307 | impl AsRawFd for Tun { 308 | fn as_raw_fd(&self) -> RawFd { 309 | self.reader.as_raw_fd() 310 | } 311 | } 312 | 313 | impl IntoRawFd for Tun { 314 | fn into_raw_fd(self) -> RawFd { 315 | drop(self.writer); 316 | // guarantee fd is the unique owner such that Arc::into_inner can return some 317 | let fd = Arc::into_inner(self.reader.fd).unwrap(); // panic if accident 318 | fd.into_raw_fd() 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /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::Layer; 20 | use crate::configuration::Configuration; 21 | use crate::device::AbstractDevice; 22 | use crate::error::{Error, Result}; 23 | use crate::run_command::run_command; 24 | use wintun_bindings::{Adapter, MAX_RING_CAPACITY, Session, load_from_path}; 25 | 26 | /// A TUN device using the wintun driver. 27 | pub struct Device { 28 | pub(crate) tun: Tun, 29 | mtu: u16, 30 | } 31 | 32 | impl Device { 33 | /// Create a new `Device` for the given `Configuration`. 34 | pub fn new(config: &Configuration) -> Result { 35 | let layer = config.layer.unwrap_or(Layer::L3); 36 | if layer == Layer::L3 { 37 | let wintun_file = &config.platform_config.wintun_file; 38 | let wintun = unsafe { load_from_path(wintun_file)? }; 39 | let tun_name = config.tun_name.as_deref().unwrap_or("wintun"); 40 | let guid = config.platform_config.device_guid; 41 | let adapter = match Adapter::open(&wintun, tun_name) { 42 | Ok(a) => a, 43 | Err(e) => { 44 | log::debug!("failed to open adapter: {}", e); 45 | Adapter::create(&wintun, tun_name, tun_name, guid)? 46 | } 47 | }; 48 | if let Some(metric) = config.metric { 49 | // command: netsh interface ip set interface {index} metric={metric} 50 | let i = adapter.get_adapter_index()?.to_string(); 51 | let m = format!("metric={}", metric); 52 | run_command("netsh", &["interface", "ip", "set", "interface", &i, &m])?; 53 | } 54 | let address = config 55 | .address 56 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 2))); 57 | let mask = config 58 | .netmask 59 | .unwrap_or(IpAddr::V4(Ipv4Addr::new(255, 255, 255, 0))); 60 | let gateway = config.destination; 61 | adapter.set_network_addresses_tuple(address, mask, gateway)?; 62 | if let Some(dns_servers) = &config.platform_config.dns_servers { 63 | adapter.set_dns_servers(dns_servers)?; 64 | } 65 | if let Some(mtu) = config.mtu { 66 | adapter.set_mtu(mtu as _)?; 67 | } 68 | let capacity = config.ring_capacity.unwrap_or(MAX_RING_CAPACITY); 69 | let session = adapter.start_session(capacity)?; 70 | let mut device = Device { 71 | tun: Tun { session }, 72 | mtu: adapter.get_mtu()? as u16, 73 | }; 74 | 75 | // This is not needed since we use netsh to set the address. 76 | device.configure(config)?; 77 | 78 | Ok(device) 79 | } else if layer == Layer::L2 { 80 | todo!() 81 | } else { 82 | panic!("unknow layer {:?}", layer); 83 | } 84 | } 85 | 86 | pub fn split(self) -> (Reader, Writer) { 87 | let tun = Arc::new(self.tun); 88 | (Reader(tun.clone()), Writer(tun)) 89 | } 90 | 91 | /// Recv a packet from tun device 92 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 93 | self.tun.recv(buf) 94 | } 95 | 96 | /// Send a packet to tun device 97 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 98 | self.tun.send(buf) 99 | } 100 | } 101 | 102 | impl Read for Device { 103 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 104 | self.tun.read(buf) 105 | } 106 | } 107 | 108 | impl Write for Device { 109 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 110 | self.tun.write(buf) 111 | } 112 | 113 | fn flush(&mut self) -> std::io::Result<()> { 114 | self.tun.flush() 115 | } 116 | } 117 | 118 | impl AbstractDevice for Device { 119 | fn tun_index(&self) -> Result { 120 | Ok(self.tun.session.get_adapter().get_adapter_index()? as i32) 121 | } 122 | 123 | fn tun_name(&self) -> Result { 124 | Ok(self.tun.session.get_adapter().get_name()?) 125 | } 126 | 127 | fn set_tun_name(&mut self, value: &str) -> Result<()> { 128 | Ok(self.tun.session.get_adapter().set_name(value)?) 129 | } 130 | 131 | fn enabled(&mut self, _value: bool) -> Result<()> { 132 | Ok(()) 133 | } 134 | 135 | fn address(&self) -> Result { 136 | let addresses = self.tun.session.get_adapter().get_addresses()?; 137 | addresses 138 | .iter() 139 | .find_map(|a| match a { 140 | std::net::IpAddr::V4(a) => Some(std::net::IpAddr::V4(*a)), 141 | _ => None, 142 | }) 143 | .ok_or(Error::InvalidConfig) 144 | } 145 | 146 | fn set_address(&mut self, value: IpAddr) -> Result<()> { 147 | let IpAddr::V4(value) = value else { 148 | unimplemented!("do not support IPv6 yet") 149 | }; 150 | Ok(self.tun.session.get_adapter().set_address(value)?) 151 | } 152 | 153 | fn destination(&self) -> Result { 154 | // It's just the default gateway in windows. 155 | self.tun 156 | .session 157 | .get_adapter() 158 | .get_gateways()? 159 | .iter() 160 | .find_map(|a| match a { 161 | std::net::IpAddr::V4(a) => Some(std::net::IpAddr::V4(*a)), 162 | _ => None, 163 | }) 164 | .ok_or(Error::InvalidConfig) 165 | } 166 | 167 | fn set_destination(&mut self, value: IpAddr) -> Result<()> { 168 | let IpAddr::V4(value) = value else { 169 | unimplemented!("do not support IPv6 yet") 170 | }; 171 | // It's just set the default gateway in windows. 172 | Ok(self.tun.session.get_adapter().set_gateway(Some(value))?) 173 | } 174 | 175 | fn broadcast(&self) -> Result { 176 | Err(Error::NotImplemented) 177 | } 178 | 179 | fn set_broadcast(&mut self, value: IpAddr) -> Result<()> { 180 | log::debug!("set_broadcast {} is not need", value); 181 | Ok(()) 182 | } 183 | 184 | fn netmask(&self) -> Result { 185 | let current_addr = self.address()?; 186 | self.tun 187 | .session 188 | .get_adapter() 189 | .get_netmask_of_address(¤t_addr) 190 | .map_err(Error::WintunError) 191 | } 192 | 193 | fn set_netmask(&mut self, value: IpAddr) -> Result<()> { 194 | let IpAddr::V4(value) = value else { 195 | unimplemented!("do not support IPv6 yet") 196 | }; 197 | Ok(self.tun.session.get_adapter().set_netmask(value)?) 198 | } 199 | 200 | /// The return value is always `Ok(65535)` due to wintun 201 | fn mtu(&self) -> Result { 202 | Ok(self.mtu) 203 | } 204 | 205 | /// This setting has no effect since the mtu of wintun is always 65535 206 | fn set_mtu(&mut self, mtu: u16) -> Result<()> { 207 | self.tun.session.get_adapter().set_mtu(mtu as _)?; 208 | self.mtu = mtu; 209 | Ok(()) 210 | } 211 | 212 | fn packet_information(&self) -> bool { 213 | // Note: wintun does not support packet information 214 | false 215 | } 216 | } 217 | 218 | pub struct Tun { 219 | session: Arc, 220 | } 221 | 222 | impl Tun { 223 | pub fn get_session(&self) -> Arc { 224 | self.session.clone() 225 | } 226 | fn read_by_ref(&self, mut buf: &mut [u8]) -> std::io::Result { 227 | use std::io::{Error, ErrorKind::ConnectionAborted}; 228 | match self.session.receive_blocking() { 229 | Ok(pkt) => match std::io::copy(&mut pkt.bytes(), &mut buf) { 230 | Ok(n) => Ok(n as usize), 231 | Err(e) => Err(e), 232 | }, 233 | Err(e) => Err(Error::new(ConnectionAborted, e)), 234 | } 235 | } 236 | fn write_by_ref(&self, mut buf: &[u8]) -> std::io::Result { 237 | use std::io::{Error, ErrorKind::OutOfMemory}; 238 | let size = buf.len(); 239 | match self.session.allocate_send_packet(size as u16) { 240 | Err(e) => Err(Error::new(OutOfMemory, e)), 241 | Ok(mut packet) => match std::io::copy(&mut buf, &mut packet.bytes_mut()) { 242 | Ok(s) => { 243 | self.session.send_packet(packet); 244 | Ok(s as usize) 245 | } 246 | Err(e) => Err(e), 247 | }, 248 | } 249 | } 250 | 251 | /// Recv a packet from tun device 252 | pub fn recv(&self, buf: &mut [u8]) -> std::io::Result { 253 | self.read_by_ref(buf) 254 | } 255 | 256 | /// Send a packet to tun device 257 | pub fn send(&self, buf: &[u8]) -> std::io::Result { 258 | self.write_by_ref(buf) 259 | } 260 | } 261 | 262 | impl Read for Tun { 263 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 264 | self.read_by_ref(buf) 265 | } 266 | } 267 | 268 | impl Write for Tun { 269 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 270 | self.write_by_ref(buf) 271 | } 272 | 273 | fn flush(&mut self) -> std::io::Result<()> { 274 | Ok(()) 275 | } 276 | } 277 | 278 | // impl Drop for Tun { 279 | // fn drop(&mut self) { 280 | // // The session has implemented drop 281 | // if let Err(err) = self.session.shutdown() { 282 | // log::error!("failed to shutdown session: {:?}", err); 283 | // } 284 | // } 285 | // } 286 | 287 | #[repr(transparent)] 288 | pub struct Reader(Arc); 289 | 290 | impl Read for Reader { 291 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result { 292 | self.0.read_by_ref(buf) 293 | } 294 | } 295 | 296 | #[repr(transparent)] 297 | pub struct Writer(Arc); 298 | 299 | impl Write for Writer { 300 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 301 | self.0.write_by_ref(buf) 302 | } 303 | 304 | fn flush(&mut self) -> std::io::Result<()> { 305 | Ok(()) 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /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 | pub use device::{Device, Reader, Tun, Writer}; 22 | use std::ffi::OsString; 23 | 24 | /// Windows-only interface configuration. 25 | #[derive(Clone, Debug)] 26 | pub struct PlatformConfig { 27 | pub(crate) device_guid: Option, 28 | pub(crate) wintun_file: OsString, 29 | pub(crate) dns_servers: Option>, 30 | } 31 | 32 | impl Default for PlatformConfig { 33 | fn default() -> Self { 34 | Self { 35 | device_guid: None, 36 | wintun_file: "wintun.dll".into(), 37 | dns_servers: None, 38 | } 39 | } 40 | } 41 | 42 | impl PlatformConfig { 43 | pub fn device_guid(&mut self, device_guid: u128) { 44 | log::trace!("Windows configuration device GUID"); 45 | self.device_guid = Some(device_guid); 46 | } 47 | 48 | /// Use a custom path to the wintun.dll instead of looking in the working directory. 49 | /// Security note: It is up to the caller to ensure that the library can be safely loaded from 50 | /// the indicated path. 51 | /// 52 | /// [`wintun_file`](PlatformConfig::wintun_file) likes "path/to/wintun" or "path/to/wintun.dll". 53 | pub fn wintun_file>(&mut self, wintun_file: S) { 54 | self.wintun_file = wintun_file.into(); 55 | } 56 | 57 | pub fn dns_servers(&mut self, dns_servers: &[std::net::IpAddr]) { 58 | self.dns_servers = Some(dns_servers.to_vec()); 59 | } 60 | } 61 | 62 | /// Create a TUN device with the given name. 63 | pub fn create(configuration: &Configuration) -> Result { 64 | Device::new(configuration) 65 | } 66 | -------------------------------------------------------------------------------- /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::other(info)); 23 | } 24 | Ok(out.stdout) 25 | } 26 | --------------------------------------------------------------------------------