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::{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, CredsParseError,
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 tcp_nodelay: bool,
30 pub echo: bool,
31 pub client_name: Option<String>,
32 #[cfg(feature = "non-standard-zstd")]
33 pub zstd_compression_level: Option<u8>,
34}
35
36impl Default for ConnectFlags {
37 fn default() -> Self {
38 Self {
39 tcp_nodelay: true,
40 echo: false,
41 client_name: None,
42 #[cfg(feature = "non-standard-zstd")]
43 zstd_compression_level: Some(3),
44 }
45 }
46}
47
48#[expect(
57 clippy::missing_panics_doc,
58 reason = "the crypto_provider function always returns a provider that supports TLS 1.3"
59)]
60pub async fn easy_connect(
61 addr: &ServerAddr,
62 auth: Option<&AuthenticationMethod>,
63 flags: ConnectFlags,
64) -> Result<
65 (
66 Connection<
67 ConnectionCompression<ConnectionSecurity<TcpStream>>,
68 ConnectionSecurity<TcpStream>,
69 >,
70 Box<ServerInfo>,
71 ),
72 ConnectError,
73> {
74 let provider = Arc::new(crypto_provider());
75 let connector = TlsConnector::from(Arc::new(
76 ClientConfig::builder_with_provider(Arc::clone(&provider))
77 .with_protocol_versions(&[&TLS13])
78 .unwrap()
79 .dangerous()
80 .with_custom_certificate_verifier(Arc::new(
81 Verifier::new(provider).map_err(ConnectError::Tls)?,
82 ))
83 .with_no_client_auth(),
84 ));
85
86 let (conn, info) = connect(&connector, addr, flags.client_name.clone(), auth, flags).await?;
87 Ok((conn, info))
88}
89
90fn crypto_provider() -> CryptoProvider {
91 #[cfg(feature = "aws-lc-rs")]
92 return tokio_rustls::rustls::crypto::aws_lc_rs::default_provider();
93 #[cfg(all(not(feature = "aws-lc-rs"), feature = "ring"))]
94 return tokio_rustls::rustls::crypto::ring::default_provider();
95 #[cfg(all(
96 not(feature = "aws-lc-rs"),
97 not(feature = "ring"),
98 feature = "graviola"
99 ))]
100 return rustls_graviola::default_provider();
101 #[cfg(not(any(feature = "aws-lc-rs", feature = "ring", feature = "graviola")))]
102 compile_error!("Please enable the `aws-lc-rs`, the `ring` or the `graviola` feature")
103}