Add read and write functions for TunInterface

This adds read and write functionality for TunInterface.
This commit is contained in:
JettChenT 2023-05-29 10:36:10 +08:00 committed by Conrad Kramer
parent 9aa1951575
commit 82c4d218d7
5 changed files with 105 additions and 4 deletions

View file

@ -1,4 +1,7 @@
use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use std::{
io::{Error, Read},
os::fd::{AsRawFd, FromRawFd, IntoRawFd, RawFd},
};
mod queue;
@ -10,6 +13,7 @@ mod imp;
#[path = "linux/mod.rs"]
mod imp;
use fehler::throws;
pub use imp::TunInterface;
pub use queue::TunQueue;
@ -32,6 +36,19 @@ impl IntoRawFd for TunInterface {
self.socket.into_raw_fd()
}
}
impl TunInterface {
// #[throws]
// pub fn write(&self, buf: &[u8]) -> usize {
// self.socket.send(buf)?
// }
#[throws]
pub fn read(&mut self, buf: &mut [u8]) -> usize {
self.socket.read(buf)?
}
}
pub fn ifname_to_string(buf: [libc::c_char; libc::IFNAMSIZ]) -> String {
// TODO: Switch to `CStr::from_bytes_until_nul` when stabilized
unsafe {
@ -48,3 +65,39 @@ pub fn string_to_ifname(name: &str) -> [libc::c_char; libc::IFNAMSIZ] {
buf[..len].copy_from_slice(unsafe { &*(name.as_bytes() as *const _ as *const [libc::c_char]) });
buf
}
#[cfg(test)]
mod test {
use super::*;
use std::io::Write;
use std::io::{self, BufRead};
use std::net::Ipv4Addr;
#[throws]
#[test]
fn tst_read() {
// This test is interactive, you need to send a packet to any server through 192.168.1.10
// EG. `sudo route add 8.8.8.8 192.168.1.10`,
//`dig @8.8.8.8 hackclub.com`
let mut tun = TunInterface::new()?;
println!("tun name: {:?}", tun.name()?);
tun.set_ipv4_addr(Ipv4Addr::from([192, 168, 1, 10]))?;
println!("tun ip: {:?}", tun.ipv4_addr()?);
println!("Waiting for a packet...");
let buf = &mut [0u8; 1500];
let res = tun.read(buf);
println!("Received!");
assert!(res.is_ok());
}
#[test]
#[throws]
fn write_packets() {
let mut tun = TunInterface::new()?;
let mut buf = [0u8; 1500];
buf[0] = 6 << 4;
let bytes_written = tun.write(&buf)?;
assert_eq!(bytes_written, 1504);
}
}