watermelon_mini/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::sync::Arc;
4
5use rustls_platform_verifier::Verifier;
6use tokio::net::TcpStream;
7use tokio_rustls::{
8    TlsConnector,
9    rustls::{self, ClientConfig, crypto::CryptoProvider, version::TLS13},
10};
11use watermelon_net::Connection;
12use watermelon_proto::{ServerAddr, ServerInfo};
13
14#[cfg(feature = "non-standard-zstd")]
15pub use self::non_standard_zstd::ZstdStream;
16use self::proto::connect;
17pub use self::proto::{
18    AuthenticationMethod, ConnectError, ConnectionCompression, ConnectionSecurity,
19};
20
21#[cfg(feature = "non-standard-zstd")]
22pub(crate) mod non_standard_zstd;
23mod proto;
24mod util;
25
26#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub struct ConnectFlags {
29    pub echo: bool,
30    #[cfg(feature = "non-standard-zstd")]
31    pub zstd_compression_level: Option<u8>,
32}
33
34impl Default for ConnectFlags {
35    fn default() -> Self {
36        Self {
37            echo: false,
38            #[cfg(feature = "non-standard-zstd")]
39            zstd_compression_level: Some(3),
40        }
41    }
42}
43
44/// Connect to a given address with some reasonable presets.
45///
46/// The function is going to establish a TLS 1.3 connection, without the support of the client
47/// authorization.
48///
49/// # Errors
50///
51/// This returns an error in case the connection fails.
52#[expect(
53    clippy::missing_panics_doc,
54    reason = "the crypto_provider function always returns a provider that supports TLS 1.3"
55)]
56pub async fn easy_connect(
57    addr: &ServerAddr,
58    auth: Option<&AuthenticationMethod>,
59    flags: ConnectFlags,
60) -> Result<
61    (
62        Connection<
63            ConnectionCompression<ConnectionSecurity<TcpStream>>,
64            ConnectionSecurity<TcpStream>,
65        >,
66        Box<ServerInfo>,
67    ),
68    ConnectError,
69> {
70    let provider = Arc::new(crypto_provider());
71    let connector = TlsConnector::from(Arc::new(
72        ClientConfig::builder_with_provider(Arc::clone(&provider))
73            .with_protocol_versions(&[&TLS13])
74            .unwrap()
75            .dangerous()
76            .with_custom_certificate_verifier(Arc::new(
77                Verifier::new(provider).map_err(ConnectError::Tls)?,
78            ))
79            .with_no_client_auth(),
80    ));
81
82    let (conn, info) = connect(&connector, addr, "watermelon".to_owned(), auth, flags).await?;
83    Ok((conn, info))
84}
85
86fn crypto_provider() -> CryptoProvider {
87    #[cfg(feature = "aws-lc-rs")]
88    return rustls::crypto::aws_lc_rs::default_provider();
89    #[cfg(all(not(feature = "aws-lc-rs"), feature = "ring"))]
90    return rustls::crypto::ring::default_provider();
91    #[cfg(not(any(feature = "aws-lc-rs", feature = "ring")))]
92    compile_error!("Please enable the `aws-lc-rs` or the `ring` feature")
93}