iroh_relay/
client.rs

1//! Exposes [`Client`], which allows to establish connections to a relay server.
2//!
3//! Based on tailscale/derp/derphttp/derphttp_client.go
4
5use std::{
6    net::SocketAddr,
7    pin::Pin,
8    sync::Arc,
9    task::{self, Poll},
10};
11
12use conn::Conn;
13use iroh_base::{RelayUrl, SecretKey};
14#[cfg(not(wasm_browser))]
15use iroh_dns::dns::{DnsError, DnsResolver};
16#[cfg(wasm_browser)]
17use n0_error::StdResultExt;
18use n0_error::{AnyError, e, stack_error};
19use n0_future::{
20    Sink, Stream,
21    split::{SplitSink, SplitStream, split},
22    time,
23};
24use tracing::{debug, trace};
25use url::Url;
26
27pub use self::conn::{RecvError, SendError};
28use crate::{
29    KeyCache,
30    http::{ProtocolVersion, RELAY_RELATIVE_PATH},
31    protos::{
32        handshake,
33        relay::{ClientToRelayMsg, RelayToClientMsg},
34    },
35};
36
37pub(crate) mod conn;
38#[cfg(not(wasm_browser))]
39pub(crate) mod streams;
40#[cfg(not(wasm_browser))]
41mod tls;
42#[cfg(not(wasm_browser))]
43mod util;
44
45/// Connection errors.
46///
47/// `ConnectError` contains `DialError`, errors that can occur while dialing the
48/// relay, as well as errors that occur while creating or maintaining a connection.
49#[stack_error(derive, add_meta, from_sources)]
50#[allow(missing_docs)]
51#[non_exhaustive]
52pub enum ConnectError {
53    #[error("Invalid URL for websocket: {url}")]
54    InvalidWebsocketUrl { url: Url },
55    #[error("Invalid relay URL: {url}")]
56    InvalidRelayUrl { url: Url },
57    /// Error returned from the underlying WebSocket stream while establishing the connection.
58    ///
59    /// The concrete error type is `tokio_websockets::Error` on native targets and
60    /// `ws_stream_wasm::WsErr` on `wasm_browser` targets. Use [`AnyError::downcast_ref`] to
61    /// recover it. Note that the concrete downcast type is not covered by any semver
62    /// guarantees and may change between releases.
63    #[error(transparent)]
64    Websocket { source: AnyError },
65    #[error(
66        "Server replied with invalid iroh-relay version header: {}",
67        server_version.as_deref().unwrap_or("<empty>")
68    )]
69    BadVersionHeader { server_version: Option<String> },
70    #[error("Authorization token set to a string that is not a valid HTTP header value")]
71    InvalidAuthToken,
72    #[error(transparent)]
73    Handshake {
74        #[error(std_err)]
75        source: handshake::Error,
76    },
77    #[error(transparent)]
78    Dial { source: DialError },
79    #[error("Unexpected status during upgrade: {code}")]
80    UnexpectedUpgradeStatus { code: hyper::StatusCode },
81    #[error("Failed to upgrade response")]
82    Upgrade {
83        #[error(std_err)]
84        source: hyper::Error,
85    },
86    #[error("Invalid TLS servername")]
87    InvalidTlsServername {},
88    #[error("No local address available")]
89    NoLocalAddr {},
90    #[error("tls connection failed")]
91    Tls {
92        #[error(std_err)]
93        source: std::io::Error,
94    },
95    #[error(
96        "No rustls crypto provider configured while both ring and aws-lc-rs feature flags are disabled"
97    )]
98    MissingCryptoProvider,
99    #[cfg(wasm_browser)]
100    #[error("The relay protocol is not available in browsers")]
101    RelayProtoNotAvailable {},
102}
103
104/// Errors that can occur while dialing the relay server.
105#[stack_error(derive, add_meta, from_sources)]
106#[allow(missing_docs)]
107#[non_exhaustive]
108pub enum DialError {
109    #[error("Invalid target port")]
110    InvalidTargetPort {},
111    #[error(transparent)]
112    #[cfg(not(wasm_browser))]
113    Dns { source: DnsError },
114    #[error(transparent)]
115    Timeout {
116        #[error(std_err)]
117        source: time::Elapsed,
118    },
119    #[error(transparent)]
120    Io {
121        #[error(std_err)]
122        source: std::io::Error,
123    },
124    #[error("Invalid URL: {url}")]
125    InvalidUrl { url: Url },
126    #[error("Failed proxy connection: {status}")]
127    ProxyConnectInvalidStatus { status: hyper::StatusCode },
128    #[error("Invalid Proxy URL {proxy_url}")]
129    ProxyInvalidUrl { proxy_url: Url },
130    #[error("failed to establish proxy connection")]
131    ProxyConnect {
132        #[error(std_err)]
133        source: hyper::Error,
134    },
135    #[error("Invalid proxy TLS servername: {proxy_hostname}")]
136    ProxyInvalidTlsServername { proxy_hostname: String },
137    #[error("Invalid proxy target port")]
138    ProxyInvalidTargetPort {},
139}
140
141/// Build a Client.
142#[derive(derive_more::Debug, Clone)]
143pub struct ClientBuilder {
144    /// Default is None
145    #[debug("address family selector callback")]
146    address_family_selector: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
147    /// Server url.
148    url: RelayUrl,
149    /// TLS verification config.
150    tls_config: Option<rustls::ClientConfig>,
151    /// HTTP Proxy
152    proxy_url: Option<Url>,
153    /// The secret key of this client.
154    secret_key: SecretKey,
155    /// Optional authorization token.
156    ///
157    /// Sent as an `Authorization: Bearer` header on native targets and as
158    /// a `?token=` query parameter under Wasm. See [`ClientBuilder::auth_token`].
159    auth_token: Option<String>,
160    #[cfg(not(wasm_browser))]
161    dns_resolver: DnsResolver,
162    /// Cache for public keys of remote endpoints.
163    key_cache: KeyCache,
164}
165
166impl ClientBuilder {
167    /// Create a new [`ClientBuilder`]
168    pub fn new(
169        url: impl Into<RelayUrl>,
170        secret_key: SecretKey,
171        #[cfg(not(wasm_browser))] dns_resolver: DnsResolver,
172    ) -> Self {
173        ClientBuilder {
174            address_family_selector: None,
175            url: url.into(),
176            tls_config: None,
177            proxy_url: None,
178            secret_key,
179            #[cfg(not(wasm_browser))]
180            dns_resolver,
181            key_cache: KeyCache::new(128),
182            auth_token: None,
183        }
184    }
185
186    /// Sets a custom TLS config.
187    ///
188    /// This is a required option.
189    ///
190    /// You can construct a [`rustls::ClientConfig`] by combining a [`rustls::crypto::CryptoProvider`]
191    /// with a [`tls::CaTlsConfig`] using [`tls::CaTlsConfig::client_config`], for example:
192    ///
193    /// ```no_run
194    /// use std::sync::Arc;
195    ///
196    /// use iroh_relay::tls::CaTlsConfig;
197    ///
198    /// let crypto_provider: rustls::crypto::CryptoProvider = todo!();
199    /// let client_config = CaTlsConfig::default().client_config(Arc::new(crypto_provider));
200    /// ```
201    ///
202    /// If you enable the tls-ring or tls-aws-lc-rs feature, you can use the enabled crypto provider
203    /// by using [`tls::default_provider`].
204    ///
205    /// [`tls::CaTlsConfig`]: crate::tls::CaTlsConfig
206    /// [`tls::CaTlsConfig::client_config`]: crate::tls::CaTlsConfig::client_config
207    /// [`tls::default_provider`]: crate::tls::default_provider
208    pub fn tls_client_config(mut self, tls_config: rustls::ClientConfig) -> Self {
209        self.tls_config = Some(tls_config);
210        self
211    }
212
213    /// Sets a callback hinting whether to prefer IPv6 when dialing the relay.
214    ///
215    /// The callback runs on each dial. When it returns `true`, IPv6 addresses
216    /// are tried first and IPv4 dials are held back slightly, biasing the
217    /// happy-eyeballs race towards IPv6; when it returns `false`, IPv4 is
218    /// preferred. Only return `true` when IPv6 is expected to work, since
219    /// otherwise the bias just delays the connection.
220    pub fn address_family_selector<S>(mut self, selector: S) -> Self
221    where
222        S: Fn() -> bool + Send + Sync + 'static,
223    {
224        self.address_family_selector = Some(Arc::new(selector));
225        self
226    }
227
228    /// Set an explicit proxy url to proxy all HTTP(S) traffic through.
229    pub fn proxy_url(mut self, url: Url) -> Self {
230        self.proxy_url.replace(url);
231        self
232    }
233
234    /// Sets an authorization token.
235    ///
236    /// On native targets, the token is sent as an `Authorization: Bearer TOKEN`
237    /// header on the WebSocket upgrade request that establishes the relay
238    /// connection. The token must be a valid HTTP header field value, if not
239    /// [`Self::connect`] will return [`ConnectError::InvalidAuthToken`].
240    ///
241    /// When compiled to WebAssembly the token is sent as a `?token=TOKEN`
242    /// query parameter on the upgrade URL, since browsers don't allow setting
243    /// headers on WebSocket requests.
244    pub fn auth_token(mut self, token: impl Into<String>) -> Self {
245        self.auth_token = Some(token.into());
246        self
247    }
248
249    /// Set the capacity of the cache for public keys.
250    pub fn key_cache_capacity(mut self, capacity: usize) -> Self {
251        self.key_cache = KeyCache::new(capacity);
252        self
253    }
254
255    /// Establishes a new connection to the relay server.
256    #[cfg(not(wasm_browser))]
257    pub async fn connect(&self) -> Result<Client, ConnectError> {
258        use http::header::{AUTHORIZATION, HeaderValue, SEC_WEBSOCKET_PROTOCOL};
259        use n0_error::StdResultExt;
260        use tls::MaybeTlsStreamBuilder;
261
262        use crate::{
263            http::CLIENT_AUTH_HEADER,
264            protos::{handshake::KeyMaterialClientAuth, relay::MAX_FRAME_SIZE},
265        };
266
267        let mut dial_url = self.url.join(RELAY_RELATIVE_PATH).map_err(|_| {
268            e!(ConnectError::InvalidRelayUrl {
269                url: (*self.url).clone()
270            })
271        })?;
272        // The relay URL is exchanged with the http(s) scheme in tickets and similar.
273        // We need to use the ws:// or wss:// schemes when connecting with websockets, though.
274        dial_url
275            .set_scheme(match self.url.scheme() {
276                "http" => "ws",
277                "ws" => "ws",
278                _ => "wss",
279            })
280            .map_err(|_| {
281                e!(ConnectError::InvalidWebsocketUrl {
282                    url: dial_url.clone()
283                })
284            })?;
285
286        debug!(%dial_url, "Dialing relay by websocket");
287
288        let tls_config = self
289            .tls_config
290            .clone()
291            .ok_or_else(|| e!(ConnectError::MissingCryptoProvider))?;
292
293        #[allow(unused_mut)]
294        let mut builder =
295            MaybeTlsStreamBuilder::new(dial_url.clone(), self.dns_resolver.clone(), tls_config)
296                .prefer_ipv6(self.prefer_ipv6())
297                .proxy_url(self.proxy_url.clone());
298
299        let stream = builder.connect().await?;
300        let local_addr = stream
301            .as_ref()
302            .local_addr()
303            .map_err(|_| e!(ConnectError::NoLocalAddr))?;
304
305        let mut builder = tokio_websockets::ClientBuilder::new()
306            .uri(dial_url.as_str())
307            .map_err(|_| {
308                e!(ConnectError::InvalidRelayUrl {
309                    url: dial_url.clone()
310                })
311            })?
312            .add_header(
313                SEC_WEBSOCKET_PROTOCOL,
314                ProtocolVersion::all_as_header_value(),
315            )
316            .expect("valid header name and value")
317            .limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)))
318            // We turn off automatic flushing after a threshold (the default would be after 8KB).
319            // This means we need to flush manually, which we do by calling `Sink::send_all` or
320            // `Sink::send` (which calls `Sink::flush`) in the `ActiveRelayActor`.
321            .config(tokio_websockets::Config::default().flush_threshold(usize::MAX));
322
323        if let Some(token) = self.auth_token.as_ref() {
324            let value = HeaderValue::from_str(&format!("Bearer {token}"))
325                .map_err(|_| e!(ConnectError::InvalidAuthToken))?;
326            builder = builder
327                .add_header(AUTHORIZATION, value)
328                .expect("valid header name");
329        }
330
331        if let Some(client_auth) = KeyMaterialClientAuth::new(&self.secret_key, &stream) {
332            debug!("Using TLS key export for relay client authentication");
333            builder = builder
334                .add_header(CLIENT_AUTH_HEADER, client_auth.into_header_value())
335                .expect(
336                    "impossible: CLIENT_AUTH_HEADER isn't a disallowed header value for websockets",
337                );
338        }
339        let (conn, response) = builder.connect_on(stream).await.anyerr()?;
340
341        n0_error::ensure!(
342            response.status() == hyper::StatusCode::SWITCHING_PROTOCOLS,
343            ConnectError::UnexpectedUpgradeStatus {
344                code: response.status()
345            }
346        );
347
348        let protocol_version_str = response
349            .headers()
350            .get(SEC_WEBSOCKET_PROTOCOL)
351            .and_then(|s| s.to_str().ok());
352        let protocol_version = protocol_version_str
353            .and_then(ProtocolVersion::match_from_str)
354            .ok_or_else(|| {
355                e!(ConnectError::BadVersionHeader {
356                    server_version: protocol_version_str.map(ToOwned::to_owned)
357                })
358            })?;
359
360        let conn = Conn::new(
361            conn,
362            self.key_cache.clone(),
363            &self.secret_key,
364            protocol_version,
365        )
366        .await?;
367
368        trace!("connect done");
369
370        Ok(Client {
371            conn,
372            local_addr: Some(local_addr),
373        })
374    }
375
376    /// Reports whether IPv4 dials should be slightly
377    /// delayed to give IPv6 a better chance of winning dial races.
378    /// Implementations should only return true if IPv6 is expected
379    /// to succeed. (otherwise delaying IPv4 will delay the connection
380    /// overall)
381    #[cfg(not(wasm_browser))]
382    fn prefer_ipv6(&self) -> bool {
383        match self.address_family_selector {
384            Some(ref selector) => selector(),
385            None => false,
386        }
387    }
388
389    /// Establishes a new connection to the relay server.
390    #[cfg(wasm_browser)]
391    pub async fn connect(&self) -> Result<Client, ConnectError> {
392        use crate::http::AUTH_TOKEN_URL_QUERY_PARAM;
393
394        let mut dial_url = self.url.join(RELAY_RELATIVE_PATH).map_err(|_| {
395            e!(ConnectError::InvalidRelayUrl {
396                url: (*self.url).clone()
397            })
398        })?;
399        // The relay URL is exchanged with the http(s) scheme in tickets and similar.
400        // We need to use the ws:// or wss:// schemes when connecting with websockets, though.
401        dial_url
402            .set_scheme(match self.url.scheme() {
403                "http" => "ws",
404                "ws" => "ws",
405                _ => "wss",
406            })
407            .map_err(|_| {
408                e!(ConnectError::InvalidWebsocketUrl {
409                    url: dial_url.clone()
410                })
411            })?;
412
413        if let Some(token) = self.auth_token.as_ref() {
414            dial_url
415                .query_pairs_mut()
416                .append_pair(AUTH_TOKEN_URL_QUERY_PARAM, token);
417        }
418
419        debug!(%dial_url, "Dialing relay by websocket");
420
421        let (ws_meta, ws_stream) = ws_stream_wasm::WsMeta::connect(
422            dial_url.as_str(),
423            Some(ProtocolVersion::all().collect()),
424        )
425        .await
426        .anyerr()?;
427
428        let protocol_version =
429            ProtocolVersion::match_from_str(&ws_meta.protocol()).ok_or_else(|| {
430                e!(ConnectError::BadVersionHeader {
431                    server_version: Some(ws_meta.protocol())
432                })
433            })?;
434
435        let conn = Conn::new(
436            ws_stream,
437            self.key_cache.clone(),
438            &self.secret_key,
439            protocol_version,
440        )
441        .await?;
442
443        trace!("connect done");
444
445        Ok(Client {
446            conn,
447            local_addr: None,
448        })
449    }
450}
451
452/// A relay client.
453#[derive(Debug)]
454pub struct Client {
455    conn: Conn,
456    local_addr: Option<SocketAddr>,
457}
458
459impl Client {
460    /// Splits the client into a sink and a stream.
461    pub fn split(self) -> (ClientStream, ClientSink) {
462        let (sink, stream) = split(self.conn);
463        (
464            ClientStream {
465                stream,
466                local_addr: self.local_addr,
467            },
468            ClientSink { sink },
469        )
470    }
471}
472
473impl Stream for Client {
474    type Item = Result<RelayToClientMsg, RecvError>;
475
476    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
477        Pin::new(&mut self.conn).poll_next(cx)
478    }
479}
480
481impl Sink<ClientToRelayMsg> for Client {
482    type Error = SendError;
483
484    fn poll_ready(
485        mut self: Pin<&mut Self>,
486        cx: &mut task::Context<'_>,
487    ) -> Poll<Result<(), Self::Error>> {
488        Pin::new(&mut self.conn).poll_ready(cx)
489    }
490
491    fn start_send(mut self: Pin<&mut Self>, item: ClientToRelayMsg) -> Result<(), Self::Error> {
492        Pin::new(&mut self.conn).start_send(item)
493    }
494
495    fn poll_flush(
496        mut self: Pin<&mut Self>,
497        cx: &mut task::Context<'_>,
498    ) -> Poll<Result<(), Self::Error>> {
499        Pin::new(&mut self.conn).poll_flush(cx)
500    }
501
502    fn poll_close(
503        mut self: Pin<&mut Self>,
504        cx: &mut task::Context<'_>,
505    ) -> Poll<Result<(), Self::Error>> {
506        Pin::new(&mut self.conn).poll_close(cx)
507    }
508}
509
510/// The send half of a relay client.
511#[derive(Debug)]
512pub struct ClientSink {
513    sink: SplitSink<Conn, ClientToRelayMsg>,
514}
515
516impl Sink<ClientToRelayMsg> for ClientSink {
517    type Error = SendError;
518
519    fn poll_ready(
520        mut self: Pin<&mut Self>,
521        cx: &mut task::Context<'_>,
522    ) -> Poll<Result<(), Self::Error>> {
523        Pin::new(&mut self.sink).poll_ready(cx)
524    }
525
526    fn start_send(mut self: Pin<&mut Self>, item: ClientToRelayMsg) -> Result<(), Self::Error> {
527        Pin::new(&mut self.sink).start_send(item)
528    }
529
530    fn poll_flush(
531        mut self: Pin<&mut Self>,
532        cx: &mut task::Context<'_>,
533    ) -> Poll<Result<(), Self::Error>> {
534        Pin::new(&mut self.sink).poll_flush(cx)
535    }
536
537    fn poll_close(
538        mut self: Pin<&mut Self>,
539        cx: &mut task::Context<'_>,
540    ) -> Poll<Result<(), Self::Error>> {
541        Pin::new(&mut self.sink).poll_close(cx)
542    }
543}
544
545/// The receive half of a relay client.
546#[derive(Debug)]
547pub struct ClientStream {
548    stream: SplitStream<Conn>,
549    local_addr: Option<SocketAddr>,
550}
551
552impl ClientStream {
553    /// Returns the local address of the client.
554    pub fn local_addr(&self) -> Option<SocketAddr> {
555        self.local_addr
556    }
557}
558
559impl Stream for ClientStream {
560    type Item = Result<RelayToClientMsg, RecvError>;
561
562    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
563        Pin::new(&mut self.stream).poll_next(cx)
564    }
565}