1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
use std::{
fmt::{self, Display},
future::Future,
net::SocketAddr,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use futures_util::{future::FutureExt, stream::Stream};
use quinn::{ClientConfig, Connection, Endpoint, NewConnection, OpenBi, TransportConfig, VarInt};
use rustls::{version::TLS13, ClientConfig as TlsClientConfig};
use crate::{
error::ProtoError,
quic::quic_stream::{DoqErrorCode, QuicStream},
udp::UdpSocket,
xfer::{DnsRequest, DnsRequestSender, DnsResponse, DnsResponseStream},
};
use super::{quic_config, quic_stream};
#[must_use = "futures do nothing unless polled"]
pub struct QuicClientStream {
quic_connection: Connection,
name_server_name: Arc<str>,
name_server: SocketAddr,
is_shutdown: bool,
}
impl Display for QuicClientStream {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
formatter,
"QUIC({},{})",
self.name_server, self.name_server_name
)
}
}
impl QuicClientStream {
pub fn builder() -> QuicClientStreamBuilder {
QuicClientStreamBuilder::default()
}
async fn inner_send(stream: OpenBi, message: DnsRequest) -> Result<DnsResponse, ProtoError> {
let (send_stream, recv_stream) = stream.await?;
let mut stream = QuicStream::new(send_stream, recv_stream);
stream.send(message.into_parts().0).await?;
stream.finish().await?;
let response = stream.receive().await?;
Ok(response.into())
}
}
impl DnsRequestSender for QuicClientStream {
fn send_message(&mut self, message: DnsRequest) -> DnsResponseStream {
if self.is_shutdown {
panic!("can not send messages after stream is shutdown")
}
let connection = self.quic_connection.open_bi();
Box::pin(Self::inner_send(connection, message)).into()
}
fn shutdown(&mut self) {
self.is_shutdown = true;
self.quic_connection
.close(DoqErrorCode::NoError.into(), b"Shutdown");
}
fn is_shutdown(&self) -> bool {
self.is_shutdown
}
}
impl Stream for QuicClientStream {
type Item = Result<(), ProtoError>;
fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.is_shutdown {
Poll::Ready(None)
} else {
Poll::Ready(Some(Ok(())))
}
}
}
#[derive(Clone)]
pub struct QuicClientStreamBuilder {
crypto_config: TlsClientConfig,
transport_config: Arc<TransportConfig>,
bind_addr: Option<SocketAddr>,
}
impl QuicClientStreamBuilder {
pub fn crypto_config(&mut self, crypto_config: TlsClientConfig) -> &mut Self {
self.crypto_config = crypto_config;
self
}
pub fn bind_addr(&mut self, bind_addr: SocketAddr) -> &mut Self {
self.bind_addr = Some(bind_addr);
self
}
pub fn build(self, name_server: SocketAddr, dns_name: String) -> QuicClientConnect {
QuicClientConnect(Box::pin(self.connect(name_server, dns_name)) as _)
}
async fn connect(
self,
name_server: SocketAddr,
dns_name: String,
) -> Result<QuicClientStream, ProtoError> {
let connect = if let Some(bind_addr) = self.bind_addr {
<tokio::net::UdpSocket as UdpSocket>::connect_with_bind(name_server, bind_addr)
} else {
<tokio::net::UdpSocket as UdpSocket>::connect(name_server)
};
let socket = connect.await?;
let socket = socket.into_std()?;
let endpoint_config = quic_config::endpoint();
let (mut endpoint, _incoming) = Endpoint::new(endpoint_config, None, socket)?;
let mut crypto_config = self.crypto_config;
if crypto_config.alpn_protocols.is_empty() {
crypto_config.alpn_protocols = vec![quic_stream::DOQ_ALPN.to_vec()];
}
let early_data_enabled = crypto_config.enable_early_data;
let mut client_config = ClientConfig::new(Arc::new(crypto_config));
client_config.transport = self.transport_config;
endpoint.set_default_client_config(client_config);
let connecting = endpoint.connect(name_server, &dns_name)?;
let connection = if early_data_enabled {
match connecting.into_0rtt() {
Ok((new_connection, _)) => new_connection,
Err(connecting) => connecting.await?,
}
} else {
connecting.await?
};
let NewConnection {
connection: quic_connection,
..
} = connection;
Ok(QuicClientStream {
quic_connection,
name_server_name: Arc::from(dns_name),
name_server,
is_shutdown: false,
})
}
}
pub fn client_config_tls13_webpki_roots() -> TlsClientConfig {
use rustls::{OwnedTrustAnchor, RootCertStore};
let mut root_store = RootCertStore::empty();
root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject,
ta.spki,
ta.name_constraints,
)
}));
TlsClientConfig::builder()
.with_safe_default_cipher_suites()
.with_safe_default_kx_groups()
.with_protocol_versions(&[&TLS13])
.expect("TLS 1.3 not supported")
.with_root_certificates(root_store)
.with_no_client_auth()
}
impl Default for QuicClientStreamBuilder {
fn default() -> Self {
let mut transport_config = quic_config::transport();
transport_config.max_concurrent_bidi_streams(VarInt::from_u32(0));
let client_config = client_config_tls13_webpki_roots();
Self {
crypto_config: client_config,
transport_config: Arc::new(transport_config),
bind_addr: None,
}
}
}
pub struct QuicClientConnect(
Pin<Box<dyn Future<Output = Result<QuicClientStream, ProtoError>> + Send>>,
);
impl Future for QuicClientConnect {
type Output = Result<QuicClientStream, ProtoError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.0.poll_unpin(cx)
}
}
pub struct QuicClientResponse(
Pin<Box<dyn Future<Output = Result<DnsResponse, ProtoError>> + Send>>,
);
impl Future for QuicClientResponse {
type Output = Result<DnsResponse, ProtoError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.0.as_mut().poll(cx).map_err(ProtoError::from)
}
}