Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft code to add TlsConnect trait #2139

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions crates/client/Cargo.toml
Expand Up @@ -41,10 +41,9 @@ dns-over-https-openssl = ["dns-over-https", "dns-over-openssl"]
dns-over-https-rustls = [
"dns-over-https",
"dns-over-rustls",
"rustls",
"hickory-proto/dns-over-https-rustls",
]
dns-over-https = ["hickory-proto/dns-over-https"]
dns-over-https = ["dns-over-tls", "h2", "bytes", "hickory-proto/dns-over-https"]

dns-over-quic = ["dns-over-rustls", "hickory-proto/dns-over-quic"]

Expand All @@ -53,6 +52,8 @@ dns-over-openssl = ["dns-over-tls", "dnssec-openssl"]
dns-over-rustls = [
"dns-over-tls",
"dnssec-ring",
"rustls",
"tokio-rustls",
"hickory-proto/dns-over-rustls",
]
dns-over-tls = []
Expand Down Expand Up @@ -86,6 +87,9 @@ once_cell.workspace = true
radix_trie.workspace = true
rand.workspace = true
rustls = { workspace = true, optional = true }
tokio-rustls = { workspace = true, optional = true }
h2 = { workspace = true, features = ["stream"], optional = true }
bytes = { workspace = true, optional = true }
serde = { workspace = true, features = ["derive"], optional = true }
thiserror.workspace = true
tracing.workspace = true
Expand Down
179 changes: 179 additions & 0 deletions crates/client/src/h2/mod.rs
@@ -0,0 +1,179 @@
#[cfg(feature = "dns-over-https-rustls")]
mod client_connection;
#[cfg(feature = "dns-over-https-rustls")]
pub use client_connection::HttpsClientConnection;

use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use crate::proto::error::ProtoError;
use crate::proto::h2::HttpsClientStream;
use crate::proto::iocompat::AsyncIoStdAsTokio;
use crate::proto::tcp::{Connect, DnsTcpStream};

use bytes::Bytes;
use futures_util::future::{FutureExt, TryFutureExt};
use futures_util::ready;
use h2::client::{Connection, SendRequest};
use tracing::{debug, warn};

use crate::tls::connect::TlsConnect;

pub fn connect_with_bind_addr<S: Connect, TC: TlsConnect<S> + Send + 'static>(
name_server: SocketAddr,
bind_addr: Option<SocketAddr>,
tls_connector: TC,
) -> HttpsClientConnect<S, TC>
where
TC::TlsStream: DnsTcpStream,
{
let connect = S::connect_with_bind(name_server, bind_addr);

HttpsClientConnect::<S, TC>(HttpsClientConnectState::TcpConnecting {
connect,
name_server,
tls: Some(tls_connector),
})
}

pub struct HttpsClientConnect<S, TC>(HttpsClientConnectState<S, TC>)
where
S: Connect,
TC: TlsConnect<S>;

impl<S, TC> Future for HttpsClientConnect<S, TC>
where
S: Connect,
TC: TlsConnect<S> + Unpin,
{
type Output = Result<HttpsClientStream, ProtoError>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.0.poll_unpin(cx)
}
}

enum HttpsClientConnectState<S, TC>
where
S: Connect,
TC: TlsConnect<S>,
{
TcpConnecting {
connect: Pin<Box<dyn Future<Output = io::Result<S>> + Send>>,
name_server: SocketAddr,
tls: Option<TC>,
},
TlsConnecting {
// TODO: also abstract away Tokio TLS in RuntimeProvider.
tls: Pin<Box<dyn Future<Output = io::Result<TC::TlsStream>> + Send>>,
name_server_name: Arc<str>,
name_server: SocketAddr,
},
H2Handshake {
handshake: Pin<
Box<
dyn Future<
Output = Result<
(
SendRequest<Bytes>,
Connection<AsyncIoStdAsTokio<TC::TlsStream>, Bytes>,
),
h2::Error,
>,
> + Send,
>,
>,
name_server_name: Arc<str>,
name_server: SocketAddr,
},
Connected(Option<HttpsClientStream>),
Errored(Option<ProtoError>),
}

impl<S, TC> Future for HttpsClientConnectState<S, TC>
where
S: Connect,
TC: TlsConnect<S> + Unpin,
{
type Output = Result<HttpsClientStream, ProtoError>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let next = match *self {
Self::TcpConnecting {
ref mut connect,
name_server,
ref mut tls,
} => {
let tcp = ready!(connect.poll_unpin(cx))?;

debug!("tcp connection established to: {}", name_server);
let tls = tls
.take()
.expect("programming error, tls should not be None here");
let name_server_name = Arc::from(tls.server_name());

let tls_connect = tls.tls_connect(tcp);
Self::TlsConnecting {
name_server_name,
name_server,
tls: tls_connect,
}
}
Self::TlsConnecting {
ref name_server_name,
name_server,
ref mut tls,
} => {
let tls = ready!(tls.poll_unpin(cx))?;
debug!("tls connection established to: {}", name_server);
let mut handshake = h2::client::Builder::new();
handshake.enable_push(false);

let handshake = handshake.handshake(AsyncIoStdAsTokio(tls));
Self::H2Handshake {
name_server_name: Arc::clone(name_server_name),
name_server,
handshake: Box::pin(handshake),
}
}
Self::H2Handshake {
ref name_server_name,
name_server,
ref mut handshake,
} => {
let (send_request, connection) = ready!(handshake
.poll_unpin(cx)
.map_err(|e| ProtoError::from(format!("h2 handshake error: {e}"))))?;

// TODO: hand this back for others to run rather than spawning here?
debug!("h2 connection established to: {}", name_server);
tokio::spawn(
connection
.map_err(|e| warn!("h2 connection failed: {e}"))
.map(|_: Result<(), ()>| ()),
);

Self::Connected(Some(HttpsClientStream::new(
Arc::clone(name_server_name),
name_server,
send_request,
)))
}
Self::Connected(ref mut conn) => {
return Poll::Ready(Ok(conn.take().expect("cannot poll after complete")))
}
Self::Errored(ref mut err) => {
return Poll::Ready(Err(err.take().expect("cannot poll after complete")))
}
};

*self.as_mut().deref_mut() = next;
}
}
}
17 changes: 6 additions & 11 deletions crates/client/src/lib.rs
Expand Up @@ -271,28 +271,23 @@

pub mod client;
pub mod error;
#[cfg(feature = "dns-over-https")]
#[cfg_attr(docsrs, doc(cfg(feature = "dns-over-https")))]
pub mod h2;
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
pub mod multicast;
pub mod op;
pub mod rr;
pub mod serialize;
pub mod tcp;
#[cfg(feature = "dns-over-tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "dns-over-tls")))]
pub mod tls;
pub mod udp;

// TODO: consider removing tcp/udp/https modules...
#[cfg(feature = "dns-over-https")]
mod h2_client_connection;

pub use hickory_proto as proto;

/// The https module which contains all https related connection types
#[cfg(feature = "dns-over-https")]
#[cfg_attr(docsrs, doc(cfg(feature = "dns-over-https")))]
pub mod h2 {
pub use super::h2_client_connection::HttpsClientConnection;
}

/// Returns a version as specified in Cargo.toml
pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
Expand Down
18 changes: 18 additions & 0 deletions crates/client/src/tls/connect/mod.rs
@@ -0,0 +1,18 @@
use std::future::Future;
use std::io;
use std::pin::Pin;

use crate::proto::tcp::{Connect, DnsTcpStream};

#[cfg(feature = "dns-over-rustls")]
pub mod rustls;

pub trait TlsConnect<S: Connect> {
type TlsStream: DnsTcpStream;

fn server_name(&self) -> String;
fn tls_connect(
&self,
stream: S,
) -> Pin<Box<dyn Future<Output = io::Result<Self::TlsStream>> + Send + Unpin + 'static>>;
}
50 changes: 50 additions & 0 deletions crates/client/src/tls/connect/rustls.rs
@@ -0,0 +1,50 @@
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::Arc;

use crate::proto::iocompat::{AsyncIoStdAsTokio, AsyncIoTokioAsStd};
use crate::proto::tcp::Connect;

use rustls::{ClientConfig, ServerName};
use tokio_rustls::client::TlsStream;
use tokio_rustls::TlsConnector;

use super::TlsConnect;

pub struct RustlsConnector {
pub config: Arc<ClientConfig>,
pub tls_name: ServerName,
}

impl<S: Connect> TlsConnect<S> for RustlsConnector {
type TlsStream = AsyncIoTokioAsStd<TlsStream<AsyncIoStdAsTokio<S>>>;

fn server_name(&self) -> String {
match &self.tls_name {
ServerName::DnsName(domain) => domain.as_ref().to_string(),
ServerName::IpAddress(ip) => ip.to_string(),
_ => panic!("unsupported server name"),
}
}

fn tls_connect(
&self,
stream: S,
) -> Pin<Box<dyn Future<Output = io::Result<Self::TlsStream>> + Send + Unpin + 'static>> {
let connect = connect_tls(self.config.clone(), self.tls_name.clone(), stream);
Box::pin(connect)
}
}

async fn connect_tls<S: Connect>(
config: Arc<ClientConfig>,
tls_name: ServerName,
stream: S,
) -> io::Result<AsyncIoTokioAsStd<TlsStream<AsyncIoStdAsTokio<S>>>> {
let connector = TlsConnector::from(config);
connector
.connect(tls_name, AsyncIoStdAsTokio(stream))
.await
.map(|s| AsyncIoTokioAsStd(s))
}