Skip to main content

karyon_p2p/
builtin_transports.rs

1//! The built-in TCP, TLS and QUIC transports. wasm has none: there
2//! `builtin_transports_wasm.rs` takes this module's place.
3
4use karyon_core::crypto::KeyPair;
5use karyon_net::{
6    ClientLayer, Endpoint,
7    tcp::{self, TcpListener},
8    tls::{ClientTlsConfig, ServerTlsConfig, TlsLayer},
9};
10
11use crate::{
12    Error, PeerID, Result,
13    config::{Config, CryptoProviderRef},
14    connector::DialResult,
15    listener::StreamListener,
16    peer_cert::peer_id_from_certs,
17    tls_config::{tls_client_config, tls_server_config},
18};
19
20#[cfg(feature = "quic")]
21use karyon_core::async_runtime::Executor;
22#[cfg(feature = "quic")]
23use karyon_net::{
24    StreamMux,
25    quic::{ClientQuicConfig, QuicEndpoint, QuicRuntimeRef, ServerQuicConfig},
26};
27
28#[cfg(feature = "quic")]
29use crate::tls_config::{quic_client_config, quic_server_config};
30
31static DNS_NAME: &str = "karyontech.net";
32
33/// Dials and listens with the built-in TCP, TLS and QUIC.
34pub(crate) struct BuiltinTransports {
35    /// Signs the TLS and QUIC certificates.
36    key_pair: KeyPair,
37    /// The rustls crypto (see `Config::crypto_provider`).
38    crypto_provider: Option<CryptoProviderRef>,
39    /// Runs the built-in QUIC (see `Config::quic_runtime`).
40    #[cfg(feature = "quic")]
41    quic_runtime: Option<QuicRuntimeRef>,
42}
43
44impl BuiltinTransports {
45    pub(crate) fn new(key_pair: &KeyPair, config: &Config) -> Self {
46        Self {
47            key_pair: key_pair.clone(),
48            crypto_provider: config.crypto_provider.clone(),
49            #[cfg(feature = "quic")]
50            quic_runtime: config.quic_runtime.clone(),
51        }
52    }
53
54    /// Dials a TCP or TLS endpoint.
55    pub(crate) async fn dial(
56        &self,
57        endpoint: &Endpoint,
58        peer_id: &Option<PeerID>,
59    ) -> Result<DialResult> {
60        match endpoint {
61            Endpoint::Tcp(..) => {
62                let stream = tcp::connect(endpoint, Default::default()).await?;
63                Ok(DialResult::Channel(stream, None))
64            }
65            Endpoint::Tls(..) => {
66                let tls_config = ClientTlsConfig {
67                    client_config: tls_client_config(
68                        &self.key_pair,
69                        peer_id.clone(),
70                        self.crypto_provider.as_ref(),
71                    )?,
72                    dns_name: DNS_NAME.to_string(),
73                };
74                let stream = tcp::connect(endpoint, Default::default()).await?;
75                let tls_layer = TlsLayer::client(tls_config);
76                let stream = ClientLayer::handshake(&tls_layer, stream).await?;
77                let vpid = stream
78                    .peer_certificates()
79                    .as_deref()
80                    .and_then(peer_id_from_certs);
81                Ok(DialResult::Channel(stream, vpid))
82            }
83            _ => Err(Error::UnsupportedEndpoint(endpoint.to_string())),
84        }
85    }
86
87    /// Dials a QUIC endpoint and opens the first stream, for the handshake.
88    #[cfg(feature = "quic")]
89    pub(crate) async fn dial_quic(
90        &self,
91        endpoint: &Endpoint,
92        peer_id: &Option<PeerID>,
93        ex: &Executor,
94    ) -> Result<DialResult> {
95        let rustls_config = quic_client_config(
96            &self.key_pair,
97            peer_id.clone(),
98            self.crypto_provider.as_ref(),
99        )?;
100        let mut config =
101            ClientQuicConfig::from_rustls(rustls_config, DNS_NAME).with_executor(ex.clone());
102        if let Some(runtime) = &self.quic_runtime {
103            config = config.with_runtime(runtime.clone());
104        }
105        let quic_conn = QuicEndpoint::dial(endpoint, config).await?;
106        let vpid = quic_conn
107            .peer_certificates()
108            .as_deref()
109            .and_then(peer_id_from_certs);
110        let stream = quic_conn.open_stream().await?;
111        Ok(DialResult::Quic(stream, quic_conn, vpid))
112    }
113
114    /// Listens on a TCP or TLS endpoint.
115    pub(crate) async fn listen(&self, endpoint: &Endpoint) -> Result<StreamListener> {
116        match endpoint {
117            Endpoint::Tcp(..) => {
118                let listener = TcpListener::bind(endpoint, Default::default()).await?;
119                Ok(StreamListener::plain(Box::new(listener)))
120            }
121            Endpoint::Tls(..) => {
122                let tls_config = ServerTlsConfig {
123                    server_config: tls_server_config(
124                        &self.key_pair,
125                        self.crypto_provider.as_ref(),
126                    )?,
127                };
128                let listener = TcpListener::bind(endpoint, Default::default()).await?;
129                Ok(StreamListener {
130                    inner: Box::new(listener),
131                    tls: Some(Box::new(TlsLayer::server(tls_config))),
132                })
133            }
134            _ => Err(Error::UnsupportedEndpoint(endpoint.to_string())),
135        }
136    }
137
138    /// The config of a built-in QUIC listener.
139    #[cfg(feature = "quic")]
140    pub(crate) fn quic_server_config(&self, ex: &Executor) -> Result<ServerQuicConfig> {
141        let rustls_config = quic_server_config(&self.key_pair, self.crypto_provider.as_ref())?;
142        let mut config = ServerQuicConfig::from_rustls(rustls_config).with_executor(ex.clone());
143        if let Some(runtime) = &self.quic_runtime {
144            config = config.with_runtime(runtime.clone());
145        }
146        Ok(config)
147    }
148}