1//! DNS high level transit implimentations.
2//!
3//! Primarily there are two types in this module of interest, the `DnsMultiplexer` type and the `DnsHandle` type. `DnsMultiplexer` can be thought of as the state machine responsible for sending and receiving DNS messages. `DnsHandle` is the type given to API users of the `trust-dns-proto` library to send messages into the `DnsMultiplexer` for delivery. Finally there is the `DnsRequest` type. This allows for customizations, through `DnsRequestOptions`, to the delivery of messages via a `DnsMultiplexer`.
4//!
5//! TODO: this module needs some serious refactoring and normalization.
67use std::fmt::{Debug, Display};
8use std::net::SocketAddr;
9use std::pin::Pin;
10use std::task::{Context, Poll};
1112use futures_channel::mpsc;
13use futures_channel::oneshot;
14use futures_util::future::Future;
15use futures_util::ready;
16use futures_util::stream::{Fuse, Peekable, Stream, StreamExt};
17use tracing::{debug, warn};
1819use crate::error::*;
20use crate::Time;
2122mod dns_exchange;
23pub mod dns_handle;
24pub mod dns_multiplexer;
25pub mod dns_request;
26pub mod dns_response;
27#[cfg(feature = "dnssec")]
28#[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
29pub mod dnssec_dns_handle;
30pub mod retry_dns_handle;
31mod serial_message;
3233pub use self::dns_exchange::{
34 DnsExchange, DnsExchangeBackground, DnsExchangeConnect, DnsExchangeSend,
35};
36pub use self::dns_handle::{DnsHandle, DnsStreamHandle};
37pub use self::dns_multiplexer::{DnsMultiplexer, DnsMultiplexerConnect};
38pub use self::dns_request::{DnsRequest, DnsRequestOptions};
39pub use self::dns_response::{DnsResponse, DnsResponseStream};
40#[cfg(feature = "dnssec")]
41#[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
42pub use self::dnssec_dns_handle::DnssecDnsHandle;
43pub use self::retry_dns_handle::RetryDnsHandle;
44pub use self::serial_message::SerialMessage;
4546/// Ignores the result of a send operation and logs and ignores errors
47fn ignore_send<M, T>(result: Result<M, mpsc::TrySendError<T>>) {
48if let Err(error) = result {
49if error.is_disconnected() {
50debug!("ignoring send error on disconnected stream");
51return;
52 }
5354warn!("error notifying wait, possible future leak: {:?}", error);
55 }
56}
5758/// A non-multiplexed stream of Serialized DNS messages
59pub trait DnsClientStream:
60 Stream<Item = Result<SerialMessage, ProtoError>> + Display + Send
61{
62/// Time implementation for this impl
63type Time: Time;
6465/// The remote name server address
66fn name_server_addr(&self) -> SocketAddr;
67}
6869/// Receiver handle for peekable fused SerialMessage channel
70pub type StreamReceiver = Peekable<Fuse<mpsc::Receiver<SerialMessage>>>;
7172const CHANNEL_BUFFER_SIZE: usize = 32;
7374/// A buffering stream bound to a `SocketAddr`
75///
76/// This stream handle ensures that all messages sent via this handle have the remote_addr set as the destination for the packet
77#[derive(Clone)]
78pub struct BufDnsStreamHandle {
79 remote_addr: SocketAddr,
80 sender: mpsc::Sender<SerialMessage>,
81}
8283impl BufDnsStreamHandle {
84/// Constructs a new Buffered Stream Handle, used for sending data to the DNS peer.
85 ///
86 /// # Arguments
87 ///
88 /// * `remote_addr` - the address of the remote DNS system (client or server)
89 /// * `sender` - the handle being used to send data to the server
90pub fn new(remote_addr: SocketAddr) -> (Self, StreamReceiver) {
91let (sender, receiver) = mpsc::channel(CHANNEL_BUFFER_SIZE);
92let receiver = receiver.fuse().peekable();
9394let this = Self {
95 remote_addr,
96 sender,
97 };
9899 (this, receiver)
100 }
101102/// Associates a different remote address for any responses.
103 ///
104 /// This is mainly useful in server use cases where the incoming address is only known after receiving a packet.
105pub fn with_remote_addr(&self, remote_addr: SocketAddr) -> Self {
106Self {
107 remote_addr,
108 sender: self.sender.clone(),
109 }
110 }
111}
112113impl DnsStreamHandle for BufDnsStreamHandle {
114fn send(&mut self, buffer: SerialMessage) -> Result<(), ProtoError> {
115let remote_addr: SocketAddr = self.remote_addr;
116let sender: &mut _ = &mut self.sender;
117 sender
118 .try_send(SerialMessage::new(buffer.into_parts().0, remote_addr))
119 .map_err(|e| ProtoError::from(format!("mpsc::SendError {}", e)))
120 }
121}
122123/// Types that implement this are capable of sending a serialized DNS message on a stream
124///
125/// The underlying Stream implementation should yield `Some(())` whenever it is ready to send a message,
126/// NotReady, if it is not ready to send a message, and `Err` or `None` in the case that the stream is
127/// done, and should be shutdown.
128pub trait DnsRequestSender: Stream<Item = Result<(), ProtoError>> + Send + Unpin + 'static {
129/// Send a message, and return a stream of response
130 ///
131 /// # Return
132 ///
133 /// A stream which will resolve to SerialMessage responses
134fn send_message(&mut self, message: DnsRequest) -> DnsResponseStream;
135136/// Allows the upstream user to inform the underling stream that it should shutdown.
137 ///
138 /// After this is called, the next time `poll` is called on the stream it would be correct to return `Poll::Ready(Ok(()))`. This is not required though, if there are say outstanding requests that are not yet complete, then it would be correct to first wait for those results.
139fn shutdown(&mut self);
140141/// Returns true if the stream has been shutdown with `shutdown`
142fn is_shutdown(&self) -> bool;
143}
144145/// Used for associating a name_server to a DnsRequestStreamHandle
146#[derive(Clone)]
147pub struct BufDnsRequestStreamHandle {
148 sender: mpsc::Sender<OneshotDnsRequest>,
149}
150151macro_rules! try_oneshot {
152 ($expr:expr) => {{
153use std::result::Result;
154155match $expr {
156 Result::Ok(val) => val,
157 Result::Err(err) => return DnsResponseReceiver::Err(Some(ProtoError::from(err))),
158 }
159 }};
160 ($expr:expr,) => {
161$expr?
162};
163}
164165impl DnsHandle for BufDnsRequestStreamHandle {
166type Response = DnsResponseReceiver;
167type Error = ProtoError;
168169fn send<R: Into<DnsRequest>>(&mut self, request: R) -> Self::Response {
170let request: DnsRequest = request.into();
171debug!(
172"enqueueing message:{}:{:?}",
173 request.op_code(),
174 request.queries()
175 );
176177let (request, oneshot) = OneshotDnsRequest::oneshot(request);
178try_oneshot!(self.sender.try_send(request).map_err(|_| {
179debug!("unable to enqueue message");
180 ProtoError::from(ProtoErrorKind::Busy)
181 }));
182183 DnsResponseReceiver::Receiver(oneshot)
184 }
185}
186187// TODO: this future should return the origin message in the response on errors
188/// A OneshotDnsRequest creates a channel for a response to message
189pub struct OneshotDnsRequest {
190 dns_request: DnsRequest,
191 sender_for_response: oneshot::Sender<DnsResponseStream>,
192}
193194impl OneshotDnsRequest {
195fn oneshot(dns_request: DnsRequest) -> (Self, oneshot::Receiver<DnsResponseStream>) {
196let (sender_for_response, receiver) = oneshot::channel();
197198 (
199Self {
200 dns_request,
201 sender_for_response,
202 },
203 receiver,
204 )
205 }
206207fn into_parts(self) -> (DnsRequest, OneshotDnsResponse) {
208 (
209self.dns_request,
210 OneshotDnsResponse(self.sender_for_response),
211 )
212 }
213}
214215struct OneshotDnsResponse(oneshot::Sender<DnsResponseStream>);
216217impl OneshotDnsResponse {
218fn send_response(self, serial_response: DnsResponseStream) -> Result<(), DnsResponseStream> {
219self.0.send(serial_response)
220 }
221}
222223/// A Stream that wraps a oneshot::Receiver<Stream> and resolves to items in the inner Stream
224pub enum DnsResponseReceiver {
225/// The receiver
226Receiver(oneshot::Receiver<DnsResponseStream>),
227/// The stream once received
228Received(DnsResponseStream),
229/// Error during the send operation
230Err(Option<ProtoError>),
231}
232233impl Stream for DnsResponseReceiver {
234type Item = Result<DnsResponse, ProtoError>;
235236fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
237loop {
238*self = match *self.as_mut() {
239Self::Receiver(ref mut receiver) => {
240let receiver = Pin::new(receiver);
241let future = ready!(receiver
242 .poll(cx)
243 .map_err(|_| ProtoError::from("receiver was canceled")))?;
244Self::Received(future)
245 }
246Self::Received(ref mut stream) => {
247return stream.poll_next_unpin(cx);
248 }
249Self::Err(ref mut err) => return Poll::Ready(err.take().map(Err)),
250 };
251 }
252 }
253}
254255/// Helper trait to convert a Stream of dns response into a Future
256pub trait FirstAnswer<T, E: From<ProtoError>>: Stream<Item = Result<T, E>> + Unpin + Sized {
257/// Convert a Stream of dns response into a Future yielding the first answer,
258 /// discarding others if any.
259fn first_answer(self) -> FirstAnswerFuture<Self> {
260 FirstAnswerFuture { stream: Some(self) }
261 }
262}
263264impl<E, S, T> FirstAnswer<T, E> for S
265where
266S: Stream<Item = Result<T, E>> + Unpin + Sized,
267 E: From<ProtoError>,
268{
269}
270271/// See [FirstAnswer::first_answer]
272#[derive(Debug)]
273#[must_use = "futures do nothing unless you `.await` or poll them"]
274pub struct FirstAnswerFuture<S> {
275 stream: Option<S>,
276}
277278impl<E, S: Stream<Item = Result<T, E>> + Unpin, T> Future for FirstAnswerFuture<S>
279where
280S: Stream<Item = Result<T, E>> + Unpin + Sized,
281 E: From<ProtoError>,
282{
283type Output = S::Item;
284285fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
286let s = self
287.stream
288 .as_mut()
289 .expect("polling FirstAnswerFuture twice");
290let item = match ready!(s.poll_next_unpin(cx)) {
291Some(r) => r,
292None => Err(ProtoError::from(ProtoErrorKind::Timeout).into()),
293 };
294self.stream.take();
295 Poll::Ready(item)
296 }
297}