1use core::fmt::Display;
8use core::fmt::{self, Debug};
9use core::future::Future;
10use core::marker::PhantomData;
11use core::net::SocketAddr;
12use core::pin::Pin;
13use core::task::{Context, Poll};
14use core::time::Duration;
15use std::io;
16
17use futures_channel::mpsc;
18use futures_channel::oneshot;
19use futures_util::future::BoxFuture;
20use futures_util::ready;
21use futures_util::stream::{Fuse, Peekable};
22use futures_util::stream::{Stream, StreamExt};
23#[cfg(feature = "serde")]
24use serde::{Deserialize, Serialize};
25use tracing::{debug, warn};
26
27use crate::error::NetError;
28use crate::proto::ProtoError;
29use crate::proto::op::{DnsRequest, DnsResponse, SerialMessage};
30use crate::runtime::{RuntimeProvider, Time};
31
32mod dns_exchange;
33pub use dns_exchange::{DnsExchange, DnsExchangeBackground, DnsExchangeSend};
34
35pub mod dns_handle;
36pub use dns_handle::{DnsHandle, DnsStreamHandle};
37
38pub mod dns_multiplexer;
39pub use dns_multiplexer::DnsMultiplexer;
40
41pub mod retry_dns_handle;
42pub use retry_dns_handle::RetryDnsHandle;
43
44pub struct DnsResponseStream {
46 inner: DnsResponseStreamInner,
47 done: bool,
48}
49
50impl DnsResponseStream {
51 fn new(inner: DnsResponseStreamInner) -> Self {
52 Self { inner, done: false }
53 }
54}
55
56impl Stream for DnsResponseStream {
57 type Item = Result<DnsResponse, NetError>;
58
59 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
60 use DnsResponseStreamInner::*;
61
62 if self.done {
64 return Poll::Ready(None);
65 }
66
67 let Self { inner, done } = self.get_mut();
69
70 let result = match inner {
71 Timeout(fut) => {
72 let x = match ready!(fut.as_mut().poll(cx)) {
73 Ok(x) => x,
74 Err(e) => Err(e.into()),
75 };
76 *done = true;
77 x
78 }
79 Receiver(fut) => match ready!(Pin::new(fut).poll_next(cx)) {
80 Some(Ok(x)) => Ok(x),
81 Some(Err(e)) => Err(e),
82 None => return Poll::Ready(None),
83 },
84 Error(err) => {
85 *done = true;
86 Err(err.take().expect("cannot poll after complete"))
87 }
88 Boxed(fut) => {
89 let x = ready!(fut.as_mut().poll(cx));
90 *done = true;
91 x
92 }
93 };
94
95 match result {
96 Err(NetError::Timeout) => Poll::Ready(None),
97 r => Poll::Ready(Some(r)),
98 }
99 }
100}
101
102impl From<TimeoutFuture> for DnsResponseStream {
103 fn from(f: TimeoutFuture) -> Self {
104 Self::new(DnsResponseStreamInner::Timeout(f))
105 }
106}
107
108impl From<mpsc::Receiver<Result<DnsResponse, NetError>>> for DnsResponseStream {
109 fn from(receiver: mpsc::Receiver<Result<DnsResponse, NetError>>) -> Self {
110 Self::new(DnsResponseStreamInner::Receiver(receiver))
111 }
112}
113
114impl From<NetError> for DnsResponseStream {
115 fn from(e: NetError) -> Self {
116 Self::new(DnsResponseStreamInner::Error(Some(e)))
117 }
118}
119
120impl<F> From<Pin<Box<F>>> for DnsResponseStream
121where
122 F: Future<Output = Result<DnsResponse, NetError>> + Send + 'static,
123{
124 fn from(f: Pin<Box<F>>) -> Self {
125 Self::new(DnsResponseStreamInner::Boxed(f))
126 }
127}
128
129enum DnsResponseStreamInner {
130 Timeout(TimeoutFuture),
131 Receiver(mpsc::Receiver<Result<DnsResponse, NetError>>),
132 Error(Option<NetError>),
133 Boxed(BoxFuture<'static, Result<DnsResponse, NetError>>),
134}
135
136type TimeoutFuture = BoxFuture<'static, Result<Result<DnsResponse, NetError>, io::Error>>;
137
138fn ignore_send<M, T>(result: Result<M, mpsc::TrySendError<T>>) {
140 if let Err(error) = result {
141 if error.is_disconnected() {
142 debug!("ignoring send error on disconnected stream");
143 return;
144 }
145
146 warn!("error notifying wait, possible future leak: {:?}", error);
147 }
148}
149
150pub trait DnsClientStream:
152 Stream<Item = Result<SerialMessage, NetError>> + Unpin + Send + 'static
153{
154 type Time: Time;
156
157 fn name_server_addr(&self) -> SocketAddr;
159}
160
161pub type StreamReceiver = Peekable<Fuse<mpsc::Receiver<SerialMessage>>>;
163
164#[derive(Clone)]
170pub struct BufDnsStreamHandle {
171 remote_addr: SocketAddr,
172 sender: mpsc::Sender<SerialMessage>,
173}
174
175impl BufDnsStreamHandle {
176 pub fn new(remote_addr: SocketAddr) -> (Self, StreamReceiver) {
182 Self::with_buffer_size(remote_addr, DEFAULT_STREAM_BUFFER_SIZE)
183 }
184
185 pub fn with_buffer_size(remote_addr: SocketAddr, buffer_size: usize) -> (Self, StreamReceiver) {
195 let (sender, receiver) = mpsc::channel(buffer_size);
196 let receiver = receiver.fuse().peekable();
197
198 let this = Self {
199 remote_addr,
200 sender,
201 };
202
203 (this, receiver)
204 }
205
206 pub fn with_remote_addr(&self, remote_addr: SocketAddr) -> Self {
210 Self {
211 remote_addr,
212 sender: self.sender.clone(),
213 }
214 }
215}
216
217impl DnsStreamHandle for BufDnsStreamHandle {
218 fn send(&mut self, buffer: SerialMessage) -> Result<(), NetError> {
219 let sender: &mut _ = &mut self.sender;
220 sender
221 .try_send(SerialMessage::new(buffer.into_parts().0, self.remote_addr))
222 .map_err(|e| NetError::from(format!("mpsc::SendError {e}")))
223 }
224}
225
226pub trait DnsRequestSender: Stream<Item = Result<(), NetError>> + Send + Unpin + 'static {
232 fn send_message(&mut self, request: DnsRequest) -> DnsResponseStream;
238
239 fn shutdown(&mut self);
243
244 fn is_shutdown(&self) -> bool;
246}
247
248#[derive(Clone)]
250
251pub struct BufDnsRequestStreamHandle<P> {
252 sender: mpsc::Sender<OneshotDnsRequest>,
253 _phantom: PhantomData<P>,
254}
255
256impl<P: RuntimeProvider> DnsHandle for BufDnsRequestStreamHandle<P> {
257 type Response = DnsResponseReceiver;
258 type Runtime = P;
259
260 fn send(&self, request: DnsRequest) -> Self::Response {
261 debug!(
262 "enqueueing message:{}:{:?}",
263 request.op_code, request.queries
264 );
265
266 let (request, oneshot) = OneshotDnsRequest::oneshot(request);
267 let mut sender = self.sender.clone();
268 let try_send = sender.try_send(request).map_err(|error| {
269 debug!("unable to enqueue message");
270 match error.is_disconnected() {
271 true => NetError::ConnectionClosed,
272 false => NetError::Busy,
273 }
274 });
275
276 match try_send {
277 Ok(val) => val,
278 Err(err) => return DnsResponseReceiver::Err(Some(err)),
279 }
280
281 DnsResponseReceiver::Receiver(oneshot)
282 }
283}
284
285pub struct OneshotDnsRequest {
288 dns_request: DnsRequest,
289 sender_for_response: oneshot::Sender<DnsResponseStream>,
290}
291
292impl OneshotDnsRequest {
293 fn oneshot(dns_request: DnsRequest) -> (Self, oneshot::Receiver<DnsResponseStream>) {
294 let (sender_for_response, receiver) = oneshot::channel();
295
296 (
297 Self {
298 dns_request,
299 sender_for_response,
300 },
301 receiver,
302 )
303 }
304
305 fn is_canceled(&self) -> bool {
307 self.sender_for_response.is_canceled()
308 }
309
310 fn into_parts(self) -> (DnsRequest, OneshotDnsResponse) {
311 (
312 self.dns_request,
313 OneshotDnsResponse(self.sender_for_response),
314 )
315 }
316}
317
318struct OneshotDnsResponse(oneshot::Sender<DnsResponseStream>);
319
320impl OneshotDnsResponse {
321 fn send_response(self, serial_response: DnsResponseStream) -> Result<(), DnsResponseStream> {
322 self.0.send(serial_response)
323 }
324}
325
326pub enum DnsResponseReceiver {
328 Receiver(oneshot::Receiver<DnsResponseStream>),
330 Received(DnsResponseStream),
332 Err(Option<NetError>),
334}
335
336impl Stream for DnsResponseReceiver {
337 type Item = Result<DnsResponse, NetError>;
338
339 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
340 loop {
341 *self = match &mut *self {
342 Self::Receiver(receiver) => {
343 let receiver = Pin::new(receiver);
344 let future = ready!(receiver.poll(cx).map_err(|_| NetError::ConnectionClosed))?;
345 Self::Received(future)
346 }
347 Self::Received(stream) => {
348 return stream.poll_next_unpin(cx);
349 }
350 Self::Err(err) => return Poll::Ready(err.take().map(Err)),
351 };
352 }
353 }
354}
355
356pub trait FirstAnswer<T, E: From<ProtoError>>: Stream<Item = Result<T, E>> + Unpin + Sized {
358 fn first_answer(self) -> FirstAnswerFuture<Self> {
361 FirstAnswerFuture { stream: Some(self) }
362 }
363}
364
365impl<E, S, T> FirstAnswer<T, E> for S
366where
367 S: Stream<Item = Result<T, E>> + Unpin + Sized,
368 E: From<ProtoError>,
369{
370}
371
372#[derive(Debug)]
374#[must_use = "futures do nothing unless you `.await` or poll them"]
375pub struct FirstAnswerFuture<S> {
376 stream: Option<S>,
377}
378
379impl<S: Stream<Item = Result<T, NetError>> + Unpin, T> Future for FirstAnswerFuture<S>
380where
381 S: Stream<Item = Result<T, NetError>> + Unpin + Sized,
382{
383 type Output = S::Item;
384
385 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
386 let s = self
387 .stream
388 .as_mut()
389 .expect("polling FirstAnswerFuture twice");
390 let item = match ready!(s.poll_next_unpin(cx)) {
391 Some(r) => r,
392 None => Err(NetError::Timeout),
393 };
394 self.stream.take();
395 Poll::Ready(item)
396 }
397}
398
399#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
401#[cfg_attr(
402 feature = "serde",
403 derive(Serialize, Deserialize),
404 serde(rename_all = "lowercase")
405)]
406#[non_exhaustive]
407pub enum Protocol {
408 Udp,
410 Tcp,
412 #[cfg(feature = "__tls")]
414 Tls,
415 #[cfg(feature = "__https")]
417 Https,
418 #[cfg(feature = "__quic")]
420 Quic,
421 #[cfg(feature = "__h3")]
423 H3,
424}
425
426impl Protocol {
427 pub fn is_datagram(self) -> bool {
429 matches!(self, Self::Udp)
430 }
431
432 pub fn is_stream(self) -> bool {
434 !self.is_datagram()
435 }
436
437 pub fn is_encrypted(self) -> bool {
439 match self {
440 Self::Udp => false,
441 Self::Tcp => false,
442 #[cfg(feature = "__tls")]
443 Self::Tls => true,
444 #[cfg(feature = "__https")]
445 Self::Https => true,
446 #[cfg(feature = "__quic")]
447 Self::Quic => true,
448 #[cfg(feature = "__h3")]
449 Self::H3 => true,
450 }
451 }
452
453 pub fn as_str(&self) -> &'static str {
455 match self {
456 Self::Udp => "udp",
457 Self::Tcp => "tcp",
458 #[cfg(feature = "__tls")]
459 Self::Tls => "tls",
460 #[cfg(feature = "__https")]
461 Self::Https => "https",
462 #[cfg(feature = "__quic")]
463 Self::Quic => "quic",
464 #[cfg(feature = "__h3")]
465 Self::H3 => "http3",
466 }
467 }
468}
469
470impl Display for Protocol {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 f.write_str(self.as_str())
473 }
474}
475
476#[allow(unused)] pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
478
479const DEFAULT_STREAM_BUFFER_SIZE: usize = 32;
489
490#[cfg(test)]
491mod tests {
492 use futures_util::StreamExt;
493
494 use crate::proto::op::Message;
495 use crate::runtime::TokioRuntimeProvider;
496
497 use super::*;
498
499 #[tokio::test]
500 async fn a_dropped_request_reports_a_closed_connection() {
501 let (sender, receiver) = oneshot::channel();
502 let mut response = DnsResponseReceiver::Receiver(receiver);
503 drop(sender);
504
505 let err = response
506 .next()
507 .await
508 .expect("the receiver yields the failure")
509 .expect_err("a dropped request cannot produce a response");
510 assert!(matches!(&err, NetError::ConnectionClosed));
511 assert!(err.is_connection_closed());
512 }
513
514 #[tokio::test]
515 async fn a_request_sent_to_a_closed_exchange_reports_a_closed_connection() {
516 let (sender, receiver) = mpsc::channel(1);
517 drop(receiver);
518 let handle = BufDnsRequestStreamHandle::<TokioRuntimeProvider> {
519 sender,
520 _phantom: PhantomData,
521 };
522
523 let err = handle
524 .send(DnsRequest::from(Message::query()))
525 .next()
526 .await
527 .expect("the response stream yields the send failure")
528 .expect_err("a closed exchange cannot accept a request");
529 assert!(matches!(err, NetError::ConnectionClosed));
530 }
531}