Skip to content

Why is simpleserver example not using rustls::Stream? #2520

@Ten0

Description

@Ten0

I just spent about an hour trying to understand the simpleserver example to make a simple TLS stream over TCP:

let mut conn = rustls::ServerConnection::new(Arc::new(config))?;
conn.complete_io(&mut stream)?;
conn.writer()
.write_all(b"Hello from the server")?;
conn.complete_io(&mut stream)?;
let mut buf = [0; 64];
let len = conn.reader().read(&mut buf)?;
println!("Received message from client: {:?}", &buf[..len]);

because I was thrown off by the fact that we don't pass the TcpStream when creating the ServerConnection, and that seemed to imply that this example (using conn.reader() as my final reader) would not work if the message was too large, because it was unclear to me how it would be able to still refer to the TcpStream when doing many calls to read on that...

Only to finally figure out that one can actually use rustls::Stream, like on the client side, to get a working stream with none of the crazy read_tls()/write_tls()/complete_io() concerns.

My question is, why is that example not using that already?
The current writing seems error-prone: people might not immediately notice that they need to interlace calls to read on the connection.reader() and calls to complete_io, or actually just use Stream instead.
I could just as well have not noticed that we don't pass the TcpStream when creating the ServerConnection...

New proposed writing:

	let listener = TcpListener::bind(format!("[::]:{}", 4443)).unwrap();
	let (mut tcp_stream, _) = listener.accept()?;
	let mut conn = rustls::ServerConnection::new(Arc::new(config))?;
	let mut tls_stream = rustls::Stream::new(&mut conn, &mut tcp_stream);

	tls_stream.write_all(b"Hello from the server")?;
	let mut buf = [0; 64];
	let len = tls_stream.read(&mut buf)?;
	println!("Received message from client: {:?}", &buf[..len]);

@cpu since you authored the relevant file

(I can open a PR if you like)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions