iroh_relay/client/
tls.rs

1//! Functionality related to lower-level tls-based connection establishment.
2//!
3//! Primarily to support [`ClientBuilder::connect`].
4//!
5//! This doesn't work in the browser - thus separated into its own file.
6
7// Based on tailscale/derp/derphttp/derphttp_client.go
8
9use std::{collections::VecDeque, net::IpAddr};
10
11use bytes::Bytes;
12use data_encoding::BASE64;
13use http_body_util::Empty;
14use hyper::{Request, upgrade::Parts};
15use hyper_util::rt::TokioIo;
16use n0_error::e;
17use n0_future::{
18    FuturesUnordered, MaybeFuture, StreamExt, task,
19    time::{self},
20};
21use percent_encoding::percent_decode_str;
22use rustls::client::Resumption;
23use tokio::net::TcpStream;
24use tracing::{Instrument, error, info_span};
25
26use super::{
27    streams::{MaybeTlsStream, ProxyStream},
28    *,
29};
30use crate::defaults::timeouts::*;
31
32#[derive(Debug, Clone)]
33pub(super) struct MaybeTlsStreamBuilder {
34    url: Url,
35    dns_resolver: DnsResolver,
36    proxy_url: Option<Url>,
37    prefer_ipv6: bool,
38    tls_config: rustls::ClientConfig,
39}
40
41impl MaybeTlsStreamBuilder {
42    pub(super) fn new(
43        url: Url,
44        dns_resolver: DnsResolver,
45        tls_config: rustls::ClientConfig,
46    ) -> Self {
47        Self {
48            url,
49            dns_resolver,
50            proxy_url: None,
51            prefer_ipv6: false,
52            tls_config,
53        }
54    }
55
56    pub(super) fn proxy_url(mut self, proxy_url: Option<Url>) -> Self {
57        self.proxy_url = proxy_url;
58        self
59    }
60
61    pub(super) fn prefer_ipv6(mut self, prefer: bool) -> Self {
62        self.prefer_ipv6 = prefer;
63        self
64    }
65
66    pub(super) async fn connect(self) -> Result<MaybeTlsStream<ProxyStream>, ConnectError> {
67        let mut config = self.tls_config.clone();
68        config.resumption = Resumption::default();
69        let tls_connector: tokio_rustls::TlsConnector = Arc::new(config).into();
70
71        let tcp_stream = self.dial_url(&tls_connector).await?;
72
73        let local_addr = tcp_stream
74            .local_addr()
75            .map_err(|_| e!(ConnectError::NoLocalAddr))?;
76
77        debug!(server_addr = ?tcp_stream.peer_addr(), %local_addr, "TCP stream connected");
78
79        if self.use_tls() {
80            trace!("Starting TLS handshake");
81            let hostname = self
82                .tls_servername()
83                .ok_or_else(|| e!(ConnectError::InvalidTlsServername))?;
84
85            let hostname = hostname.to_owned();
86            let tls_stream = tls_connector
87                .connect(hostname, tcp_stream)
88                .await
89                .map_err(|err| e!(ConnectError::Tls, err))?;
90            trace!("tls_connector connect success");
91            Ok(MaybeTlsStream::Tls(tls_stream))
92        } else {
93            trace!("Starting handshake");
94            Ok(MaybeTlsStream::Raw(tcp_stream))
95        }
96    }
97
98    fn use_tls(&self) -> bool {
99        // only disable tls if we are explicitly dialing a http url
100        #[allow(clippy::match_like_matches_macro)]
101        match self.url.scheme() {
102            "http" => false,
103            "ws" => false,
104            _ => true,
105        }
106    }
107
108    fn tls_servername(&self) -> Option<rustls::pki_types::ServerName<'_>> {
109        let host_str = self.url.host_str()?;
110        let servername = rustls::pki_types::ServerName::try_from(host_str).ok()?;
111        Some(servername)
112    }
113
114    async fn dial_url(
115        &self,
116        tls_connector: &tokio_rustls::TlsConnector,
117    ) -> Result<ProxyStream, DialError> {
118        if let Some(ref proxy) = self.proxy_url {
119            let stream = self.dial_url_proxy(proxy.clone(), tls_connector).await?;
120            Ok(ProxyStream::Proxied(stream))
121        } else {
122            let stream =
123                dial_happy_eyeballs(&self.dns_resolver, &self.url, self.prefer_ipv6).await?;
124            Ok(ProxyStream::Raw(stream))
125        }
126    }
127
128    async fn dial_url_proxy(
129        &self,
130        proxy_url: Url,
131        tls_connector: &tokio_rustls::TlsConnector,
132    ) -> Result<util::Chain<std::io::Cursor<Bytes>, MaybeTlsStream<tokio::net::TcpStream>>, DialError>
133    {
134        debug!(%self.url, %proxy_url, "dial url via proxy");
135
136        let tcp_stream = dial_happy_eyeballs(&self.dns_resolver, &proxy_url, self.prefer_ipv6)
137            .await
138            .map_err(|err| match err {
139                DialError::InvalidTargetPort { meta } => DialError::ProxyInvalidTargetPort { meta },
140                err => err,
141            })?;
142
143        // Setup TLS if necessary
144        let io = if proxy_url.scheme() == "http" {
145            MaybeTlsStream::Raw(tcp_stream)
146        } else {
147            let hostname = proxy_url.host_str().ok_or_else(|| {
148                e!(DialError::ProxyInvalidUrl {
149                    proxy_url: proxy_url.clone()
150                })
151            })?;
152            let hostname =
153                rustls::pki_types::ServerName::try_from(hostname.to_string()).map_err(|_| {
154                    e!(DialError::ProxyInvalidTlsServername {
155                        proxy_hostname: hostname.to_string()
156                    })
157                })?;
158            let tls_stream = tls_connector.connect(hostname, tcp_stream).await?;
159            MaybeTlsStream::Tls(tls_stream)
160        };
161        let io = TokioIo::new(io);
162
163        let target_host = self.url.host_str().ok_or_else(|| {
164            e!(DialError::InvalidUrl {
165                url: self.url.clone()
166            })
167        })?;
168
169        let port = url_port(&self.url).ok_or_else(|| e!(DialError::InvalidTargetPort))?;
170
171        // Establish Proxy Tunnel
172        let mut req_builder = Request::builder()
173            .uri(format!("{target_host}:{port}"))
174            .method("CONNECT")
175            .header("Host", target_host)
176            .header("Proxy-Connection", "Keep-Alive");
177        if !proxy_url.username().is_empty() {
178            // Passthrough authorization
179            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization
180            debug!(
181                "setting proxy-authorization: username={}",
182                proxy_url.username()
183            );
184            // `Url` keeps the username and password percent-encoded.
185            let mut to_encode: Vec<u8> = percent_decode_str(proxy_url.username()).collect();
186            to_encode.push(b':');
187            to_encode.extend(percent_decode_str(proxy_url.password().unwrap_or_default()));
188            let encoded = BASE64.encode(&to_encode);
189            req_builder = req_builder.header("Proxy-Authorization", format!("Basic {encoded}"));
190        }
191        let req = req_builder
192            .body(Empty::<Bytes>::new())
193            .expect("fixed config");
194
195        debug!("Sending proxy request: {:?}", req);
196
197        let (mut sender, conn) = hyper::client::conn::http1::handshake(io)
198            .await
199            .map_err(|err| e!(DialError::ProxyConnect, err))?;
200        task::spawn(async move {
201            if let Err(err) = conn.with_upgrades().await {
202                error!("Proxy connection failed: {:?}", err);
203            }
204        });
205
206        let res = sender
207            .send_request(req)
208            .await
209            .map_err(|err| e!(DialError::ProxyConnect, err))?;
210        if !res.status().is_success() {
211            return Err(e!(DialError::ProxyConnectInvalidStatus {
212                status: res.status()
213            }));
214        }
215
216        let upgraded = hyper::upgrade::on(res)
217            .await
218            .map_err(|err| e!(DialError::ProxyConnect, err))?;
219        let Parts { io, read_buf, .. } = upgraded
220            .downcast::<TokioIo<MaybeTlsStream<tokio::net::TcpStream>>>()
221            .expect("only this upgrade used");
222
223        let res = util::chain(std::io::Cursor::new(read_buf), io.into_inner());
224
225        Ok(res)
226    }
227}
228
229/// Resolves `url` and races TCP connections across the resulting addresses,
230/// Happy Eyeballs style (RFC 8305).
231///
232/// IPv4 and IPv6 addresses stream in as their lookups resolve and are appended
233/// to a single queue. The loop dials them one at a time, [`pop_family`] taking
234/// the next address interleaved by family, the preferred one (`prefer_ipv6`)
235/// first:
236///
237/// - the first attempt waits a [`RESOLUTION_DELAY`] head start for the preferred
238///   family while only the other family has resolved, and starts immediately
239///   once the preferred family resolves;
240/// - each later attempt starts [`CONNECTION_ATTEMPT_DELAY`] after the previous
241///   one, or as soon as the last in-flight attempt fails, whichever comes first;
242/// - every attempt is itself capped at [`DIAL_ENDPOINT_TIMEOUT`].
243///
244/// The first connection to succeed is returned; the rest are dropped, which
245/// cancels them.
246async fn dial_happy_eyeballs(
247    dns_resolver: &DnsResolver,
248    url: &Url,
249    prefer_ipv6: bool,
250) -> Result<TcpStream, DialError> {
251    let port = url_port(url).ok_or_else(|| e!(DialError::InvalidTargetPort))?;
252
253    // Stream of resolved addresses.
254    let resolve_stream = dns_resolver.resolve_host_all(url, DNS_TIMEOUT);
255    tokio::pin!(resolve_stream);
256    // Set to `true` once `resolve_stream` yielded `None`, to not poll it again after completion.
257    let mut resolve_stream_finished = false;
258    // Addresses resolved but not yet tried, in arrival order.
259    let mut queue: VecDeque<IpAddr> = VecDeque::new();
260    // Family to dial next, toggled to interleave.
261    let mut next_prefer_v6 = prefer_ipv6;
262    // In-progress connection attempts.
263    let mut dials = FuturesUnordered::new();
264    // Whether the first connection attempt has been started yet.
265    let mut started = false;
266    // Last error that occurred, returned if no connection attempt succeeded.
267    let mut last_err: Option<DialError> = None;
268    // Timer after which to start the next connection attempt, or `None` for immediately.
269    let next_dial_delayed_until = MaybeFuture::None;
270    tokio::pin!(next_dial_delayed_until);
271
272    loop {
273        if resolve_stream_finished && queue.is_empty() && dials.is_empty() {
274            // Nothing left to resolve, attempt, or wait on.
275            return Err(last_err.unwrap_or_else(|| e!(DnsError::NoResponse).into()));
276        }
277
278        // The next dial is due and an address is waiting: dial the next address,
279        // interleaved by family, and set the timer for the next attempt.
280        if next_dial_delayed_until.is_none()
281            && let Some(ip) = pop_family(&mut queue, &mut next_prefer_v6)
282        {
283            let addr = SocketAddr::new(ip, port);
284            dials.push(
285                async move {
286                    trace!("connecting TCP stream");
287                    let stream = time::timeout(DIAL_ENDPOINT_TIMEOUT, TcpStream::connect(addr))
288                        .await
289                        .map_err(DialError::from)
290                        .and_then(|res| res.map_err(DialError::from))
291                        .inspect_err(|err| debug!("failed to connect: {err:#}"))?;
292                    trace!("TCP stream connected");
293                    stream.set_nodelay(true)?;
294                    Ok(stream)
295                }
296                .instrument(info_span!("connect", %addr)),
297            );
298            started = true;
299            next_dial_delayed_until
300                .as_mut()
301                .set_future(time::sleep(CONNECTION_ATTEMPT_DELAY));
302        }
303
304        // All three arms are guarded, but it is guaranteed that at least one arm
305        // is enabled, otherwise the check at the top of the loop returns.
306        tokio::select! {
307            biased;
308            // Yields when a dial attempt completed.
309            Some(res) = dials.next(), if !dials.is_empty() => match res {
310                Ok(stream) => return Ok(stream),
311                Err(err) => {
312                    last_err = Some(err);
313                    if dials.is_empty() {
314                        // Fail fast: start the next attempt now rather than waiting it out.
315                        next_dial_delayed_until.as_mut().set_none();
316                    }
317                }
318            },
319            // Yields when the next address is resolved.
320            addr = resolve_stream.next(), if !resolve_stream_finished => {
321                match addr {
322                    Some(Ok(ip)) => {
323                        queue.push_back(ip);
324                        if !started {
325                            // If no connection attempt has been started, and a non-preferred
326                            // address is resolved, delay the connect by `RESOLUTION_DELAY`.
327                            // If a preferred address arrives later but before this delay expires,
328                            // it will be dialed instead.
329                            if prefer_ipv6 == ip.is_ipv6() {
330                                next_dial_delayed_until.as_mut().set_none();
331                            } else if next_dial_delayed_until.is_none() {
332                                next_dial_delayed_until.as_mut().set_future(time::sleep(RESOLUTION_DELAY));
333                            }
334                        }
335                    }
336                    Some(Err(err)) => {
337                        last_err = Some(err.into());
338                    }
339                    None => {
340                        resolve_stream_finished = true;
341                        if !started {
342                            next_dial_delayed_until.as_mut().set_none();
343                        }
344                    }
345                }
346            }
347            // Yields when the next dial attempt is due, if the timer is set.
348            () = &mut next_dial_delayed_until, if next_dial_delayed_until.is_some() => {},
349        }
350    }
351}
352
353/// Removes the next address to attempt, preferring `*next_is_v6`'s family and
354/// flipping it so families interleave; falls back to whatever is available.
355fn pop_family(addrs: &mut VecDeque<IpAddr>, next_is_v6: &mut bool) -> Option<IpAddr> {
356    let idx = addrs
357        .iter()
358        .position(|ip| ip.is_ipv6() == *next_is_v6)
359        .unwrap_or(0);
360    let addr = addrs.remove(idx)?;
361    *next_is_v6 = !*next_is_v6;
362    Some(addr)
363}
364
365fn url_port(url: &Url) -> Option<u16> {
366    if let Some(port) = url.port() {
367        return Some(port);
368    }
369
370    match url.scheme() {
371        "http" | "ws" => Some(80),
372        "https" | "wss" => Some(443),
373        _ => None,
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use std::net::{Ipv4Addr, Ipv6Addr};
380
381    use tokio::net::TcpListener;
382
383    use super::*;
384    use crate::test_utils::static_resolver;
385
386    fn relay_url(port: u16) -> Url {
387        format!("http://relay.test:{port}")
388            .parse()
389            .expect("valid url")
390    }
391
392    /// An unreachable IPv4 address (RFC 5737 TEST-NET-1).
393    fn dead_v4(n: u8) -> Ipv4Addr {
394        Ipv4Addr::new(192, 0, 2, n)
395    }
396
397    /// An unreachable IPv6 address (RFC 3849 documentation prefix).
398    fn dead_v6(n: u16) -> Ipv6Addr {
399        Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, n)
400    }
401
402    /// Tests that all addresses are tried until one succeeds.
403    #[tokio::test]
404    async fn tries_addresses_until_one_connects() {
405        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
406        let port = listener.local_addr().unwrap().port();
407
408        let addrs = (1..5).map(dead_v4).chain([Ipv4Addr::LOCALHOST]).collect();
409        let resolver = static_resolver(addrs, vec![]);
410        let stream = dial_happy_eyeballs(&resolver, &relay_url(port), false)
411            .await
412            .expect("should skip the invalid addrs and still connect");
413        assert_eq!(stream.peer_addr().unwrap().ip(), Ipv4Addr::LOCALHOST);
414    }
415
416    /// Tests if the preferred family is unreachable the non-preferred family is used.
417    #[tokio::test]
418    async fn falls_back_from_unreachable_preferred_family() {
419        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
420        let port = listener.local_addr().unwrap().port();
421        let resolver = static_resolver(vec![Ipv4Addr::LOCALHOST], vec![dead_v6(1), dead_v6(2)]);
422
423        let stream = dial_happy_eyeballs(&resolver, &relay_url(port), true)
424            .await
425            .expect("falls back to IPv4");
426        assert!(stream.peer_addr().unwrap().is_ipv4());
427    }
428
429    #[tokio::test]
430    async fn errors_when_all_addresses_unreachable() {
431        let resolver = static_resolver(vec![dead_v4(1), dead_v4(2)], vec![dead_v6(1)]);
432        let err = dial_happy_eyeballs(&resolver, &relay_url(80), true)
433            .await
434            .expect_err("nothing reachable");
435        dbg!(&err);
436        assert!(matches!(
437            err,
438            DialError::Io { .. } | DialError::Timeout { .. }
439        ));
440    }
441
442    #[tokio::test]
443    async fn errors_when_nothing_resolves() {
444        let resolver = static_resolver(vec![], vec![]);
445        let err = dial_happy_eyeballs(&resolver, &relay_url(80), false)
446            .await
447            .expect_err("no addresses to dial");
448        assert!(matches!(err, DialError::Dns { .. }));
449    }
450
451    /// Dials through a fake proxy with the given userinfo and returns the
452    /// `Proxy-Authorization` header the proxy received.
453    ///
454    /// The proxy reads the `CONNECT` request and hangs up, so the dial fails.
455    #[cfg(with_crypto_provider)]
456    async fn proxy_authorization_for(userinfo: &str) -> String {
457        use std::time::Duration;
458
459        use tokio::io::AsyncReadExt;
460
461        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
462        let port = listener.local_addr().unwrap().port();
463        let proxy = task::spawn(async move {
464            let (mut stream, _) = listener.accept().await.unwrap();
465            let mut head = Vec::new();
466            while !head.ends_with(b"\r\n\r\n") {
467                head.push(stream.read_u8().await.unwrap());
468            }
469            String::from_utf8(head).unwrap()
470        });
471
472        let proxy_url = format!("http://{userinfo}@proxy.test:{port}")
473            .parse()
474            .expect("valid url");
475        let resolver = static_resolver(vec![Ipv4Addr::LOCALHOST], vec![]);
476        let res = MaybeTlsStreamBuilder::new(
477            relay_url(443),
478            resolver,
479            crate::tls::make_dangerous_client_config(),
480        )
481        .proxy_url(Some(proxy_url))
482        .connect()
483        .await;
484        assert!(res.is_err(), "the proxy never opens the tunnel");
485
486        let head = time::timeout(Duration::from_secs(5), proxy)
487            .await
488            .expect("the proxy received no request")
489            .unwrap();
490        head.lines()
491            .find_map(|line| {
492                let (name, value) = line.split_once(':')?;
493                name.eq_ignore_ascii_case("proxy-authorization")
494                    .then(|| value.trim().to_string())
495            })
496            .expect("no Proxy-Authorization header")
497    }
498
499    /// Tests that the proxy credentials use the standard base64 alphabet (RFC 7617).
500    #[cfg(with_crypto_provider)]
501    #[tokio::test]
502    async fn proxy_authorization_uses_standard_base64() {
503        // The URL-safe alphabet gives "dXNlcjpzM2NyZXR-fg==".
504        assert_eq!(
505            proxy_authorization_for("user:s3cret~~").await,
506            "Basic dXNlcjpzM2NyZXR+fg=="
507        );
508    }
509
510    /// Tests that the proxy credentials are percent-decoded before they are encoded.
511    #[cfg(with_crypto_provider)]
512    #[tokio::test]
513    async fn proxy_authorization_decodes_credentials() {
514        // `Url` keeps these passwords as "s3cret%3E%3E" and "p%40ss".
515        assert_eq!(
516            proxy_authorization_for("user:s3cret>>").await,
517            "Basic dXNlcjpzM2NyZXQ+Pg=="
518        );
519        assert_eq!(
520            proxy_authorization_for("user:p%40ss").await,
521            "Basic dXNlcjpwQHNz"
522        );
523    }
524}