Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clean code #74

Merged
merged 7 commits into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 91 additions & 37 deletions src/async/win/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use core::pin::Pin;
use core::task::{Context, Poll};
use std::io;
use std::io::{Error, Write};
use std::io::Error;

use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio_util::codec::Framed;
Expand All @@ -26,12 +26,17 @@ use crate::r#async::codec::*;

pub struct AsyncDevice {
inner: Device,
session: WinSession,
}

impl AsyncDevice {
/// Create a new `AsyncDevice` wrapping around a `Device`.
pub fn new(device: Device) -> io::Result<AsyncDevice> {
Ok(AsyncDevice { inner: device })
let session = WinSession::new(device.queue.get_session())?;
Ok(AsyncDevice {
inner: device,
session,
})
}
/// Returns a shared reference to the underlying Device object
pub fn get_ref(&self) -> &Device {
Expand All @@ -56,50 +61,41 @@ impl AsyncRead for AsyncDevice {
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let rbuf = buf.initialize_unfilled();
match Pin::new(&mut self.inner).poll_read(cx, rbuf) {
Poll::Ready(Ok(n)) => {
buf.advance(n);
Poll::Ready(Ok(()))
}
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
Poll::Pending => Poll::Pending,
}
Pin::new(&mut self.session).poll_read(cx, buf)
}
}

impl AsyncWrite for AsyncDevice {
fn poll_write(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, Error>> {
match self.inner.write(buf) {
Ok(n) => Poll::Ready(Ok(n)),
Err(e) => Poll::Ready(Err(e)),
}
Pin::new(&mut self.session).poll_write(cx, buf)
}

fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
match self.inner.flush() {
Ok(n) => Poll::Ready(Ok(n)),
Err(e) => Poll::Ready(Err(e)),
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
Pin::new(&mut self.session).poll_flush(cx)
}

fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
Poll::Ready(Ok(()))
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
Pin::new(&mut self.session).poll_shutdown(cx)
}
}

pub struct AsyncQueue {
inner: Queue,
session: WinSession,
}

impl AsyncQueue {
/// Create a new `AsyncQueue` wrapping around a `Queue`.
pub fn new(queue: Queue) -> io::Result<AsyncQueue> {
Ok(AsyncQueue { inner: queue })
let session = WinSession::new(queue.get_session())?;
Ok(AsyncQueue {
inner: queue,
session,
})
}
/// Returns a shared reference to the underlying Queue object
pub fn get_ref(&self) -> &Queue {
Expand All @@ -124,29 +120,87 @@ impl AsyncRead for AsyncQueue {
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let rbuf = buf.initialize_unfilled();
match Pin::new(&mut self.inner).poll_read(cx, rbuf) {
Poll::Ready(Ok(n)) => {
buf.advance(n);
Poll::Ready(Ok(()))
}
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
Poll::Pending => Poll::Pending,
}
Pin::new(&mut self.session).poll_read(cx, buf)
}
}

impl AsyncWrite for AsyncQueue {
fn poll_write(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, Error>> {
match self.inner.write(buf) {
Ok(n) => Poll::Ready(Ok(n)),
Err(e) => Poll::Ready(Err(e)),
Pin::new(&mut self.session).poll_write(cx, buf)
}

fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
Pin::new(&mut self.session).poll_flush(cx)
}

fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
Pin::new(&mut self.session).poll_shutdown(cx)
}
}

struct WinSession {
session: std::sync::Arc<wintun::Session>,
receiver: tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
_task: std::thread::JoinHandle<()>,
}

impl WinSession {
fn new(session: std::sync::Arc<wintun::Session>) -> Result<WinSession, io::Error> {
let session_reader = session.clone();
let (receiver_tx, receiver_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
let task = std::thread::spawn(move || loop {
match session_reader.receive_blocking() {
Ok(packet) => {
if let Err(err) = receiver_tx.send(packet.bytes().to_vec()) {
log::error!("{}", err);
}
}
Err(err) => {
log::info!("{}", err);
break;
}
}
});

Ok(WinSession {
session,
receiver: receiver_rx,
_task: task,
})
}
}

impl AsyncRead for WinSession {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
match std::task::ready!(self.receiver.poll_recv(cx)) {
Some(bytes) => {
buf.put_slice(&bytes);
std::task::Poll::Ready(Ok(()))
}
None => std::task::Poll::Ready(Ok(())),
}
}
}

impl AsyncWrite for WinSession {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, Error>> {
let mut write_pack = self.session.allocate_send_packet(buf.len() as u16)?;
write_pack.bytes_mut().copy_from_slice(buf.as_ref());
self.session.send_packet(write_pack);
std::task::Poll::Ready(Ok(buf.len()))
}

fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
Poll::Ready(Ok(()))
Expand Down
81 changes: 4 additions & 77 deletions src/platform/windows/device.rs
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wintun::Adapter::create(&wintun, tun_name, tun_name, guid)? The last argument should be set as None here. I find the given guid can make the creation of the tun device fail, especially, the next time after the device was created successfully.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixed value prevents the number of device name aliases from growing indefinitely. so needn't to set to None.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixed value prevents the number of device name aliases from growing indefinitely. so needn't to set to None.

However, the device can fail to be created with the current arguments, during my practice test.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

post your log info here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chat from telegram?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

result

Run the example, then key ctrl+c to terminate the program, I repeated the process three times, and I got the error Error: WintunError(String("Failed to create adapter")). You can try to do this process

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure this error can be stably reproduced within three times

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

emm, I can't meet this issue. my OS is windows 11.
image

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This number will not changed while we set a guid.
image

Copy link
Collaborator Author

@ssrlive ssrlive Dec 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have add a switch for tun, now you can set guid to Some(u128) or None in the examples.

Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@

use std::io::{self, Read, Write};
use std::net::{IpAddr, Ipv4Addr};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::thread;
use std::vec::Vec;
use std::sync::Arc;

use wintun::Session;

Expand All @@ -28,7 +24,7 @@ use crate::error::*;

/// A TUN device using the wintun driver.
pub struct Device {
queue: Queue,
pub(crate) queue: Queue,
mtu: usize,
}

Expand All @@ -54,7 +50,6 @@ impl Device {
let mut device = Device {
queue: Queue {
session: Arc::new(session),
cached: Arc::new(Mutex::new(Vec::with_capacity(mtu))),
},
mtu,
};
Expand All @@ -64,14 +59,6 @@ impl Device {

Ok(device)
}

pub fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.queue).poll_read(cx, buf)
}
}

impl Read for Device {
Expand Down Expand Up @@ -183,7 +170,6 @@ impl D for Device {

fn set_mtu(&mut self, value: i32) -> Result<()> {
self.mtu = value as usize;
self.queue.cached = Arc::new(Mutex::new(Vec::with_capacity(self.mtu)));
Ok(())
}

Expand All @@ -194,70 +180,11 @@ impl D for Device {

pub struct Queue {
session: Arc<Session>,
cached: Arc<Mutex<Vec<u8>>>,
}

impl Queue {
pub fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
mut buf: &mut [u8],
) -> Poll<io::Result<usize>> {
{
let mut cached = self
.cached
.lock()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
if cached.len() > 0 {
let res = match io::copy(&mut cached.as_slice(), &mut buf) {
Ok(n) => Poll::Ready(Ok(n as usize)),
Err(e) => Poll::Ready(Err(e)),
};
cached.clear();
return res;
}
}
let reader_session = self.session.clone();
match reader_session.try_receive() {
Err(e) => Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, e))),
Ok(Some(packet)) => match io::copy(&mut packet.bytes(), &mut buf) {
Ok(n) => Poll::Ready(Ok(n as usize)),
Err(e) => Poll::Ready(Err(e)),
},
Ok(None) => {
let waker = cx.waker().clone();
let cached = self.cached.clone();
thread::spawn(move || {
match reader_session.receive_blocking() {
Ok(packet) => {
if let Ok(mut cached) = cached.lock() {
cached.extend_from_slice(packet.bytes());
} else {
log::error!("cached lock error in wintun reciever thread, packet will be dropped");
}
}
Err(e) => log::error!("receive_blocking error: {:?}", e),
}
waker.wake()
});
Poll::Pending
}
}
}

#[allow(dead_code)]
fn try_read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
let reader_session = self.session.clone();
match reader_session.try_receive() {
Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
Ok(op) => match op {
None => Ok(0),
Some(packet) => match io::copy(&mut packet.bytes(), &mut buf) {
Ok(s) => Ok(s as usize),
Err(e) => Err(e),
},
},
}
pub fn get_session(&self) -> Arc<Session> {
self.session.clone()
}
}

Expand Down