A TcpStream with pluggable TLS support.
Wraps std::net::TcpStream in a TcpStream enum that can be upgraded
to a TLS-encrypted stream via TcpStream::into_tls. Supported backends
are rustls (default), native-tls, and OpenSSL, selected through feature
flags. Async variants of the encrypted stream are provided via the
futures-io traits when the futures feature is enabled.
§Feature flags
§Async runtime (pick exactly one)
| Flag | Notes |
tokio (default) | Requires a running Tokio runtime |
smol | Uses the smol executor |
async-global-executor | Uses async-global-executor |
§TLS backend (pick at most one; rustls is the default)
| Flag | Notes |
rustls (default) | TLS via rustls |
native-tls | TLS via the platform’s native library |
openssl | TLS via OpenSSL |
§Rustls certificate store (only when rustls is active)
| Flag | Notes |
rustls-platform-verifier (default) | Uses the platform trust store |
rustls-native-certs | Loads native root certificates |
rustls-webpki-roots-certs | Uses the webpki bundled root set |
§Rustls crypto provider (at least one must be enabled)
| Flag | Notes |
rustls--aws_lc_rs (default) | Uses aws-lc-rs |
rustls--ring | Uses ring (more portable) |
§Miscellaneous
| Flag | Notes |
futures | Enable futures-io async trait impls on the encrypted stream |
vendored-openssl | Build a vendored OpenSSL (requires openssl feature) |
§Example
To connect to a remote server:
use tcp_stream::{HandshakeError, TcpStream, TLSConfig};
use std::io::{self, Read, Write};
let mut stream = TcpStream::connect("www.rust-lang.org:443").unwrap();
stream.set_nonblocking(true).unwrap();
loop {
if stream.try_connect().unwrap() {
break;
}
}
let mut stream = stream.into_tls("www.rust-lang.org", TLSConfig::default());
while let Err(HandshakeError::WouldBlock(mid_handshake)) = stream {
stream = mid_handshake.handshake();
}
let mut stream = stream.unwrap();
while let Err(err) = stream.write_all(b"GET / HTTP/1.0\r\n\r\n") {
if err.kind() != io::ErrorKind::WouldBlock {
panic!("error: {:?}", err);
}
}
while let Err(err) = stream.flush() {
if err.kind() != io::ErrorKind::WouldBlock {
panic!("error: {:?}", err);
}
}
let mut res = vec![];
while let Err(err) = stream.read_to_end(&mut res) {
if err.kind() != io::ErrorKind::WouldBlock {
panic!("stream error: {:?}", err);
}
}
println!("{}", String::from_utf8_lossy(&res));