-
Notifications
You must be signed in to change notification settings - Fork 84
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
Add async support for DTLS #253
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -15,29 +15,63 @@ use crate::{ | |
io::{IoCallback, IoCallbackUnsafe}, | ||
}, | ||
}; | ||
use async_trait::async_trait; | ||
use std::{ | ||
future::Future, | ||
io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult}, | ||
pin::Pin, | ||
result::Result as StdResult, | ||
task::{Context as TaskContext, Poll}, | ||
}; | ||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; | ||
use tokio::{ | ||
io::{AsyncRead, AsyncWrite, ReadBuf}, | ||
macros::support::poll_fn, | ||
net::UdpSocket, | ||
}; | ||
|
||
/// Marker type for an IO implementation that implements both | ||
/// `tokio::io::AsyncRead` and `tokio::io::AsyncWrite`. | ||
pub enum AsyncStream {} | ||
|
||
// TODO: Add enum `AnyAsyncIo` as marker type for an IO implementation that | ||
// doesn't implement `tokio::io::AsyncRead` and `tokio::io::AsyncWrite`. | ||
/// Marker type for an IO implementation that | ||
/// doesn't implement [`tokio::io::AsyncRead`] and [`tokio::io::AsyncWrite`]. | ||
pub enum AnyAsyncIo {} | ||
|
||
/// Async read or write bytes or packets. | ||
/// | ||
/// Implementors represent a socket or file descriptor that can be read from or | ||
/// written to. | ||
/// | ||
/// By implementing [`AsyncIo`] you can wrap any type of | ||
/// [`AsyncIo`] with [`Context<T>::establish_async`] to protect that | ||
/// communication channel with (D)TLS. That [`Context`] then also implements | ||
/// [`AsyncIo`] so you can use it interchangeably. | ||
/// | ||
/// If you are using byte streams and are using [`tokio::io`], you don't need | ||
/// this trait and can rely on [`tokio::io::AsyncRead`] and | ||
/// [`tokio::io::AsyncWrite`] instead. | ||
#[async_trait] | ||
pub trait AsyncIo { | ||
async fn recv(&mut self, buf: &mut [u8]) -> IoResult<usize>; | ||
async fn send(&mut self, buf: &[u8]) -> IoResult<usize>; | ||
} | ||
|
||
#[async_trait] | ||
impl<T: AsyncIo + Send> AsyncIo for Context<T> { | ||
async fn recv(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||
self.io_mut() | ||
.ok_or(IoError::new(IoErrorKind::Other, "stream has been shutdown"))? | ||
.recv(buf) | ||
.await | ||
} | ||
|
||
// TODO: Add `AsyncIo` trait for async IO that that doesn't implement | ||
// `tokio::io::AsyncRead` and `tokio::io::AsyncWrite`. For example: | ||
// pub trait AsyncIo { | ||
// async fn recv(&mut self, buf: &mut [u8]) -> Result<usize>; | ||
// async fn send(&mut self, buf: &[u8]) -> Result<usize>; | ||
// } | ||
// Could implement by using `async-trait` crate or | ||
// #![feature(async_fn_in_trait)] or Associated Types | ||
async fn send(&mut self, buf: &[u8]) -> IoResult<usize> { | ||
self.io_mut() | ||
.ok_or(IoError::new(IoErrorKind::Other, "stream has been shutdown"))? | ||
.send(buf) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. How does MbedTLS buffering work in DTLS? |
||
.await | ||
} | ||
} | ||
|
||
impl<'a, 'b, 'c, IO: AsyncRead + AsyncWrite + std::marker::Unpin + 'static> IoCallback<AsyncStream> | ||
for (&'a mut TaskContext<'b>, &'c mut IO) | ||
|
@@ -62,6 +96,24 @@ impl<'a, 'b, 'c, IO: AsyncRead + AsyncWrite + std::marker::Unpin + 'static> IoCa | |
} | ||
} | ||
|
||
impl<'a, 'b, 'c, IO: AsyncIo> IoCallback<AnyAsyncIo> for (&'a mut TaskContext<'b>, &'c mut IO) { | ||
fn recv(&mut self, buf: &mut [u8]) -> Result<usize> { | ||
match Pin::new(&mut self.1.recv(buf)).poll(self.0) { | ||
Poll::Ready(Ok(n)) => Ok(n), | ||
Poll::Ready(Err(_)) => Err(Error::NetRecvFailed), | ||
Poll::Pending => Err(Error::SslWantRead), | ||
} | ||
} | ||
|
||
fn send(&mut self, buf: &[u8]) -> Result<usize> { | ||
match Pin::new(&mut self.1.send(buf)).poll(self.0) { | ||
Poll::Ready(Ok(n)) => Ok(n), | ||
Poll::Ready(Err(_)) => Err(Error::NetSendFailed), | ||
Poll::Pending => Err(Error::SslWantWrite), | ||
} | ||
} | ||
} | ||
|
||
impl<T: Unpin + AsyncRead + AsyncWrite + 'static> Context<T> { | ||
pub async fn establish_async<IoType>(&mut self, io: T, hostname: Option<&str>) -> Result<()> | ||
where | ||
|
@@ -121,14 +173,13 @@ where | |
return Poll::Ready(Err(IoError::new(IoErrorKind::Other, "stream has been shutdown"))); | ||
} | ||
|
||
self | ||
.with_bio_async(cx, |ssl_ctx| match ssl_ctx.async_write(buf) { | ||
Err(Error::SslPeerCloseNotify) => Poll::Ready(Ok(0)), | ||
Err(Error::SslWantWrite) => Poll::Pending, | ||
Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(e))), | ||
Ok(i) => Poll::Ready(Ok(i)), | ||
}) | ||
.unwrap_or_else(|| Poll::Ready(Err(crate::private::error_to_io_error(Error::NetSendFailed)))) | ||
self.with_bio_async(cx, |ssl_ctx| match ssl_ctx.async_write(buf) { | ||
Err(Error::SslPeerCloseNotify) => Poll::Ready(Ok(0)), | ||
Err(Error::SslWantWrite) => Poll::Pending, | ||
Err(e) => Poll::Ready(Err(crate::private::error_to_io_error(e))), | ||
Ok(i) => Poll::Ready(Ok(i)), | ||
}) | ||
.unwrap_or_else(|| Poll::Ready(Err(crate::private::error_to_io_error(Error::NetSendFailed)))) | ||
} | ||
|
||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<IoResult<()>> { | ||
|
@@ -168,4 +219,42 @@ where | |
} | ||
} | ||
|
||
// TODO: AsyncIo impl for tokio::net::UdpSocket | ||
/// A wrapper of [`tokio::net::UdpSocket`] on which | ||
/// [`tokio::net::UdpSocket::connect`] was successfully called. | ||
/// | ||
/// Construct this type using [`ConnectedAsyncUdpSocket::connect`]. | ||
pub struct ConnectedAsyncUdpSocket { | ||
socket: UdpSocket, | ||
} | ||
|
||
impl ConnectedAsyncUdpSocket { | ||
pub async fn connect<A: tokio::net::ToSocketAddrs>(socket: UdpSocket, addr: A) -> StdResult<Self, (IoError, UdpSocket)> { | ||
match socket.connect(addr).await { | ||
Ok(()) => Ok(ConnectedAsyncUdpSocket { socket }), | ||
Err(e) => Err((e, socket)), | ||
} | ||
} | ||
|
||
pub fn into_socket(self) -> UdpSocket { | ||
self.socket | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl AsyncIo for ConnectedAsyncUdpSocket { | ||
async fn recv(&mut self, buf: &mut [u8]) -> IoResult<usize> { | ||
poll_fn(|cx| { | ||
let mut buf = ReadBuf::new(buf); | ||
match self.socket.poll_recv(cx, &mut buf) { | ||
Poll::Ready(res) => res, | ||
Poll::Pending => return Poll::Pending, | ||
}?; | ||
Poll::Ready(Ok(buf.filled().len())) | ||
}) | ||
.await | ||
} | ||
|
||
async fn send(&mut self, buf: &[u8]) -> IoResult<usize> { | ||
poll_fn(|cx| self.socket.poll_send(cx, buf)).await | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This doesn't seem correct? You need to call mbedtls_ssl_write here. Same issue for recv. I think you can avoid async-trait and some headache if you model this with
fn poll_recv
andfn poll_send
instead ofasync fn
.