Skip to main content

hickory_net/xfer/
dns_exchange.rs

1// Copyright 2015-2018 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! This module contains all the types for demuxing DNS oriented streams.
9
10use core::future::Future;
11use core::marker::PhantomData;
12use core::pin::Pin;
13use core::task::{Context, Poll};
14
15use futures_channel::mpsc;
16use futures_util::stream::{Peekable, Stream, StreamExt};
17use tracing::debug;
18
19use crate::error::NetError;
20use crate::proto::op::{DnsRequest, DnsResponse};
21use crate::runtime::RuntimeProvider;
22use crate::runtime::Time;
23use crate::xfer::dns_handle::DnsHandle;
24use crate::xfer::{
25    BufDnsRequestStreamHandle, DEFAULT_STREAM_BUFFER_SIZE, DnsRequestSender, DnsResponseReceiver,
26    OneshotDnsRequest,
27};
28
29/// This is a generic Exchange implemented over multiplexed DNS connection providers.
30///
31/// The underlying `DnsRequestSender` is expected to multiplex any I/O connections.
32/// DnsExchange assumes that the underlying stream is responsible for this.
33#[must_use = "futures do nothing unless polled"]
34pub struct DnsExchange<P> {
35    sender: BufDnsRequestStreamHandle<P>,
36}
37
38impl<P: RuntimeProvider> DnsExchange<P> {
39    /// Wraps a [`DnsRequestSender`] in a buffered, cloneable [`DnsHandle`].
40    ///
41    /// Returns a `DnsExchange` handle and a background future that must be spawned
42    /// to drive I/O. The handle can be cloned and shared across tasks; requests are
43    /// buffered in an internal channel and forwarded to the underlying stream by the
44    /// background task.
45    ///
46    /// # Arguments
47    ///
48    /// * `stream` - Any [`DnsRequestSender`] (e.g.,
49    ///   [`UdpClientStream`][crate::udp::UdpClientStream],
50    ///   [`TcpClientStream`][crate::tcp::TcpClientStream])
51    pub fn from_stream<S: DnsRequestSender>(
52        stream: S,
53    ) -> (Self, DnsExchangeBackground<S, P::Timer>) {
54        let (sender, outbound_messages) = mpsc::channel(DEFAULT_STREAM_BUFFER_SIZE);
55        (
56            Self {
57                sender: BufDnsRequestStreamHandle {
58                    sender,
59                    _phantom: PhantomData,
60                },
61            },
62            DnsExchangeBackground {
63                io_stream: stream,
64                outbound_messages: outbound_messages.peekable(),
65                marker: PhantomData,
66            },
67        )
68    }
69}
70
71impl<P: Clone> Clone for DnsExchange<P> {
72    fn clone(&self) -> Self {
73        Self {
74            sender: self.sender.clone(),
75        }
76    }
77}
78
79impl<P: RuntimeProvider> DnsHandle for DnsExchange<P> {
80    type Response = DnsExchangeSend<P>;
81    type Runtime = P;
82
83    fn send(&self, request: DnsRequest) -> Self::Response {
84        DnsExchangeSend {
85            result: self.sender.send(request),
86            _sender: self.sender.clone(), // TODO: this shouldn't be necessary, currently the presence of Senders is what allows the background to track current users, it generally is dropped right after send, this makes sure that there is at least one active after send
87        }
88    }
89}
90
91/// A Stream that will resolve to Responses after sending the request
92#[must_use = "futures do nothing unless polled"]
93pub struct DnsExchangeSend<P> {
94    result: DnsResponseReceiver,
95    _sender: BufDnsRequestStreamHandle<P>,
96}
97
98impl<P: Unpin> Stream for DnsExchangeSend<P> {
99    type Item = Result<DnsResponse, NetError>;
100
101    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
102        // as long as there is no result, poll the exchange
103        self.result.poll_next_unpin(cx)
104    }
105}
106
107/// This background future is responsible for driving all network operations for the DNS protocol.
108///
109/// It must be spawned before any DNS messages are sent.
110#[must_use = "futures do nothing unless polled"]
111pub struct DnsExchangeBackground<S, TE> {
112    io_stream: S,
113    outbound_messages: Peekable<mpsc::Receiver<OneshotDnsRequest>>,
114    marker: PhantomData<TE>,
115}
116
117impl<S, TE> DnsExchangeBackground<S, TE> {
118    fn pollable_split(&mut self) -> (&mut S, &mut Peekable<mpsc::Receiver<OneshotDnsRequest>>) {
119        (&mut self.io_stream, &mut self.outbound_messages)
120    }
121}
122
123impl<S: DnsRequestSender, TE: Time> Future for DnsExchangeBackground<S, TE> {
124    type Output = ();
125
126    #[allow(clippy::unused_unit)]
127    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
128        let (io_stream, outbound_messages) = self.pollable_split();
129        let mut io_stream = Pin::new(io_stream);
130        let mut outbound_messages = Pin::new(outbound_messages);
131
132        // this will not accept incoming data while there is data to send
133        //  makes this self throttling.
134        loop {
135            // poll the underlying stream, to drive it...
136            match io_stream.as_mut().poll_next(cx) {
137                // The stream is ready
138                Poll::Ready(Some(Ok(()))) => (),
139                Poll::Pending => {
140                    if io_stream.is_shutdown() {
141                        // the io_stream is in a shutdown state, we are only waiting for final results...
142                        return Poll::Pending;
143                    }
144
145                    // NotReady and not shutdown, see if there are more messages to send
146                    ()
147                } // underlying stream is complete.
148                Poll::Ready(None) => {
149                    debug!("io_stream is done, shutting down");
150                    return Poll::Ready(());
151                }
152                Poll::Ready(Some(Err(error))) => {
153                    debug!(
154                        %error,
155                        "io_stream hit an error, shutting down"
156                    );
157
158                    return Poll::Ready(());
159                }
160            }
161
162            // then see if there is more to send
163            match outbound_messages.as_mut().poll_next(cx) {
164                // already handled above, here to make sure the poll() pops the next message
165                Poll::Ready(Some(dns_request)) => {
166                    // if there is no peer, this connection should die...
167                    let (dns_request, serial_response): (DnsRequest, _) = dns_request.into_parts();
168
169                    // Try to forward the `DnsResponseStream` to the requesting task. If we fail,
170                    // it must be because the requesting task has gone away / is no longer
171                    // interested. In that case, we can just log a warning, but there's no need
172                    // to take any more serious measures (such as shutting down this task).
173                    match serial_response.send_response(io_stream.send_message(dns_request)) {
174                        Ok(()) => (),
175                        Err(_) => {
176                            debug!("failed to associate send_message response to the sender");
177                        }
178                    }
179                }
180                // On not ready, this is our time to return...
181                Poll::Pending => return Poll::Pending,
182                Poll::Ready(None) => {
183                    // if there is nothing that can use this connection to send messages, then this is done...
184                    io_stream.shutdown();
185
186                    // now we'll await the stream to shutdown... see io_stream poll above
187                }
188            }
189
190            // else we loop to poll on the outbound_messages
191        }
192    }
193}