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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
use std::convert::TryInto;
use std::fmt::{self, Display};
use std::future::Future;
use std::io;
use std::net::SocketAddr;
use std::ops::DerefMut;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;
use std::task::{Context, Poll};
use bytes::{Buf, Bytes, BytesMut};
use futures_util::future::{FutureExt, TryFutureExt};
use futures_util::ready;
use futures_util::stream::Stream;
use h2::client::{Connection, SendRequest};
use http::header::{self, CONTENT_LENGTH};
use log::{debug, warn};
use rustls::ClientConfig;
use tokio_rustls::{
client::TlsStream as TokioTlsClientStream, Connect as TokioTlsConnect, TlsConnector,
};
use crate::error::ProtoError;
use crate::iocompat::AsyncIoStdAsTokio;
use crate::tcp::Connect;
use crate::xfer::{DnsRequest, DnsRequestSender, DnsResponse, DnsResponseStream, SerialMessage};
const ALPN_H2: &[u8] = b"h2";
#[derive(Clone)]
#[must_use = "futures do nothing unless polled"]
pub struct HttpsClientStream {
name_server_name: Arc<str>,
name_server: SocketAddr,
h2: SendRequest<Bytes>,
is_shutdown: bool,
}
impl Display for HttpsClientStream {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
formatter,
"HTTPS({},{})",
self.name_server, self.name_server_name
)
}
}
impl HttpsClientStream {
async fn inner_send(
h2: SendRequest<Bytes>,
message: Bytes,
name_server_name: Arc<str>,
name_server: SocketAddr,
) -> Result<DnsResponse, ProtoError> {
let mut h2 = match h2.ready().await {
Ok(h2) => h2,
Err(err) => {
return Err(ProtoError::from(format!("h2 send_request error: {}", err)));
}
};
let request = crate::https::request::new(&name_server_name, message.remaining());
let request =
request.map_err(|err| ProtoError::from(format!("bad http request: {}", err)))?;
debug!("request: {:#?}", request);
let (response_future, mut send_stream) = h2
.send_request(request, false)
.map_err(|err| ProtoError::from(format!("h2 send_request error: {}", err)))?;
send_stream
.send_data(message, true)
.map_err(|e| ProtoError::from(format!("h2 send_data error: {}", e)))?;
let mut response_stream = response_future
.await
.map_err(|err| ProtoError::from(format!("received a stream error: {}", err)))?;
debug!("got response: {:#?}", response_stream);
let content_length = response_stream
.headers()
.get(CONTENT_LENGTH)
.map(|v| v.to_str())
.transpose()
.map_err(|e| ProtoError::from(format!("bad headers received: {}", e)))?
.map(usize::from_str)
.transpose()
.map_err(|e| ProtoError::from(format!("bad headers received: {}", e)))?;
let mut response_bytes =
BytesMut::with_capacity(content_length.unwrap_or(512).clamp(512, 4096));
while let Some(partial_bytes) = response_stream.body_mut().data().await {
let partial_bytes =
partial_bytes.map_err(|e| ProtoError::from(format!("bad http request: {}", e)))?;
debug!("got bytes: {}", partial_bytes.len());
response_bytes.extend(partial_bytes);
if let Some(content_length) = content_length {
if response_bytes.len() >= content_length {
break;
}
}
}
if let Some(content_length) = content_length {
if response_bytes.len() != content_length {
return Err(ProtoError::from(format!(
"expected byte length: {}, got: {}",
content_length,
response_bytes.len()
)));
}
}
if !response_stream.status().is_success() {
let error_string = String::from_utf8_lossy(response_bytes.as_ref());
return Err(ProtoError::from(format!(
"http unsuccessful code: {}, message: {}",
response_stream.status(),
error_string
)));
} else {
{
let content_type = response_stream
.headers()
.get(header::CONTENT_TYPE)
.map(|h| {
h.to_str().map_err(|err| {
ProtoError::from(format!("ContentType header not a string: {}", err))
})
})
.unwrap_or(Ok(crate::https::MIME_APPLICATION_DNS))?;
if content_type != crate::https::MIME_APPLICATION_DNS {
return Err(ProtoError::from(format!(
"ContentType unsupported (must be '{}'): '{}'",
crate::https::MIME_APPLICATION_DNS,
content_type
)));
}
}
};
let message = SerialMessage::new(response_bytes.to_vec(), name_server).to_message()?;
Ok(message.into())
}
}
impl DnsRequestSender for HttpsClientStream {
fn send_message(&mut self, mut message: DnsRequest) -> DnsResponseStream {
if self.is_shutdown {
panic!("can not send messages after stream is shutdown")
}
message.set_id(0);
let bytes = match message.to_vec() {
Ok(bytes) => bytes,
Err(err) => return err.into(),
};
Box::pin(Self::inner_send(
self.h2.clone(),
Bytes::from(bytes),
Arc::clone(&self.name_server_name),
self.name_server,
))
.into()
}
fn shutdown(&mut self) {
self.is_shutdown = true;
}
fn is_shutdown(&self) -> bool {
self.is_shutdown
}
}
impl Stream for HttpsClientStream {
type Item = Result<(), ProtoError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.is_shutdown {
return Poll::Ready(None);
}
match self.h2.poll_ready(cx) {
Poll::Ready(Ok(())) => Poll::Ready(Some(Ok(()))),
Poll::Pending => Poll::Pending,
Poll::Ready(Err(e)) => Poll::Ready(Some(Err(ProtoError::from(format!(
"h2 stream errored: {}",
e
))))),
}
}
}
#[derive(Clone)]
pub struct HttpsClientStreamBuilder {
client_config: Arc<ClientConfig>,
bind_addr: Option<SocketAddr>,
}
impl HttpsClientStreamBuilder {
pub fn with_client_config(client_config: Arc<ClientConfig>) -> Self {
Self {
client_config,
bind_addr: None,
}
}
pub fn bind_addr(&mut self, bind_addr: SocketAddr) {
self.bind_addr = Some(bind_addr);
}
pub fn build<S: Connect>(
self,
name_server: SocketAddr,
dns_name: String,
) -> HttpsClientConnect<S> {
assert!(self
.client_config
.alpn_protocols
.iter()
.any(|protocol| *protocol == ALPN_H2.to_vec()));
let tls = TlsConfig {
client_config: self.client_config,
dns_name: Arc::from(dns_name),
};
HttpsClientConnect::<S>(HttpsClientConnectState::ConnectTcp {
name_server,
bind_addr: self.bind_addr,
tls: Some(tls),
})
}
}
pub struct HttpsClientConnect<S>(HttpsClientConnectState<S>)
where
S: Connect;
impl<S> Future for HttpsClientConnect<S>
where
S: Connect,
{
type Output = Result<HttpsClientStream, ProtoError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.0.poll_unpin(cx)
}
}
struct TlsConfig {
client_config: Arc<ClientConfig>,
dns_name: Arc<str>,
}
#[allow(clippy::large_enum_variant)]
#[allow(clippy::type_complexity)]
enum HttpsClientConnectState<S>
where
S: Connect,
{
ConnectTcp {
name_server: SocketAddr,
bind_addr: Option<SocketAddr>,
tls: Option<TlsConfig>,
},
TcpConnecting {
connect: Pin<Box<dyn Future<Output = io::Result<S>> + Send>>,
name_server: SocketAddr,
tls: Option<TlsConfig>,
},
TlsConnecting {
tls: TokioTlsConnect<AsyncIoStdAsTokio<S>>,
name_server_name: Arc<str>,
name_server: SocketAddr,
},
H2Handshake {
handshake: Pin<
Box<
dyn Future<
Output = Result<
(
SendRequest<Bytes>,
Connection<TokioTlsClientStream<AsyncIoStdAsTokio<S>>, Bytes>,
),
h2::Error,
>,
> + Send,
>,
>,
name_server_name: Arc<str>,
name_server: SocketAddr,
},
Connected(Option<HttpsClientStream>),
Errored(Option<ProtoError>),
}
impl<S> Future for HttpsClientConnectState<S>
where
S: Connect,
{
type Output = Result<HttpsClientStream, ProtoError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
let next = match *self {
HttpsClientConnectState::ConnectTcp {
name_server,
bind_addr,
ref mut tls,
} => {
debug!("tcp connecting to: {}", name_server);
let connect = S::connect_with_bind(name_server, bind_addr);
Self::TcpConnecting {
connect,
name_server,
tls: tls.take(),
}
}
HttpsClientConnectState::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::clone(&tls.dns_name);
match tls.dns_name.as_ref().try_into() {
Ok(dns_name) => {
let tls = TlsConnector::from(tls.client_config);
let tls = tls.connect(dns_name, AsyncIoStdAsTokio(tcp));
Self::TlsConnecting {
name_server_name,
name_server,
tls,
}
}
Err(_) => Self::Errored(Some(ProtoError::from(format!(
"bad dns_name: {}",
&tls.dns_name
)))),
}
}
HttpsClientConnectState::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(tls);
Self::H2Handshake {
name_server_name: Arc::clone(name_server_name),
name_server,
handshake: Box::pin(handshake),
}
}
HttpsClientConnectState::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))))?;
debug!("h2 connection established to: {}", name_server);
tokio::spawn(
connection
.map_err(|e| warn!("h2 connection failed: {}", e))
.map(|_: Result<(), ()>| ()),
);
Self::Connected(Some(HttpsClientStream {
name_server_name: Arc::clone(name_server_name),
name_server,
h2: send_request,
is_shutdown: false,
}))
}
HttpsClientConnectState::Connected(ref mut conn) => {
return Poll::Ready(Ok(conn.take().expect("cannot poll after complete")))
}
HttpsClientConnectState::Errored(ref mut err) => {
return Poll::Ready(Err(err.take().expect("cannot poll after complete")))
}
};
*self.as_mut().deref_mut() = next;
}
}
}
pub struct HttpsClientResponse(
Pin<Box<dyn Future<Output = Result<DnsResponse, ProtoError>> + Send>>,
);
impl Future for HttpsClientResponse {
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)
}
}
#[cfg(test)]
mod tests {
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::str::FromStr;
use rustls::KeyLogFile;
use tokio::net::TcpStream as TokioTcpStream;
use tokio::runtime::Runtime;
use crate::iocompat::AsyncIoTokioAsStd;
use crate::op::{Message, Query, ResponseCode};
use crate::rr::{Name, RData, RecordType};
use crate::xfer::{DnsRequestOptions, FirstAnswer};
use super::*;
#[test]
fn test_https_google() {
let google = SocketAddr::from(([8, 8, 8, 8], 443));
let mut request = Message::new();
let query = Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::A);
request.add_query(query);
let request = DnsRequest::new(request, DnsRequestOptions::default());
let mut client_config = client_config_tls12_webpki_roots();
client_config.key_log = Arc::new(KeyLogFile::new());
let https_builder = HttpsClientStreamBuilder::with_client_config(Arc::new(client_config));
let connect = https_builder
.build::<AsyncIoTokioAsStd<TokioTcpStream>>(google, "dns.google".to_string());
let runtime = Runtime::new().expect("could not start runtime");
let mut https = runtime.block_on(connect).expect("https connect failed");
let response = runtime
.block_on(https.send_message(request).first_answer())
.expect("send_message failed");
let record = &response.answers()[0];
let addr = record
.data()
.and_then(RData::as_a)
.expect("Expected A record");
assert_eq!(addr, &Ipv4Addr::new(93, 184, 216, 34));
let mut request = Message::new();
let query = Query::query(
Name::from_str("www.example.com.").unwrap(),
RecordType::AAAA,
);
request.add_query(query);
let request = DnsRequest::new(request, DnsRequestOptions::default());
for _ in 0..3 {
let response = runtime
.block_on(https.send_message(request.clone()).first_answer())
.expect("send_message failed");
if response.response_code() == ResponseCode::ServFail {
continue;
}
let record = &response.answers()[0];
let addr = record
.data()
.and_then(RData::as_aaaa)
.expect("invalid response, expected A record");
assert_eq!(
addr,
&Ipv6Addr::new(0x2606, 0x2800, 0x0220, 0x0001, 0x0248, 0x1893, 0x25c8, 0x1946)
);
}
}
#[test]
#[ignore]
fn test_https_cloudflare() {
let cloudflare = SocketAddr::from(([1, 1, 1, 1], 443));
let mut request = Message::new();
let query = Query::query(Name::from_str("www.example.com.").unwrap(), RecordType::A);
request.add_query(query);
let request = DnsRequest::new(request, DnsRequestOptions::default());
let client_config = client_config_tls12_webpki_roots();
let https_builder = HttpsClientStreamBuilder::with_client_config(Arc::new(client_config));
let connect = https_builder.build::<AsyncIoTokioAsStd<TokioTcpStream>>(
cloudflare,
"cloudflare-dns.com".to_string(),
);
let runtime = Runtime::new().expect("could not start runtime");
let mut https = runtime.block_on(connect).expect("https connect failed");
let response = runtime
.block_on(https.send_message(request).first_answer())
.expect("send_message failed");
let record = &response.answers()[0];
let addr = record
.data()
.and_then(RData::as_a)
.expect("invalid response, expected A record");
assert_eq!(addr, &Ipv4Addr::new(93, 184, 216, 34));
let mut request = Message::new();
let query = Query::query(
Name::from_str("www.example.com.").unwrap(),
RecordType::AAAA,
);
request.add_query(query);
let request = DnsRequest::new(request, DnsRequestOptions::default());
let response = runtime
.block_on(https.send_message(request).first_answer())
.expect("send_message failed");
let record = &response.answers()[0];
let addr = record
.data()
.and_then(RData::as_aaaa)
.expect("invalid response, expected A record");
assert_eq!(
addr,
&Ipv6Addr::new(0x2606, 0x2800, 0x0220, 0x0001, 0x0248, 0x1893, 0x25c8, 0x1946)
);
}
fn client_config_tls12_webpki_roots() -> ClientConfig {
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,
)
}));
let mut client_config = ClientConfig::builder()
.with_safe_default_cipher_suites()
.with_safe_default_kx_groups()
.with_protocol_versions(&[&rustls::version::TLS12])
.unwrap()
.with_root_certificates(root_store)
.with_no_client_auth();
client_config.alpn_protocols = vec![ALPN_H2.to_vec()];
client_config
}
}