tokio-rustls/src/lib.rs

298 lines
8.5 KiB
Rust
Raw Normal View History

//! Asynchronous TLS/SSL streams for Tokio using [Rustls](https://github.com/ctz/rustls).
2017-02-22 05:03:21 +00:00
2017-03-16 02:15:06 +00:00
#[cfg_attr(feature = "tokio-proto", macro_use)] extern crate futures;
2017-03-30 07:39:11 +00:00
#[macro_use] extern crate tokio_io;
2017-02-21 03:52:43 +00:00
extern crate rustls;
extern crate webpki;
2017-02-21 03:52:43 +00:00
2017-02-22 05:30:01 +00:00
pub mod proto;
2017-02-21 03:52:43 +00:00
use std::io;
use std::sync::Arc;
use futures::{ Future, Poll, Async };
2017-03-16 02:15:06 +00:00
use tokio_io::{ AsyncRead, AsyncWrite };
2017-03-30 06:49:24 +00:00
use rustls::{
Session, ClientSession, ServerSession,
ClientConfig, ServerConfig
};
2017-02-21 03:52:43 +00:00
2017-02-22 05:03:21 +00:00
/// Extension trait for the `Arc<ClientConfig>` type in the `rustls` crate.
pub trait ClientConfigExt {
fn connect_async<S>(&self, domain: webpki::DNSNameRef, stream: S)
2017-02-21 03:52:43 +00:00
-> ConnectAsync<S>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite;
2017-02-21 03:52:43 +00:00
}
2017-02-22 05:03:21 +00:00
/// Extension trait for the `Arc<ServerConfig>` type in the `rustls` crate.
pub trait ServerConfigExt {
2017-02-21 03:52:43 +00:00
fn accept_async<S>(&self, stream: S)
-> AcceptAsync<S>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite;
2017-02-21 03:52:43 +00:00
}
2017-02-22 05:03:21 +00:00
/// Future returned from `ClientConfigExt::connect_async` which will resolve
/// once the connection handshake has finished.
2017-02-21 03:52:43 +00:00
pub struct ConnectAsync<S>(MidHandshake<S, ClientSession>);
2017-02-22 05:03:21 +00:00
/// Future returned from `ServerConfigExt::accept_async` which will resolve
/// once the accept handshake has finished.
2017-02-21 03:52:43 +00:00
pub struct AcceptAsync<S>(MidHandshake<S, ServerSession>);
2017-02-22 05:03:21 +00:00
impl ClientConfigExt for Arc<ClientConfig> {
fn connect_async<S>(&self, domain: webpki::DNSNameRef, stream: S)
2017-02-21 03:52:43 +00:00
-> ConnectAsync<S>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite
2017-02-21 03:52:43 +00:00
{
2017-05-26 10:22:03 +00:00
connect_async_with_session(stream, ClientSession::new(self, domain))
2017-02-21 03:52:43 +00:00
}
}
2017-05-26 10:22:03 +00:00
#[inline]
2017-05-26 08:38:02 +00:00
pub fn connect_async_with_session<S>(stream: S, session: ClientSession)
-> ConnectAsync<S>
where S: AsyncRead + AsyncWrite
{
ConnectAsync(MidHandshake {
inner: Some(TlsStream::new(stream, session))
})
}
2017-02-22 05:03:21 +00:00
impl ServerConfigExt for Arc<ServerConfig> {
2017-02-21 03:52:43 +00:00
fn accept_async<S>(&self, stream: S)
-> AcceptAsync<S>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite
2017-02-21 03:52:43 +00:00
{
2017-05-26 10:22:03 +00:00
accept_async_with_session(stream, ServerSession::new(self))
2017-02-21 03:52:43 +00:00
}
}
2017-05-26 10:22:03 +00:00
#[inline]
2017-05-26 08:38:02 +00:00
pub fn accept_async_with_session<S>(stream: S, session: ServerSession)
-> AcceptAsync<S>
where S: AsyncRead + AsyncWrite
{
AcceptAsync(MidHandshake {
inner: Some(TlsStream::new(stream, session))
})
}
2017-03-16 02:15:06 +00:00
impl<S: AsyncRead + AsyncWrite> Future for ConnectAsync<S> {
2017-02-21 03:52:43 +00:00
type Item = TlsStream<S, ClientSession>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.0.poll()
}
}
2017-03-16 02:15:06 +00:00
impl<S: AsyncRead + AsyncWrite> Future for AcceptAsync<S> {
2017-02-21 03:52:43 +00:00
type Item = TlsStream<S, ServerSession>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.0.poll()
}
}
struct MidHandshake<S, C> {
inner: Option<TlsStream<S, C>>
}
impl<S, C> Future for MidHandshake<S, C>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite, C: Session
2017-02-21 03:52:43 +00:00
{
type Item = TlsStream<S, C>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
let stream = self.inner.as_mut().unwrap();
2017-02-21 03:52:43 +00:00
if !stream.session.is_handshaking() { break };
match stream.do_io() {
Ok(()) => match (stream.eof, stream.session.is_handshaking()) {
(true, true) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
(false, true) => continue,
(..) => break
2017-02-24 11:28:19 +00:00
},
Err(e) => match (e.kind(), stream.session.is_handshaking()) {
(io::ErrorKind::WouldBlock, true) => return Ok(Async::NotReady),
(io::ErrorKind::WouldBlock, false) => break,
(..) => return Err(e)
}
2017-02-21 03:52:43 +00:00
}
}
Ok(Async::Ready(self.inner.take().unwrap()))
2017-02-21 03:52:43 +00:00
}
}
2017-02-22 05:03:21 +00:00
/// A wrapper around an underlying raw stream which implements the TLS or SSL
/// protocol.
#[derive(Debug)]
2017-02-21 03:52:43 +00:00
pub struct TlsStream<S, C> {
is_shutdown: bool,
2017-02-21 03:52:43 +00:00
eof: bool,
io: S,
session: C
}
2017-02-22 05:03:21 +00:00
impl<S, C> TlsStream<S, C> {
pub fn get_ref(&self) -> (&S, &C) {
(&self.io, &self.session)
}
pub fn get_mut(&mut self) -> (&mut S, &mut C) {
(&mut self.io, &mut self.session)
}
}
2017-02-21 03:52:43 +00:00
impl<S, C> TlsStream<S, C>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite, C: Session
2017-02-21 03:52:43 +00:00
{
#[inline]
pub fn new(io: S, session: C) -> TlsStream<S, C> {
TlsStream {
is_shutdown: false,
2017-02-21 03:52:43 +00:00
eof: false,
io: io,
session: session
}
}
pub fn do_io(&mut self) -> io::Result<()> {
loop {
2017-03-16 02:15:06 +00:00
let read_would_block = if !self.eof && self.session.wants_read() {
match self.session.read_tls(&mut self.io) {
Ok(0) => {
self.eof = true;
continue
},
Ok(_) => {
if let Err(err) = self.session.process_new_packets() {
// flush queued messages before returning an Err in
// order to send alerts instead of abruptly closing
// the socket
if self.session.wants_write() {
// ignore result to avoid masking original error
let _ = self.session.write_tls(&mut self.io);
}
return Err(io::Error::new(io::ErrorKind::Other, err));
}
2017-03-16 02:15:06 +00:00
continue
},
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => true,
Err(e) => return Err(e)
}
} else {
false
2017-02-21 03:52:43 +00:00
};
2017-03-16 02:15:06 +00:00
let write_would_block = if self.session.wants_write() {
match self.session.write_tls(&mut self.io) {
2017-02-21 03:52:43 +00:00
Ok(_) => continue,
2017-03-16 02:15:06 +00:00
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => true,
2017-02-21 03:52:43 +00:00
Err(e) => return Err(e)
2017-03-16 02:15:06 +00:00
}
} else {
false
2017-02-21 03:52:43 +00:00
};
if read_would_block || write_would_block {
return Err(io::Error::from(io::ErrorKind::WouldBlock));
} else {
return Ok(());
}
}
}
}
impl<S, C> io::Read for TlsStream<S, C>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite, C: Session
2017-02-21 03:52:43 +00:00
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
loop {
match self.session.read(buf) {
Ok(0) if !self.eof => self.do_io()?,
Ok(n) => return Ok(n),
Err(e) => if e.kind() == io::ErrorKind::ConnectionAborted {
self.do_io()?;
return if self.eof { Ok(0) } else { Err(e) }
} else {
return Err(e)
}
}
2017-02-21 03:52:43 +00:00
}
}
}
impl<S, C> io::Write for TlsStream<S, C>
2017-03-16 02:15:06 +00:00
where S: AsyncRead + AsyncWrite, C: Session
2017-02-21 03:52:43 +00:00
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2017-05-26 10:22:03 +00:00
if buf.is_empty() {
2017-05-26 09:59:51 +00:00
return Ok(0);
}
loop {
let output = self.session.write(buf)?;
while self.session.wants_write() {
match self.session.write_tls(&mut self.io) {
Ok(_) => (),
2017-05-26 10:22:03 +00:00
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => if output == 0 {
// Both rustls buffer and IO buffer are blocking.
return Err(io::Error::from(io::ErrorKind::WouldBlock));
} else {
break;
},
Err(e) => return Err(e)
}
}
if output > 0 {
// Already wrote something out.
return Ok(output);
}
}
2017-02-21 03:52:43 +00:00
}
fn flush(&mut self) -> io::Result<()> {
self.session.flush()?;
while self.session.wants_write() {
2017-02-21 03:52:43 +00:00
self.session.write_tls(&mut self.io)?;
}
2017-04-14 04:43:03 +00:00
self.io.flush()
2017-02-21 03:52:43 +00:00
}
}
2017-03-16 02:15:06 +00:00
impl<S, C> AsyncRead for TlsStream<S, C>
where
S: AsyncRead + AsyncWrite,
C: Session
{}
impl<S, C> AsyncWrite for TlsStream<S, C>
where
S: AsyncRead + AsyncWrite,
C: Session
{
fn shutdown(&mut self) -> Poll<(), io::Error> {
if !self.is_shutdown {
self.session.send_close_notify();
self.is_shutdown = true;
}
2017-04-14 04:43:03 +00:00
while self.session.wants_write() {
try_nb!(self.session.write_tls(&mut self.io));
}
try_nb!(self.io.flush());
2017-03-16 02:15:06 +00:00
self.io.shutdown()
}
}