Skip to main content

protocol/
handshake.rs

1//! The client side of the handshake (packages/client connection.ts `#handleMessage` while connecting): the client
2//! sends `hello`; the server's first message must be its `hello` for the expected server ID, or a `hello_error`.
3
4use crate::framing::{DEFAULT_MAX_FRAME_LENGTH, MAX_SERVER_FRAME_LENGTH};
5use crate::message::{
6    ClientMessage, PROTOCOL_VERSION, ProtocolError, ServerMessage, ServerMessageDecoder, encode_client_message,
7};
8use std::fmt;
9use std::io::{self, ErrorKind, Read, Write};
10
11#[derive(Debug)]
12pub enum HelloError {
13    /// The server's `hello_error`.
14    Rejected(ProtocolError),
15    /// The peer broke the protocol (`ProtocolValidationError`).
16    Invalid(String),
17    /// The transport ended before the server's hello.
18    Closed,
19    Io(io::Error),
20}
21
22impl fmt::Display for HelloError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            HelloError::Rejected(error) => f.write_str(&error.message),
26            HelloError::Invalid(message) => f.write_str(message),
27            HelloError::Closed => f.write_str("Byte transport closed"),
28            HelloError::Io(error) => error.fmt(f),
29        }
30    }
31}
32
33/// The server's messages after its hello: a connection decodes the rest of the stream with `decoder`.
34pub struct Connected {
35    pub decoder: ServerMessageDecoder,
36    pub queued: Vec<ServerMessage>,
37}
38
39pub fn client_hello() -> Vec<u8> {
40    encode_client_message(
41        &ClientMessage::Hello {
42            version: PROTOCOL_VERSION,
43        },
44        DEFAULT_MAX_FRAME_LENGTH,
45    )
46    .expect("a hello frame encodes")
47}
48
49/// Wait on `read` for the server's answer to a client hello already sent: its hello for `server_id`.
50pub fn read_hello(read: &mut dyn Read, server_id: &str) -> Result<Connected, HelloError> {
51    let mut decoder = ServerMessageDecoder::new(MAX_SERVER_FRAME_LENGTH).unwrap_or_default();
52    let mut buffer = vec![0u8; 64 * 1024];
53    let mut queued = Vec::new();
54    while queued.is_empty() {
55        let n = match read.read(&mut buffer) {
56            Ok(n) => n,
57            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
58            Err(error) => return Err(HelloError::Io(error)),
59        };
60        if n == 0 {
61            return Err(match decoder.end() {
62                Err(error) => HelloError::Invalid(error.0),
63                Ok(()) => HelloError::Closed,
64            });
65        }
66        queued = decoder.push(&buffer[..n]).map_err(|e| HelloError::Invalid(e.0))?;
67    }
68    match queued.remove(0) {
69        ServerMessage::HelloError { error } => Err(HelloError::Rejected(error)),
70        ServerMessage::Hello { server_id: id, .. } if id == server_id => Ok(Connected { decoder, queued }),
71        ServerMessage::Hello { server_id: id, .. } => Err(HelloError::Invalid(format!(
72            "Connected server {id:?} does not match {server_id:?}"
73        ))),
74        _ => Err(HelloError::Invalid("Expected server hello as first message".into())),
75    }
76}
77
78pub fn hello<S: Read + Write>(stream: &mut S, server_id: &str) -> Result<Connected, HelloError> {
79    stream.write_all(&client_hello()).map_err(HelloError::Io)?;
80    read_hello(stream, server_id)
81}