1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*!
# Asynchronous Device Module
This module provides asynchronous I/O support for TUN/TAP interfaces through the [`AsyncDevice`] type.
## Overview
The async module enables non-blocking I/O operations on TUN/TAP devices, allowing you to efficiently
handle network traffic in async/await contexts. Two async runtime backends are supported:
- **Tokio**: Enable with the `async` or `async_tokio` feature
- **async-io**: Enable with the `async_io` feature (for async-std, smol, etc.)
**Important**: You must choose exactly one async runtime. Enabling both simultaneously will result
in a compile error.
## Feature Flags
- `async` (alias for `async_tokio`) - Use Tokio runtime
- `async_tokio` - Use Tokio runtime explicitly
- `async_io` - Use async-io runtime (for async-std, smol, and similar runtimes)
- `async_framed` - Enable framed I/O support with futures (requires one of the above)
## Usage with Tokio
Add to your `Cargo.toml`:
```toml
[dependencies]
tun-rs = { version = "2", features = ["async"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
```
Example:
```no_run
use tun_rs::DeviceBuilder;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let dev = DeviceBuilder::new()
.ipv4("10.0.0.1", 24, None)
.build_async()?;
let mut buf = vec![0u8; 65536];
loop {
let len = dev.recv(&mut buf).await?;
println!("Received {} bytes", len);
// Echo the packet back
dev.send(&buf[..len]).await?;
}
}
```
## Usage with async-std
Add to your `Cargo.toml`:
```toml
[dependencies]
tun-rs = { version = "2", features = ["async_io"] }
async-std = { version = "1", features = ["attributes"] }
```
Example:
```no_run
use tun_rs::DeviceBuilder;
#[async_std::main]
async fn main() -> std::io::Result<()> {
let dev = DeviceBuilder::new()
.ipv4("10.0.0.1", 24, None)
.build_async()?;
let mut buf = vec![0u8; 65536];
loop {
let len = dev.recv(&mut buf).await?;
println!("Received {} bytes", len);
}
}
```
## Device Types
### `AsyncDevice`
The main async device type. Created via `DeviceBuilder::build_async()`.
Takes ownership of the underlying file descriptor and closes it when dropped.
### `BorrowedAsyncDevice`
A borrowed variant that does not take ownership of the file descriptor.
Useful when the file descriptor is managed externally (e.g., on mobile platforms).
```no_run
# #[cfg(unix)]
# {
use tun_rs::BorrowedAsyncDevice;
async fn use_borrowed_fd(fd: std::os::fd::RawFd) -> std::io::Result<()> {
// SAFETY: fd must be a valid, open file descriptor
// This does NOT take ownership and will NOT close fd
let dev = unsafe { BorrowedAsyncDevice::borrow_raw(fd)? };
let mut buf = vec![0u8; 1500];
let len = dev.recv(&mut buf).await?;
// fd is still valid after dev is dropped
Ok(())
}
# }
```
## API Methods
### I/O Operations
- `recv(&self, buf: &mut [u8]) -> impl Future<Output = io::Result<usize>>`
- Asynchronously read a packet from the device
- `send(&self, buf: &[u8]) -> impl Future<Output = io::Result<usize>>`
- Asynchronously send a packet to the device
### Readiness Operations
- `readable(&self) -> impl Future<Output = io::Result<()>>`
- Wait until the device is readable
- `writable(&self) -> impl Future<Output = io::Result<()>>`
- Wait until the device is writable
These are useful for implementing custom I/O logic or integrating with other async primitives.
## Platform Support
Async I/O is supported on:
- Linux
- macOS
- Windows
- FreeBSD, OpenBSD, NetBSD
- Android, iOS (via borrowed file descriptors)
## Performance Considerations
- Async I/O is efficient for handling multiple connections or high concurrency
- For single-threaded blocking I/O, consider using [`crate::SyncDevice`] instead
- On Linux with offload enabled, use `recv_multiple`/`send_multiple` for best throughput
- Buffer sizes should be at least MTU + header overhead (typically 1500-65536 bytes)
## Error Handling
All async operations return `io::Result` types. Common errors include:
- `WouldBlock` (internally handled by async runtime)
- `Interrupted` (operation was interrupted, can be retried)
- `BrokenPipe` (device was closed)
- Platform-specific errors
## Safety Considerations
The `from_fd` and `borrow_raw` methods are `unsafe` because they:
- Require a valid, open file descriptor
- Can lead to double-close bugs if ownership is not managed correctly
- May cause undefined behavior if the fd is not a valid TUN/TAP device
Always ensure proper lifetime management when using these methods.
*/
pub
pub use AsyncDevice;
pub use AsyncDevice;
pub use AsyncDevice;
compile_error!
/// A borrowed asynchronous TUN/TAP device.
///
/// This type wraps an [`AsyncDevice`] but does not take ownership of the underlying file descriptor.
/// It's designed for scenarios where the file descriptor is managed externally, such as:
///
/// - iOS PacketTunnelProvider (NetworkExtension framework)
/// - Android VpnService
/// - Other FFI scenarios where file descriptor ownership is managed by foreign code
///
/// # Ownership and Lifetime
///
/// Unlike [`AsyncDevice`], `BorrowedAsyncDevice`:
/// - Does NOT close the file descriptor when dropped
/// - Requires the caller to manage the file descriptor's lifetime
/// - Must not outlive the actual file descriptor
///
/// # Example
///
/// ```no_run
/// # #[cfg(unix)]
/// # async fn example(fd: std::os::fd::RawFd) -> std::io::Result<()> {
/// use tun_rs::BorrowedAsyncDevice;
///
/// // SAFETY: Caller must ensure fd is valid and remains open
/// let device = unsafe { BorrowedAsyncDevice::borrow_raw(fd)? };
///
/// let mut buffer = vec![0u8; 1500];
/// let n = device.recv(&mut buffer).await?;
/// println!("Received {} bytes", n);
///
/// // fd is still valid after device is dropped
/// # Ok(())
/// # }
/// ```
///
/// # Safety
///
/// When using `borrow_raw`, you must ensure:
/// 1. The file descriptor is valid and open
/// 2. The file descriptor is a TUN/TAP device
/// 3. The file descriptor outlives the `BorrowedAsyncDevice`
/// 4. No other code closes the file descriptor while in use