I/O-free Rust coroutine to upgrade any plain stream to a secure one, based on io-stream and inspired by @duesee's blog post.
This library allows you to upgrade any plain stream into a secure one using an I/O-agnostic approach, based on 3 concepts:
A coroutine is an I/O-free, resumable and composable state machine that emits I/O requests. A coroutine is considered terminated when it does not emit I/O requests anymore.
See available coroutines at ./src.
A runtime contains all the I/O logic, and is responsible for processing I/O requests emitted by coroutines.
See available runtimes at pimalaya/io-stream.
The loop is the glue between coroutines and runtimes. It makes the coroutine progress while allowing runtime to process I/O.
use std::{net::TcpStream, sync::Arc};
use io_starttls::imap::UpgradeTls;
use io_stream::runtimes::std::handle;
use rustls::{ClientConfig, ClientConnection, StreamOwned};
use rustls_platform_verifier::ConfigVerifierExt;
// first connect to IMAP stream using plain TCP
let mut tcp = TcpStream::connect(("posteo.de", 143)).unwrap();
// create a new STARTTLS coroutine
let mut arg = None;
let mut starttls = UpgradeTls::new().with_discard_greeting(true);
while let Err(io) = starttls.resume(arg.take()) {
// handle I/O requests synchronously
arg = Some(handle(&mut tcp, io).unwrap());
}
// now the TCP stream is ready to be upgraded to TLS using rustls
let config = ClientConfig::with_platform_verifier();
let server_name = "posteo.de".to_string().try_into().unwrap();
let conn = ClientConnection::new(Arc::new(config), server_name).unwrap();
let mut tls = StreamOwned::new(conn, tcp);
See complete example at ./examples/std-rustls-imap.rs.
use io_starttls::imap::UpgradeTls;
use io_stream::runtimes::tokio::handle;
use tokio::net::TcpStream;
use tokio_native_tls::{native_tls, TlsConnector};
// first connect to IMAP stream using plain TCP
let mut tcp = TcpStream::connect(("posteo.de", 143)).await.unwrap();
// create a new STARTTLS coroutine
let mut arg = None;
let mut starttls = UpgradeTls::new().with_discard_greeting(true);
while let Err(io) = starttls.resume(arg.take()) {
// handle I/O requests synchronously
arg = Some(handle(&mut tcp, io).await.unwrap());
}
// now the TCP stream is ready to be upgraded to TLS using native-tls
let connector = native_tls::TlsConnector::new().unwrap();
let mut tls = TlsConnector::from(connector)
.connect(&host.to_string(), tcp)
.await
.unwrap();
See complete example at ./examples/tokio-native-tls-imap.rs.
Special thanks to the NLnet foundation and the European Commission that helped the project to receive financial support from various programs:
- NGI Assure in 2022
- NGI Zero Entrust in 2023
- NGI Zero Core in 2024 (still ongoing)
If you appreciate the project, feel free to donate using one of the following providers: