[Fixed] TlsStream::write then write_tls

- [Added] add example
This commit is contained in:
quininer kel 2017-02-22 11:42:32 +08:00
parent 6e7d67cccb
commit 0941db6792
4 changed files with 162 additions and 1 deletions

View File

@ -11,3 +11,4 @@ rustls = "*"
[dev-dependencies]
clap = "*"
webpki-roots = "*"
tokio-file-unix = "*"

71
examples/client.rs Normal file
View File

@ -0,0 +1,71 @@
extern crate clap;
extern crate futures;
extern crate tokio_core;
extern crate webpki_roots;
extern crate tokio_file_unix;
extern crate tokio_rustls;
use std::sync::Arc;
use std::net::ToSocketAddrs;
use std::io::{ BufReader, stdout };
use std::fs;
use futures::Future;
use tokio_core::io;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use clap::{ App, Arg };
use tokio_file_unix::{ StdFile, File };
use tokio_rustls::{ ClientConfig, TlsConnectorExt };
fn app() -> App<'static, 'static> {
App::new("client")
.about("tokio-rustls client example")
.arg(Arg::with_name("host").value_name("HOST").required(true))
.arg(Arg::with_name("port").short("p").long("port").value_name("PORT").help("port, default `443`"))
.arg(Arg::with_name("domain").short("d").long("domain").value_name("DOMAIN").help("domain"))
.arg(Arg::with_name("cafile").short("c").long("cafile").value_name("FILE").help("CA certificate chain"))
}
fn main() {
let matches = app().get_matches();
let host = matches.value_of("host").unwrap();
let port = if let Some(port) = matches.value_of("port") {
port.parse().unwrap()
} else {
443
};
let domain = matches.value_of("domain").unwrap_or(host);
let cafile = matches.value_of("cafile");
let text = format!("GET / HTTP/1.0\r\nHost: {}\r\n\r\n", domain);
let mut core = Core::new().unwrap();
let handle = core.handle();
let addr = (host, port)
.to_socket_addrs().unwrap()
.next().unwrap();
let stdout = stdout();
let mut stdout = File::new_nb(StdFile(stdout.lock())).unwrap();
stdout.set_nonblocking(true).unwrap();
let stdout = stdout.into_io(&handle).unwrap();
let mut config = ClientConfig::new();
if let Some(cafile) = cafile {
let mut pem = BufReader::new(fs::File::open(cafile).unwrap());
config.root_store.add_pem_file(&mut pem).unwrap();
} else {
config.root_store.add_trust_anchors(&webpki_roots::ROOTS);
}
let arc_config = Arc::new(config);
let socket = TcpStream::connect(&addr, &handle);
let resp = socket
.and_then(|stream| arc_config.connect_async(domain, stream))
.and_then(|stream| io::write_all(stream, text.as_bytes()))
.and_then(|(stream, _)| io::copy(stream, stdout));
core.run(resp).unwrap();
}

88
examples/server.rs Normal file
View File

@ -0,0 +1,88 @@
extern crate clap;
extern crate rustls;
extern crate futures;
extern crate tokio_core;
extern crate webpki_roots;
extern crate tokio_rustls;
use std::sync::Arc;
use std::net::ToSocketAddrs;
use std::io::BufReader;
use std::fs::File;
use futures::{ Future, Stream };
use rustls::{ Certificate, PrivateKey };
use rustls::internal::pemfile::{ certs, rsa_private_keys };
use tokio_core::io::{ self, Io };
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
use clap::{ App, Arg };
use tokio_rustls::{ ServerConfig, TlsAcceptorExt };
fn app() -> App<'static, 'static> {
App::new("server")
.about("tokio-rustls server example")
.arg(Arg::with_name("addr").value_name("ADDR").required(true))
.arg(Arg::with_name("cert").short("c").long("cert").value_name("FILE").help("cert file.").required(true))
.arg(Arg::with_name("key").short("k").long("key").value_name("FILE").help("key file, rsa only.").required(true))
.arg(Arg::with_name("echo").short("e").long("echo-mode").help("echo mode."))
}
fn load_certs(path: &str) -> Vec<Certificate> {
certs(&mut BufReader::new(File::open(path).unwrap())).unwrap()
}
fn load_keys(path: &str) -> Vec<PrivateKey> {
rsa_private_keys(&mut BufReader::new(File::open(path).unwrap())).unwrap()
}
fn main() {
let matches = app().get_matches();
let addr = matches.value_of("addr").unwrap()
.to_socket_addrs().unwrap()
.next().unwrap();
let cert_file = matches.value_of("cert").unwrap();
let key_file = matches.value_of("key").unwrap();
let flag_echo = matches.occurrences_of("echo") > 0;
let mut core = Core::new().unwrap();
let handle = core.handle();
let mut config = ServerConfig::new();
config.set_single_cert(load_certs(cert_file), load_keys(key_file).remove(0));
let arc_config = Arc::new(config);
let socket = TcpListener::bind(&addr, &handle).unwrap();
let done = socket.incoming()
.for_each(|(stream, addr)| if flag_echo {
let done = arc_config.accept_async(stream)
.and_then(|stream| {
let (reader, writer) = stream.split();
io::copy(reader, writer)
})
.map(move |n| println!("Echo: {} - {}", n, addr))
.map_err(move |err| println!("Error: {:?} - {}", err, addr));
handle.spawn(done);
Ok(())
} else {
let done = arc_config.accept_async(stream)
.and_then(|stream| io::write_all(
stream,
"HTTP/1.0 200 ok\r\n\
Connection: close\r\n\
Content-length: 12\r\n\
\r\n\
Hello world!".as_bytes()
))
.map(move |_| println!("Accept: {}", addr))
.map_err(move |err| println!("Error: {:?} - {}", err, addr));
handle.spawn(done);
Ok(())
});
core.run(done).unwrap();
}

View File

@ -174,10 +174,11 @@ impl<S, C> io::Write for TlsStream<S, C>
where S: Io, C: Session
{
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let output = self.session.write(buf);
while self.session.wants_write() && self.io.poll_write().is_ready() {
self.session.write_tls(&mut self.io)?;
}
self.session.write(buf)
output
}
fn flush(&mut self) -> io::Result<()> {