Skip to main content

schedr_tls/
connect.rs

1//! A worker's gRPC channel to the master: plain for an `http://` URL, TLS with the worker's
2//! certificate for an `https://` one (the master's certificate must name the URL's host).
3//!
4//! The handshake is done here rather than by tonic, so each connection uses the material in
5//! use at that moment (see [`crate::reload`]), within the same time limit as the servers'.
6//! Internal links never go through an HTTP proxy.
7
8use hyper_util::rt::TokioIo;
9use rustls::pki_types::ServerName;
10use tokio::net::TcpStream;
11use tokio_rustls::TlsConnector;
12use tonic::transport::{Channel, Endpoint, Uri};
13
14use crate::reload::Tls;
15
16#[cfg(test)]
17mod tests;
18
19/// The port of an `https://` URL without one.
20const HTTPS_PORT: u16 = 443;
21
22/// Connects to the master at `url`, over TLS when `tls` is given.
23///
24/// # Errors
25///
26/// Why the URL can't be used or the connection failed, as text.
27pub async fn channel(url: &str, tls: Option<&Tls>) -> Result<Channel, String> {
28    let endpoint = Endpoint::from_shared(url.to_owned()).map_err(|e| e.to_string())?;
29    let Some(tls) = tls else {
30        return endpoint.connect().await.map_err(|e| error_text(&e));
31    };
32    let tls = tls.clone();
33    let connector = tower::service_fn(move |uri: Uri| {
34        let tls = tls.clone();
35        async move {
36            // An IPv6 address comes in brackets.
37            let host = uri.host().unwrap_or_default();
38            let host = host
39                .trim_start_matches('[')
40                .trim_end_matches(']')
41                .to_owned();
42            let port = uri.port_u16().unwrap_or(HTTPS_PORT);
43            let name = ServerName::try_from(host.clone())
44                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
45            let tcp = TcpStream::connect((host, port)).await?;
46            let _ = tcp.set_nodelay(true);
47            let handshake = TlsConnector::from(tls.grpc_client()).connect(name, tcp);
48            let stream = tokio::time::timeout(tls.handshake_timeout(), handshake)
49                .await
50                .map_err(|_| {
51                    std::io::Error::new(
52                        std::io::ErrorKind::TimedOut,
53                        "the master didn't complete the TLS handshake",
54                    )
55                })??;
56            Ok::<_, std::io::Error>(TokioIo::new(stream))
57        }
58    });
59    endpoint
60        .connect_with_connector(connector)
61        .await
62        .map_err(|e| error_text(&e))
63}
64
65/// The error with its causes, which carry the reason (a refused certificate, say).
66#[must_use]
67pub fn error_text(error: &dyn std::error::Error) -> String {
68    let mut text = error.to_string();
69    let mut source = error.source();
70    while let Some(cause) = source {
71        text.push_str(": ");
72        text.push_str(&cause.to_string());
73        source = cause.source();
74    }
75    text
76}