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};
14use n0_future::{
15    Sink, Stream,
16    split::{SplitSink, SplitStream, split},
17    time,
18};
19use nested_enum_utils::common_fields;
20use snafu::{Backtrace, Snafu};
21#[cfg(any(test, feature = "test-utils"))]
22use tracing::warn;
23use tracing::{Level, debug, event, trace};
24use url::Url;
25
26pub use self::conn::{RecvError, SendError};
27#[cfg(not(wasm_browser))]
28use crate::dns::{DnsError, DnsResolver};
29use crate::{
30    KeyCache,
31    http::RELAY_PATH,
32    protos::{
33        handshake,
34        relay::{ClientToRelayMsg, RelayToClientMsg},
35    },
36};
37
38pub(crate) mod conn;
39#[cfg(not(wasm_browser))]
40pub(crate) mod streams;
41#[cfg(not(wasm_browser))]
42mod tls;
43#[cfg(not(wasm_browser))]
44mod util;
45
46/// Connection errors.
47///
48/// `ConnectError` contains `DialError`, errors that can occur while dialing the
49/// relay, as well as errors that occur while creating or maintaining a connection.
50#[common_fields({
51    backtrace: Option<Backtrace>,
52    #[snafu(implicit)]
53    span_trace: n0_snafu::SpanTrace,
54})]
55#[allow(missing_docs)]
56#[derive(Debug, Snafu)]
57#[non_exhaustive]
58pub enum ConnectError {
59    #[snafu(display("Invalid URL for websocket: {url}"))]
60    InvalidWebsocketUrl { url: Url },
61    #[snafu(display("Invalid relay URL: {url}"))]
62    InvalidRelayUrl { url: Url },
63    #[snafu(transparent)]
64    Websocket {
65        #[cfg(not(wasm_browser))]
66        source: tokio_websockets::Error,
67        #[cfg(wasm_browser)]
68        source: ws_stream_wasm::WsErr,
69    },
70    #[snafu(transparent)]
71    Handshake { source: handshake::Error },
72    #[snafu(transparent)]
73    Dial { source: DialError },
74    #[snafu(display("Unexpected status during upgrade: {code}"))]
75    UnexpectedUpgradeStatus { code: hyper::StatusCode },
76    #[snafu(display("Failed to upgrade response"))]
77    Upgrade { source: hyper::Error },
78    #[snafu(display("Invalid TLS servername"))]
79    InvalidTlsServername {},
80    #[snafu(display("No local address available"))]
81    NoLocalAddr {},
82    #[snafu(display("tls connection failed"))]
83    Tls { source: std::io::Error },
84    #[cfg(wasm_browser)]
85    #[snafu(display("The relay protocol is not available in browsers"))]
86    RelayProtoNotAvailable {},
87}
88
89/// Errors that can occur while dialing the relay server.
90#[common_fields({
91    backtrace: Option<Backtrace>,
92    #[snafu(implicit)]
93    span_trace: n0_snafu::SpanTrace,
94})]
95#[allow(missing_docs)]
96#[derive(Debug, Snafu)]
97#[non_exhaustive]
98pub enum DialError {
99    #[snafu(display("Invliad target port"))]
100    InvalidTargetPort {},
101    #[snafu(transparent)]
102    #[cfg(not(wasm_browser))]
103    Dns { source: DnsError },
104    #[snafu(transparent)]
105    Timeout { source: time::Elapsed },
106    #[snafu(transparent)]
107    Io { source: std::io::Error },
108    #[snafu(display("Invalid URL: {url}"))]
109    InvalidUrl { url: Url },
110    #[snafu(display("Failed proxy connection: {status}"))]
111    ProxyConnectInvalidStatus { status: hyper::StatusCode },
112    #[snafu(display("Invalid Proxy URL {proxy_url}"))]
113    ProxyInvalidUrl { proxy_url: Url },
114    #[snafu(display("failed to establish proxy connection"))]
115    ProxyConnect { source: hyper::Error },
116    #[snafu(display("Invalid proxy TLS servername: {proxy_hostname}"))]
117    ProxyInvalidTlsServername { proxy_hostname: String },
118    #[snafu(display("Invalid proxy target port"))]
119    ProxyInvalidTargetPort {},
120}
121
122/// Build a Client.
123#[derive(derive_more::Debug, Clone)]
124pub struct ClientBuilder {
125    /// Default is None
126    #[debug("address family selector callback")]
127    address_family_selector: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
128    /// Server url.
129    url: RelayUrl,
130    /// Allow self-signed certificates from relay servers
131    #[cfg(any(test, feature = "test-utils"))]
132    insecure_skip_cert_verify: bool,
133    /// HTTP Proxy
134    proxy_url: Option<Url>,
135    /// The secret key of this client.
136    secret_key: SecretKey,
137    /// The DNS resolver to use.
138    #[cfg(not(wasm_browser))]
139    dns_resolver: DnsResolver,
140    /// Cache for public keys of remote nodes.
141    key_cache: KeyCache,
142}
143
144impl ClientBuilder {
145    /// Create a new [`ClientBuilder`]
146    pub fn new(
147        url: impl Into<RelayUrl>,
148        secret_key: SecretKey,
149        #[cfg(not(wasm_browser))] dns_resolver: DnsResolver,
150    ) -> Self {
151        ClientBuilder {
152            address_family_selector: None,
153            url: url.into(),
154
155            #[cfg(any(test, feature = "test-utils"))]
156            insecure_skip_cert_verify: false,
157
158            proxy_url: None,
159            secret_key,
160            #[cfg(not(wasm_browser))]
161            dns_resolver,
162            key_cache: KeyCache::new(128),
163        }
164    }
165
166    /// Returns if we should prefer ipv6
167    /// it replaces the relayhttp.AddressFamilySelector we pass
168    /// It provides the hint as to whether in an IPv4-vs-IPv6 race that
169    /// IPv4 should be held back a bit to give IPv6 a better-than-50/50
170    /// chance of winning. We only return true when we believe IPv6 will
171    /// work anyway, so we don't artificially delay the connection speed.
172    pub fn address_family_selector<S>(mut self, selector: S) -> Self
173    where
174        S: Fn() -> bool + Send + Sync + 'static,
175    {
176        self.address_family_selector = Some(Arc::new(selector));
177        self
178    }
179
180    /// Skip the verification of the relay server's SSL certificates.
181    ///
182    /// May only be used in tests.
183    #[cfg(any(test, feature = "test-utils"))]
184    pub fn insecure_skip_cert_verify(mut self, skip: bool) -> Self {
185        self.insecure_skip_cert_verify = skip;
186        self
187    }
188
189    /// Set an explicit proxy url to proxy all HTTP(S) traffic through.
190    pub fn proxy_url(mut self, url: Url) -> Self {
191        self.proxy_url.replace(url);
192        self
193    }
194
195    /// Set the capacity of the cache for public keys.
196    pub fn key_cache_capacity(mut self, capacity: usize) -> Self {
197        self.key_cache = KeyCache::new(capacity);
198        self
199    }
200
201    /// Establishes a new connection to the relay server.
202    #[cfg(not(wasm_browser))]
203    pub async fn connect(&self) -> Result<Client, ConnectError> {
204        use http::header::SEC_WEBSOCKET_PROTOCOL;
205        use tls::MaybeTlsStreamBuilder;
206
207        use crate::{
208            http::{CLIENT_AUTH_HEADER, RELAY_PROTOCOL_VERSION},
209            protos::{handshake::KeyMaterialClientAuth, relay::MAX_FRAME_SIZE},
210        };
211
212        let mut dial_url = (*self.url).clone();
213        dial_url.set_path(RELAY_PATH);
214        // The relay URL is exchanged with the http(s) scheme in tickets and similar.
215        // We need to use the ws:// or wss:// schemes when connecting with websockets, though.
216        dial_url
217            .set_scheme(match self.url.scheme() {
218                "http" => "ws",
219                "ws" => "ws",
220                _ => "wss",
221            })
222            .map_err(|_| {
223                InvalidWebsocketUrlSnafu {
224                    url: dial_url.clone(),
225                }
226                .build()
227            })?;
228
229        debug!(%dial_url, "Dialing relay by websocket");
230
231        #[allow(unused_mut)]
232        let mut builder = MaybeTlsStreamBuilder::new(dial_url.clone(), self.dns_resolver.clone())
233            .prefer_ipv6(self.prefer_ipv6())
234            .proxy_url(self.proxy_url.clone());
235
236        #[cfg(any(test, feature = "test-utils"))]
237        if self.insecure_skip_cert_verify {
238            builder = builder.insecure_skip_cert_verify(self.insecure_skip_cert_verify);
239        }
240
241        let stream = builder.connect().await?;
242        let local_addr = stream
243            .as_ref()
244            .local_addr()
245            .map_err(|_| NoLocalAddrSnafu.build())?;
246        let mut builder = tokio_websockets::ClientBuilder::new()
247            .uri(dial_url.as_str())
248            .map_err(|_| {
249                InvalidRelayUrlSnafu {
250                    url: dial_url.clone(),
251                }
252                .build()
253            })?
254            .add_header(
255                SEC_WEBSOCKET_PROTOCOL,
256                http::HeaderValue::from_static(RELAY_PROTOCOL_VERSION),
257            )
258            .expect("valid header name and value")
259            .limits(tokio_websockets::Limits::default().max_payload_len(Some(MAX_FRAME_SIZE)))
260            // We turn off automatic flushing after a threshold (the default would be after 8KB).
261            // This means we need to flush manually, which we do by calling `Sink::send_all` or
262            // `Sink::send` (which calls `Sink::flush`) in the `ActiveRelayActor`.
263            .config(tokio_websockets::Config::default().flush_threshold(usize::MAX));
264        if let Some(client_auth) = KeyMaterialClientAuth::new(&self.secret_key, &stream) {
265            debug!("Using TLS key export for relay client authentication");
266            builder = builder
267                .add_header(CLIENT_AUTH_HEADER, client_auth.into_header_value())
268                .expect(
269                    "impossible: CLIENT_AUTH_HEADER isn't a disallowed header value for websockets",
270                );
271        }
272        let (conn, response) = builder.connect_on(stream).await?;
273
274        if response.status() != hyper::StatusCode::SWITCHING_PROTOCOLS {
275            UnexpectedUpgradeStatusSnafu {
276                code: response.status(),
277            }
278            .fail()?;
279        }
280
281        let conn = Conn::new(conn, self.key_cache.clone(), &self.secret_key).await?;
282
283        event!(
284            target: "events.net.relay.connected",
285            Level::DEBUG,
286            url = %self.url,
287        );
288
289        trace!("connect done");
290
291        Ok(Client {
292            conn,
293            local_addr: Some(local_addr),
294        })
295    }
296
297    /// Reports whether IPv4 dials should be slightly
298    /// delayed to give IPv6 a better chance of winning dial races.
299    /// Implementations should only return true if IPv6 is expected
300    /// to succeed. (otherwise delaying IPv4 will delay the connection
301    /// overall)
302    #[cfg(not(wasm_browser))]
303    fn prefer_ipv6(&self) -> bool {
304        match self.address_family_selector {
305            Some(ref selector) => selector(),
306            None => false,
307        }
308    }
309
310    /// Establishes a new connection to the relay server.
311    #[cfg(wasm_browser)]
312    pub async fn connect(&self) -> Result<Client, ConnectError> {
313        use crate::http::RELAY_PROTOCOL_VERSION;
314
315        let mut dial_url = (*self.url).clone();
316        dial_url.set_path(RELAY_PATH);
317        // The relay URL is exchanged with the http(s) scheme in tickets and similar.
318        // We need to use the ws:// or wss:// schemes when connecting with websockets, though.
319        dial_url
320            .set_scheme(match self.url.scheme() {
321                "http" => "ws",
322                "ws" => "ws",
323                _ => "wss",
324            })
325            .map_err(|_| {
326                InvalidWebsocketUrlSnafu {
327                    url: dial_url.clone(),
328                }
329                .build()
330            })?;
331
332        debug!(%dial_url, "Dialing relay by websocket");
333
334        let (_, ws_stream) =
335            ws_stream_wasm::WsMeta::connect(dial_url.as_str(), Some(vec![RELAY_PROTOCOL_VERSION]))
336                .await?;
337        let conn = Conn::new(ws_stream, self.key_cache.clone(), &self.secret_key).await?;
338
339        event!(
340            target: "events.net.relay.connected",
341            Level::DEBUG,
342            url = %self.url,
343        );
344
345        trace!("connect done");
346
347        Ok(Client {
348            conn,
349            local_addr: None,
350        })
351    }
352}
353
354/// A relay client.
355#[derive(Debug)]
356pub struct Client {
357    conn: Conn,
358    local_addr: Option<SocketAddr>,
359}
360
361impl Client {
362    /// Splits the client into a sink and a stream.
363    pub fn split(self) -> (ClientStream, ClientSink) {
364        let (sink, stream) = split(self.conn);
365        (
366            ClientStream {
367                stream,
368                local_addr: self.local_addr,
369            },
370            ClientSink { sink },
371        )
372    }
373}
374
375impl Stream for Client {
376    type Item = Result<RelayToClientMsg, RecvError>;
377
378    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
379        Pin::new(&mut self.conn).poll_next(cx)
380    }
381}
382
383impl Sink<ClientToRelayMsg> for Client {
384    type Error = SendError;
385
386    fn poll_ready(
387        mut self: Pin<&mut Self>,
388        cx: &mut task::Context<'_>,
389    ) -> Poll<Result<(), Self::Error>> {
390        Pin::new(&mut self.conn).poll_ready(cx)
391    }
392
393    fn start_send(mut self: Pin<&mut Self>, item: ClientToRelayMsg) -> Result<(), Self::Error> {
394        Pin::new(&mut self.conn).start_send(item)
395    }
396
397    fn poll_flush(
398        mut self: Pin<&mut Self>,
399        cx: &mut task::Context<'_>,
400    ) -> Poll<Result<(), Self::Error>> {
401        Pin::new(&mut self.conn).poll_flush(cx)
402    }
403
404    fn poll_close(
405        mut self: Pin<&mut Self>,
406        cx: &mut task::Context<'_>,
407    ) -> Poll<Result<(), Self::Error>> {
408        Pin::new(&mut self.conn).poll_close(cx)
409    }
410}
411
412/// The send half of a relay client.
413#[derive(Debug)]
414pub struct ClientSink {
415    sink: SplitSink<Conn, ClientToRelayMsg>,
416}
417
418impl Sink<ClientToRelayMsg> for ClientSink {
419    type Error = SendError;
420
421    fn poll_ready(
422        mut self: Pin<&mut Self>,
423        cx: &mut task::Context<'_>,
424    ) -> Poll<Result<(), Self::Error>> {
425        Pin::new(&mut self.sink).poll_ready(cx)
426    }
427
428    fn start_send(mut self: Pin<&mut Self>, item: ClientToRelayMsg) -> Result<(), Self::Error> {
429        Pin::new(&mut self.sink).start_send(item)
430    }
431
432    fn poll_flush(
433        mut self: Pin<&mut Self>,
434        cx: &mut task::Context<'_>,
435    ) -> Poll<Result<(), Self::Error>> {
436        Pin::new(&mut self.sink).poll_flush(cx)
437    }
438
439    fn poll_close(
440        mut self: Pin<&mut Self>,
441        cx: &mut task::Context<'_>,
442    ) -> Poll<Result<(), Self::Error>> {
443        Pin::new(&mut self.sink).poll_close(cx)
444    }
445}
446
447/// The receive half of a relay client.
448#[derive(Debug)]
449pub struct ClientStream {
450    stream: SplitStream<Conn>,
451    local_addr: Option<SocketAddr>,
452}
453
454impl ClientStream {
455    /// Returns the local address of the client.
456    pub fn local_addr(&self) -> Option<SocketAddr> {
457        self.local_addr
458    }
459}
460
461impl Stream for ClientStream {
462    type Item = Result<RelayToClientMsg, RecvError>;
463
464    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
465        Pin::new(&mut self.stream).poll_next(cx)
466    }
467}
468
469#[cfg(any(test, feature = "test-utils"))]
470/// Creates a client config that trusts any servers without verifying their TLS certificate.
471///
472/// Should be used for testing local relay setups only.
473pub fn make_dangerous_client_config() -> rustls::ClientConfig {
474    warn!(
475        "Insecure config: SSL certificates from relay servers will be trusted without verification"
476    );
477    rustls::client::ClientConfig::builder_with_provider(Arc::new(
478        rustls::crypto::ring::default_provider(),
479    ))
480    .with_protocol_versions(&[&rustls::version::TLS13])
481    .expect("protocols supported by ring")
482    .dangerous()
483    .with_custom_certificate_verifier(Arc::new(NoCertVerifier))
484    .with_no_client_auth()
485}
486
487/// Used to allow self signed certificates in tests
488#[cfg(any(test, feature = "test-utils"))]
489#[derive(Debug)]
490struct NoCertVerifier;
491
492#[cfg(any(test, feature = "test-utils"))]
493impl rustls::client::danger::ServerCertVerifier for NoCertVerifier {
494    fn verify_server_cert(
495        &self,
496        _end_entity: &rustls::pki_types::CertificateDer,
497        _intermediates: &[rustls::pki_types::CertificateDer],
498        _server_name: &rustls::pki_types::ServerName,
499        _ocsp_response: &[u8],
500        _now: rustls::pki_types::UnixTime,
501    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
502        Ok(rustls::client::danger::ServerCertVerified::assertion())
503    }
504    fn verify_tls12_signature(
505        &self,
506        _message: &[u8],
507        _cert: &rustls::pki_types::CertificateDer<'_>,
508        _dss: &rustls::DigitallySignedStruct,
509    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
510        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
511    }
512
513    fn verify_tls13_signature(
514        &self,
515        _message: &[u8],
516        _cert: &rustls::pki_types::CertificateDer<'_>,
517        _dss: &rustls::DigitallySignedStruct,
518    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
519        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
520    }
521
522    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
523        rustls::crypto::ring::default_provider()
524            .signature_verification_algorithms
525            .supported_schemes()
526    }
527}