Skip to main content

hickory_net/xfer/
dns_multiplexer.rs

1// Copyright 2015-2023 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//! `DnsMultiplexer` and associated types implement the state machines for sending DNS messages while using the underlying streams.
9
10use core::{
11    pin::Pin,
12    task::{Context, Poll},
13    time::Duration,
14};
15use std::collections::{HashMap, hash_map::Entry};
16use std::io;
17
18use futures_channel::mpsc;
19use futures_util::{
20    FutureExt,
21    future::BoxFuture,
22    stream::{Stream, StreamExt},
23};
24use rand::RngExt;
25use tracing::debug;
26
27use super::{
28    BufDnsStreamHandle, DnsClientStream, DnsRequestSender, DnsResponseStream, ignore_send,
29};
30use crate::proto::op::{DnsRequest, DnsResponse, SerialMessage};
31#[cfg(feature = "__dnssec")]
32use crate::proto::rr::{TSigVerifier, TSigner};
33use crate::{DnsStreamHandle, error::NetError, runtime::Time};
34
35struct ActiveRequest {
36    // the completion is the channel for a response to the original request
37    completion: mpsc::Sender<Result<DnsResponse, NetError>>,
38    request_id: u16,
39    timeout: BoxFuture<'static, ()>,
40    #[cfg(feature = "__dnssec")]
41    verifier: Option<TSigVerifier>,
42}
43
44impl ActiveRequest {
45    fn new(
46        completion: mpsc::Sender<Result<DnsResponse, NetError>>,
47        request_id: u16,
48        timeout: BoxFuture<'static, ()>,
49        #[cfg(feature = "__dnssec")] verifier: Option<TSigVerifier>,
50    ) -> Self {
51        Self {
52            completion,
53            request_id,
54            // request,
55            timeout,
56            #[cfg(feature = "__dnssec")]
57            verifier,
58        }
59    }
60
61    /// polls the timeout and converts the error
62    fn poll_timeout(&mut self, cx: &mut Context<'_>) -> Poll<()> {
63        self.timeout.poll_unpin(cx)
64    }
65
66    /// Returns true of the other side canceled the request
67    fn is_canceled(&self) -> bool {
68        self.completion.is_closed()
69    }
70
71    /// the request id of the message that was sent
72    fn request_id(&self) -> u16 {
73        self.request_id
74    }
75
76    /// Sends an error
77    fn complete_with_error(mut self, error: NetError) {
78        ignore_send(self.completion.try_send(Err(error)));
79    }
80}
81
82/// A DNS Client implemented over futures-rs.
83///
84/// This Client is generic and capable of wrapping UDP, TCP, and other underlying DNS protocol
85///  implementations. This should be used for underlying protocols that do not natively support
86///  multiplexed sessions.
87#[must_use = "futures do nothing unless polled"]
88pub struct DnsMultiplexer<S> {
89    stream: S,
90    timeout_duration: Duration,
91    stream_handle: BufDnsStreamHandle,
92    active_requests: HashMap<u16, ActiveRequest>,
93    max_active_requests: usize,
94    #[cfg(feature = "__dnssec")]
95    signer: Option<TSigner>,
96    is_shutdown: bool,
97}
98
99impl<S: DnsClientStream> DnsMultiplexer<S> {
100    /// Spawns a new DnsMultiplexer Stream.
101    ///
102    /// This uses a default timeout of 5 seconds for all requests unless changed with
103    /// [`Self::with_timeout()`]. At most 32 in-flight requests are allowed unless
104    /// changed with [`Self::with_max_active_requests()`].
105    ///
106    /// # Arguments
107    ///
108    /// * `stream` - A stream of bytes that can be used to send/receive DNS messages
109    ///   (see TcpClientStream or UdpClientStream)
110    /// * `stream_handle` - The handle for the `stream` on which bytes can be sent/received.
111    pub fn new(stream: S, stream_handle: BufDnsStreamHandle) -> Self {
112        Self {
113            stream,
114            timeout_duration: Duration::from_secs(5),
115            stream_handle,
116            active_requests: HashMap::default(),
117            max_active_requests: 32,
118            #[cfg(feature = "__dnssec")]
119            signer: None,
120            is_shutdown: false,
121        }
122    }
123
124    /// Change the default timeout of the DnsMultiplexer stream.
125    pub fn with_timeout(mut self, timeout: Duration) -> Self {
126        self.timeout_duration = timeout;
127        self
128    }
129
130    /// Set the maximum number of active (in-flight) requests.
131    ///
132    /// This limits how many DNS queries can be simultaneously pending on this
133    /// multiplexed connection. When the limit is reached, new requests will
134    /// return [`NetError::Busy`].
135    pub fn with_max_active_requests(mut self, max: usize) -> Self {
136        self.max_active_requests = max;
137        self
138    }
139
140    /// Specify an optional signer to TSIG authenticate requests.
141    #[cfg(feature = "__dnssec")]
142    pub fn with_signer(mut self, signer: TSigner) -> Self {
143        self.signer = Some(signer);
144        self
145    }
146
147    /// loop over active_requests and remove cancelled requests
148    ///  this should free up space if we already had 4096 active requests
149    fn drop_cancelled(&mut self, cx: &mut Context<'_>) {
150        let mut canceled = HashMap::<u16, NetError>::new();
151        for (&id, active_req) in &mut self.active_requests {
152            if active_req.is_canceled() {
153                canceled.insert(id, NetError::from("requestor canceled"));
154            }
155
156            // check for timeouts...
157            match active_req.poll_timeout(cx) {
158                Poll::Ready(()) => {
159                    debug!("request timed out: {}", id);
160                    canceled.insert(id, NetError::Timeout);
161                }
162                Poll::Pending => (),
163            }
164        }
165
166        // drop all the canceled requests
167        for (id, error) in canceled {
168            if let Some(active_request) = self.active_requests.remove(&id) {
169                // complete the request, it's failed...
170                active_request.complete_with_error(error);
171            }
172        }
173    }
174
175    /// creates random query_id, validates against all active queries
176    fn next_random_query_id(&self) -> Result<u16, NetError> {
177        let mut rand = rand::rng();
178
179        for _ in 0..100 {
180            let id: u16 = rand.random(); // the range is [0 ... u16::max]
181
182            if !self.active_requests.contains_key(&id) {
183                return Ok(id);
184            }
185        }
186
187        Err(NetError::from(
188            "id space exhausted, consider filing an issue",
189        ))
190    }
191
192    /// Closes all outstanding completes with a closed stream error
193    fn stream_closed_close_all(&mut self, error: NetError) {
194        debug!(%error, addr = %self.stream.name_server_addr());
195        for (_, active_request) in self.active_requests.drain() {
196            // complete the request, it's failed...
197            active_request.complete_with_error(error.clone());
198        }
199    }
200}
201
202impl<S: DnsClientStream> DnsRequestSender for DnsMultiplexer<S> {
203    fn send_message(&mut self, request: DnsRequest) -> DnsResponseStream {
204        if self.is_shutdown {
205            panic!("can not send messages after stream is shutdown")
206        }
207
208        if self.active_requests.len() >= self.max_active_requests {
209            return NetError::Busy.into();
210        }
211
212        let query_id = match self.next_random_query_id() {
213            Ok(id) => id,
214            Err(e) => return e.into(),
215        };
216
217        let (mut request, _) = request.into_parts();
218        request.metadata.id = query_id;
219
220        #[cfg(feature = "__dnssec")]
221        let mut verifier = None;
222        #[cfg(feature = "__dnssec")]
223        if let Some(signer) = &self.signer {
224            if signer.should_sign_message(&request) {
225                match request.finalize(signer, S::Time::current_time()) {
226                    Ok(answer_verifier) => verifier = answer_verifier,
227                    Err(e) => {
228                        debug!("could not sign message: {}", e);
229                        return NetError::from(e).into();
230                    }
231                }
232            }
233        }
234
235        // store a Timeout for this message before sending
236        let timeout = S::Time::delay_for(self.timeout_duration);
237
238        let (complete, receiver) = mpsc::channel(QUERY_RESPONSE_BUFFER_SIZE);
239
240        // send the message
241        let active_request = ActiveRequest::new(
242            complete,
243            request.id,
244            timeout,
245            #[cfg(feature = "__dnssec")]
246            verifier,
247        );
248
249        match request.to_vec() {
250            Ok(buffer) => {
251                debug!(id = %active_request.request_id(), "sending message");
252                let serial_message = SerialMessage::new(buffer, self.stream.name_server_addr());
253
254                debug!(
255                    "final message: {}",
256                    serial_message
257                        .to_message()
258                        .expect("bizarre we just made this message")
259                );
260
261                // add to the map -after- the client send b/c we don't want to put it in the map if
262                //  we ended up returning an error from the send.
263                match self.stream_handle.send(serial_message) {
264                    Ok(()) => self
265                        .active_requests
266                        .insert(active_request.request_id(), active_request),
267                    Err(err) => return err.into(),
268                };
269            }
270            Err(error) => {
271                debug!(
272                    id = %active_request.request_id(),
273                    %error,
274                    "error message"
275                );
276                // complete with the error, don't add to the map of active requests
277                return NetError::from(error).into();
278            }
279        }
280
281        receiver.into()
282    }
283
284    fn shutdown(&mut self) {
285        self.is_shutdown = true;
286    }
287
288    fn is_shutdown(&self) -> bool {
289        self.is_shutdown
290    }
291}
292
293impl<S: DnsClientStream> Stream for DnsMultiplexer<S> {
294    type Item = Result<(), NetError>;
295
296    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
297        // Always drop the cancelled queries first
298        self.drop_cancelled(cx);
299
300        if self.is_shutdown && self.active_requests.is_empty() {
301            debug!("stream is done: {}", self.stream.name_server_addr());
302            return Poll::Ready(None);
303        }
304
305        // Collect all inbound requests, max 100 at a time for QoS
306        //   by having a max we will guarantee that the client can't be DOSed in this loop
307        // TODO: make the QoS configurable
308        let mut messages_received = 0;
309        for i in 0..QOS_MAX_RECEIVE_MSGS {
310            match self.stream.poll_next_unpin(cx) {
311                Poll::Ready(Some(Ok(buffer))) => {
312                    messages_received = i + 1;
313
314                    //   deserialize or log decode_error
315                    match DnsResponse::from_buffer(buffer.into_parts().0) {
316                        Ok(response) => match self.active_requests.entry(response.id) {
317                            Entry::Occupied(mut request_entry) => {
318                                // send the response, complete the request...
319                                let active_request = request_entry.get_mut();
320                                #[cfg(feature = "__dnssec")]
321                                if let Some(verifier) = &mut active_request.verifier {
322                                    ignore_send(
323                                        active_request.completion.try_send(
324                                            verifier
325                                                .verify(response.as_buffer())
326                                                .map_err(NetError::from),
327                                        ),
328                                    );
329                                } else {
330                                    ignore_send(active_request.completion.try_send(Ok(response)));
331                                }
332                                #[cfg(not(feature = "__dnssec"))]
333                                ignore_send(active_request.completion.try_send(Ok(response)));
334                            }
335                            Entry::Vacant(..) => debug!("unexpected request_id: {}", response.id),
336                        },
337                        // TODO: return src address for diagnostics
338                        Err(error) => debug!(%error, "error decoding message"),
339                    }
340                }
341                Poll::Ready(err) => {
342                    let err = match err {
343                        Some(Err(e)) => e,
344                        None => NetError::from(io::Error::new(
345                            io::ErrorKind::UnexpectedEof,
346                            "stream closed",
347                        )),
348                        _ => unreachable!(),
349                    };
350
351                    self.stream_closed_close_all(err);
352                    self.is_shutdown = true;
353                    return Poll::Ready(None);
354                }
355                Poll::Pending => break,
356            }
357        }
358
359        // If still active, then if the qos (for _ in 0..100 loop) limit
360        // was hit then "yield". This'll make sure that the future is
361        // woken up immediately on the next turn of the event loop.
362        if messages_received == QOS_MAX_RECEIVE_MSGS {
363            // FIXME: this was a task::current().notify(); is this right?
364            cx.waker().wake_by_ref();
365        }
366
367        // Finally, return not ready to keep the 'driver task' alive.
368        Poll::Pending
369    }
370}
371
372const QOS_MAX_RECEIVE_MSGS: usize = 100; // max number of messages to receive from the UDP socket
373
374/// Buffer size for per-query response channels.
375///
376/// Each outgoing DNS query gets its own channel to receive responses. Standard
377/// DNS queries receive exactly one response so a small buffer is sufficient.
378const QUERY_RESPONSE_BUFFER_SIZE: usize = 8;
379
380#[cfg(test)]
381mod test {
382    use core::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
383    use core::sync::atomic::{AtomicUsize, Ordering};
384    use core::task::Waker;
385    use std::sync::Arc;
386    use std::task::Wake;
387
388    use futures_util::{
389        future::{self, BoxFuture},
390        ready,
391        stream::TryStreamExt,
392    };
393    use test_support::subscribe;
394
395    use super::*;
396    use crate::proto::op::{DnsRequestOptions, Message, Query};
397    use crate::proto::rr::rdata::{NS, SOA};
398    use crate::proto::rr::{DNSClass, Name, RData, Record, RecordType};
399    use crate::proto::serialize::binary::BinEncodable;
400    use crate::xfer::{DnsClientStream, StreamReceiver};
401
402    struct MockClientStream {
403        messages: Vec<Message>,
404        addr: SocketAddr,
405        id: Option<u16>,
406        receiver: Option<StreamReceiver>,
407    }
408
409    impl MockClientStream {
410        fn new(
411            mut messages: Vec<Message>,
412            addr: SocketAddr,
413        ) -> BoxFuture<'static, Result<Self, NetError>> {
414            messages.reverse(); // so we can pop() and get messages in order
415            Box::pin(future::ok(Self {
416                messages,
417                addr,
418                id: None,
419                receiver: None,
420            }))
421        }
422    }
423
424    impl Stream for MockClientStream {
425        type Item = Result<SerialMessage, NetError>;
426
427        fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
428            let id = if let Some(id) = self.id {
429                id
430            } else {
431                let serial = ready!(
432                    self.receiver
433                        .as_mut()
434                        .expect("should only be polled after receiver has been set")
435                        .poll_next_unpin(cx)
436                );
437                let message = serial.unwrap().to_message().unwrap();
438                self.id = Some(message.id);
439                message.id
440            };
441
442            if let Some(mut message) = self.messages.pop() {
443                message.metadata.id = id;
444                Poll::Ready(Some(Ok(SerialMessage::new(
445                    message.to_bytes().unwrap(),
446                    self.addr,
447                ))))
448            } else {
449                Poll::Pending
450            }
451        }
452    }
453
454    impl DnsClientStream for MockClientStream {
455        type Time = crate::runtime::TokioTime;
456
457        fn name_server_addr(&self) -> SocketAddr {
458            self.addr
459        }
460    }
461
462    async fn get_mocked_multiplexer(
463        mock_response: Vec<Message>,
464    ) -> DnsMultiplexer<MockClientStream> {
465        let addr = SocketAddr::from(([127, 0, 0, 1], 1234));
466        let mock_response = MockClientStream::new(mock_response, addr).await.unwrap();
467        let (handler, receiver) = BufDnsStreamHandle::new(addr);
468        let mut multiplexer =
469            DnsMultiplexer::new(mock_response, handler).with_timeout(Duration::from_millis(100));
470
471        multiplexer.stream.receiver = Some(receiver); // so it can get the correct request id
472
473        multiplexer
474    }
475
476    fn a_query_answer() -> (DnsRequest, Vec<Message>) {
477        let name = Name::from_ascii("www.example.com.").unwrap();
478
479        let mut request = Message::query();
480        request.metadata.recursion_desired = true;
481        request.add_query({
482            let mut q = Query::query(name.clone(), RecordType::A);
483            q.set_query_class(DNSClass::IN);
484            q
485        });
486
487        let mut response = request.clone().into_response();
488        response.add_answer(Record::from_rdata(
489            name,
490            86400,
491            RData::A(Ipv4Addr::new(93, 184, 215, 14).into()),
492        ));
493        (
494            DnsRequest::new(request, DnsRequestOptions::default()),
495            vec![response],
496        )
497    }
498
499    fn axfr_query() -> Message {
500        let name = Name::from_ascii("example.com.").unwrap();
501
502        let mut msg = Message::query();
503        msg.metadata.recursion_desired = true;
504        msg.add_query({
505            let mut query = Query::query(name, RecordType::AXFR);
506            query.set_query_class(DNSClass::IN);
507            query
508        });
509        msg
510    }
511
512    fn axfr_response() -> Vec<Record> {
513        let origin = Name::from_ascii("example.com.").unwrap();
514        let soa = Record::from_rdata(
515            origin.clone(),
516            3600,
517            RData::SOA(SOA::new(
518                Name::parse("sns.dns.icann.org.", None).unwrap(),
519                Name::parse("noc.dns.icann.org.", None).unwrap(),
520                2015082403,
521                7200,
522                3600,
523                1209600,
524                3600,
525            )),
526        );
527
528        vec![
529            soa.clone(),
530            Record::from_rdata(
531                origin.clone(),
532                86400,
533                RData::NS(NS(Name::parse("a.iana-servers.net.", None).unwrap())),
534            ),
535            Record::from_rdata(
536                origin.clone(),
537                86400,
538                RData::NS(NS(Name::parse("b.iana-servers.net.", None).unwrap())),
539            ),
540            Record::from_rdata(
541                origin.clone(),
542                86400,
543                RData::A(Ipv4Addr::new(93, 184, 215, 14).into()),
544            ),
545            Record::from_rdata(
546                origin,
547                86400,
548                RData::AAAA(
549                    Ipv6Addr::new(
550                        0x2606, 0x2800, 0x21f, 0xcb07, 0x6820, 0x80da, 0xaf6b, 0x8b2c,
551                    )
552                    .into(),
553                ),
554            ),
555            soa,
556        ]
557    }
558
559    fn axfr_query_answer() -> (DnsRequest, Vec<Message>) {
560        let msg = axfr_query();
561
562        let mut response = msg.clone().into_response();
563        response.insert_answers(axfr_response());
564        (
565            DnsRequest::new(msg, DnsRequestOptions::default()),
566            vec![response],
567        )
568    }
569
570    fn axfr_query_answer_multi() -> (DnsRequest, Vec<Message>) {
571        let base = axfr_query();
572
573        let query = base.clone();
574        let mut rr = axfr_response();
575        let rr2 = rr.split_off(3);
576        let mut msg1 = base.clone().into_response();
577        msg1.insert_answers(rr);
578        let mut msg2 = base.into_response();
579        msg2.insert_answers(rr2);
580        (
581            DnsRequest::new(query, DnsRequestOptions::default()),
582            vec![msg1, msg2],
583        )
584    }
585
586    /// How many times one poll of a multiplexer with `ready` messages waiting asks to be woken.
587    async fn wakes_after_one_poll(ready: usize) -> usize {
588        struct Count(AtomicUsize);
589        impl Wake for Count {
590            fn wake(self: Arc<Self>) {
591                self.0.fetch_add(1, Ordering::Relaxed);
592            }
593        }
594
595        let (query, answer) = a_query_answer();
596        let answers = answer.into_iter().cycle().take(ready).collect();
597        let mut multiplexer = get_mocked_multiplexer(answers).await;
598        let _response = multiplexer.send_message(query);
599
600        let count = Arc::new(Count(AtomicUsize::new(0)));
601        let waker = Waker::from(count.clone());
602        let mut cx = Context::from_waker(&waker);
603        assert!(multiplexer.poll_next_unpin(&mut cx).is_pending());
604        count.0.load(Ordering::Relaxed)
605    }
606
607    /// Messages left past the per-poll limit are still ready on the socket, so nothing else would
608    /// wake the task for them.
609    #[tokio::test]
610    async fn test_multiplexer_wakes_itself_past_the_qos_limit() {
611        subscribe();
612        assert_eq!(wakes_after_one_poll(QOS_MAX_RECEIVE_MSGS + 1).await, 1);
613    }
614
615    /// With the stream drained, the stream's own waker is enough: waking here would spin.
616    #[tokio::test]
617    async fn test_multiplexer_does_not_wake_itself_below_the_qos_limit() {
618        subscribe();
619        assert_eq!(wakes_after_one_poll(QOS_MAX_RECEIVE_MSGS - 1).await, 0);
620    }
621
622    #[tokio::test]
623    async fn test_multiplexer_a() {
624        subscribe();
625        let (query, answer) = a_query_answer();
626        let mut multiplexer = get_mocked_multiplexer(answer).await;
627        let response = multiplexer.send_message(query);
628        let response = tokio::select! {
629            _ = multiplexer.next() => {
630                // polling multiplexer to make it run
631                panic!("should never end")
632            },
633            r = response.try_collect::<Vec<_>>() => r.unwrap(),
634        };
635        assert_eq!(response.len(), 1);
636    }
637
638    #[tokio::test]
639    async fn test_multiplexer_axfr() {
640        subscribe();
641        let (query, answer) = axfr_query_answer();
642        let mut multiplexer = get_mocked_multiplexer(answer).await;
643        let response = multiplexer.send_message(query);
644        let response = tokio::select! {
645            _ = multiplexer.next() => {
646                // polling multiplexer to make it run
647                panic!("should never end")
648            },
649            r = response.try_collect::<Vec<_>>() => r.unwrap(),
650        };
651        assert_eq!(response.len(), 1);
652        assert_eq!(response[0].answers.len(), axfr_response().len());
653    }
654
655    #[tokio::test]
656    async fn test_multiplexer_axfr_multi() {
657        subscribe();
658        let (query, answer) = axfr_query_answer_multi();
659        let mut multiplexer = get_mocked_multiplexer(answer).await;
660        let response = multiplexer.send_message(query);
661        let response = tokio::select! {
662            _ = multiplexer.next() => {
663                // polling multiplexer to make it run
664                panic!("should never end")
665            },
666            r = response.try_collect::<Vec<_>>() => r.unwrap(),
667        };
668        assert_eq!(response.len(), 2);
669        assert_eq!(
670            response.iter().map(|m| m.answers.len()).sum::<usize>(),
671            axfr_response().len()
672        );
673    }
674}