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                    // Nobody will read the answer, and over TCP it would still be sent.
167                    if dns_request.is_canceled() {
168                        debug!("dropping a request whose requester stopped waiting");
169                        continue;
170                    }
171                    // if there is no peer, this connection should die...
172                    let (dns_request, serial_response): (DnsRequest, _) = dns_request.into_parts();
173
174                    // Try to forward the `DnsResponseStream` to the requesting task. If we fail,
175                    // it must be because the requesting task has gone away / is no longer
176                    // interested. In that case, we can just log a warning, but there's no need
177                    // to take any more serious measures (such as shutting down this task).
178                    match serial_response.send_response(io_stream.send_message(dns_request)) {
179                        Ok(()) => (),
180                        Err(_) => {
181                            debug!("failed to associate send_message response to the sender");
182                        }
183                    }
184                }
185                // On not ready, this is our time to return...
186                Poll::Pending => return Poll::Pending,
187                Poll::Ready(None) => {
188                    // if there is nothing that can use this connection to send messages, then this is done...
189                    io_stream.shutdown();
190
191                    // now we'll await the stream to shutdown... see io_stream poll above
192                }
193            }
194
195            // else we loop to poll on the outbound_messages
196        }
197    }
198}
199
200#[cfg(all(test, feature = "tokio"))]
201mod tests {
202    use std::sync::{Arc, Mutex};
203
204    use futures_util::task::noop_waker;
205
206    use super::*;
207    use crate::proto::op::{DnsRequestOptions, Message, Query};
208    use crate::proto::rr::{Name, RecordType};
209    use crate::runtime::TokioRuntimeProvider;
210    use crate::xfer::DnsResponseStream;
211
212    /// A stream that records the id of every request it is asked to send, as a TCP stream writes
213    /// each one out when asked; each response stream it returns fails at once with a marker error.
214    struct Recording(Arc<Mutex<Vec<u16>>>);
215
216    impl Stream for Recording {
217        type Item = Result<(), NetError>;
218
219        fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
220            Poll::Pending
221        }
222    }
223
224    impl DnsRequestSender for Recording {
225        fn send_message(&mut self, request: DnsRequest) -> DnsResponseStream {
226            self.0.lock().unwrap().push(request.id);
227            NetError::from("recorded").into()
228        }
229
230        fn shutdown(&mut self) {}
231
232        fn is_shutdown(&self) -> bool {
233            false
234        }
235    }
236
237    fn request(id: u16) -> DnsRequest {
238        let mut message = Message::query();
239        message.metadata.id = id;
240        message.add_query(Query::query(
241            Name::from_ascii("www.example.com.").unwrap(),
242            RecordType::A,
243        ));
244        DnsRequest::new(message, DnsRequestOptions::default())
245    }
246
247    #[test]
248    fn a_request_whose_requester_stopped_waiting_is_not_sent() {
249        let sent = Arc::new(Mutex::new(Vec::new()));
250        let (exchange, mut background) =
251            DnsExchange::<TokioRuntimeProvider>::from_stream(Recording(sent.clone()));
252
253        // Queued, then given up on before the background task ran.
254        drop(exchange.send(request(1)));
255        // Queued and still waited for.
256        let mut kept = exchange.send(request(2));
257
258        let waker = noop_waker();
259        let mut cx = Context::from_waker(&waker);
260        assert!(Pin::new(&mut background).poll(&mut cx).is_pending());
261
262        assert_eq!(*sent.lock().unwrap(), vec![2]);
263        // The kept request still gets the stream send_message returned.
264        match Pin::new(&mut kept).poll_next(&mut cx) {
265            Poll::Ready(Some(Err(NetError::Message("recorded")))) => {}
266            other => panic!("the kept request did not get its response stream: {other:?}"),
267        }
268    }
269}