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