Skip to main content

hickory_net/
error.rs

1// Copyright 2015-2020 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//! Error types for the crate
9
10#![deny(missing_docs)]
11
12use core::num::ParseIntError;
13use std::io;
14use std::sync::Arc;
15
16#[cfg(any(feature = "__https", feature = "__h3"))]
17use http::StatusCode;
18#[cfg(any(feature = "__https", feature = "__h3"))]
19use http::header::ToStrError;
20use thiserror::Error;
21use tracing::debug;
22
23use crate::proto::ProtoError;
24#[cfg(feature = "__dnssec")]
25use crate::proto::dnssec::Proof;
26use crate::proto::op::{DnsResponse, Query, ResponseCode};
27use crate::proto::rr::RData;
28use crate::proto::rr::{DNSClass, Name, Record, RecordRef, RecordType, rdata::SOA};
29use crate::proto::serialize::binary::DecodeError;
30
31/// The error type for network protocol errors (UDP, TCP, QUIC, H2, H3)
32#[non_exhaustive]
33#[derive(Error, Clone, Debug)]
34pub enum NetError {
35    /// The underlying resource is too busy
36    ///
37    /// This is a signal that an internal resource is too busy. The intended action should be tried
38    /// again, ideally after waiting for a little while for the situation to improve. Alternatively,
39    /// the action could be tried on another resource (for example, in a name server pool).
40    #[error("resource too busy")]
41    Busy,
42
43    /// The connection carrying a request went away before it could be answered.
44    #[error("connection closed before a response was received")]
45    ConnectionClosed,
46
47    /// Unable to decode HTTP header value to string
48    #[cfg(any(feature = "__https", feature = "__h3"))]
49    #[error("header decode error: {0}")]
50    Decode(Arc<ToStrError>),
51
52    /// Semantic DNS errors
53    #[error("DNS error: {0}")]
54    Dns(#[from] DnsError),
55
56    /// An HTTP error occurred
57    #[cfg(any(feature = "__https", feature = "__h3"))]
58    #[error("HTTP error {status}: {body}")]
59    Http {
60        /// The HTTP status code of the response.
61        status: StatusCode,
62        /// The response body.
63        body: String,
64    },
65
66    /// An HTTP/2 related error
67    #[error("H2 error: {0}")]
68    #[cfg(feature = "__https")]
69    H2(Arc<h2::Error>),
70
71    /// An HTTP/3 related error
72    #[error("H3 error: {0}")]
73    #[cfg(feature = "__h3")]
74    H3(Arc<h3::error::StreamError>),
75
76    /// An Invalid HTTP content type header
77    #[cfg(any(feature = "__https", feature = "__h3"))]
78    #[error("invalid content type: {0}")]
79    InvalidContentType(String),
80
81    /// An error with an arbitrary message
82    #[error("{0}")]
83    Message(&'static str),
84
85    /// An error with an arbitrary message, stored as String
86    #[error("{0}")]
87    Msg(String),
88
89    /// Unable to parse header value as number
90    #[error("unable to parse number: {0}")]
91    ParseInt(#[from] ParseIntError),
92
93    /// No connections available
94    #[error("no connections available")]
95    NoConnections,
96
97    /// Protocol error from higher layers
98    #[error("protocol error: {0}")]
99    Proto(#[from] ProtoError),
100
101    // foreign
102    /// An error got returned from IO
103    #[error("io error: {0}")]
104    Io(Arc<io::Error>),
105
106    /// A request was too large
107    #[cfg(any(feature = "__https", feature = "__h3"))]
108    #[error("request too large")]
109    RequestTooLarge,
110
111    /// A request timed out
112    #[error("request timed out")]
113    Timeout,
114
115    /// A Quinn (Quic) connection error occurred
116    #[cfg(feature = "__quic")]
117    #[error("error creating quic connection: {0}")]
118    QuinnConnect(#[from] quinn::ConnectError),
119
120    /// A Quinn (QUIC) connection error occurred
121    #[cfg(feature = "__quic")]
122    #[error("error with quic connection: {0}")]
123    QuinnConnection(#[from] quinn::ConnectionError),
124
125    /// A Quinn (QUIC) write error occurred
126    #[cfg(feature = "__quic")]
127    #[error("error writing to quic connection: {0}")]
128    QuinnWriteError(#[from] quinn::WriteError),
129
130    /// A Quinn (QUIC) read error occurred
131    #[cfg(feature = "__quic")]
132    #[error("error writing to quic read: {0}")]
133    QuinnReadError(#[from] quinn::ReadExactError),
134
135    /// A Quinn (QUIC) stream error occurred
136    #[cfg(feature = "__quic")]
137    #[error("referenced a closed QUIC stream: {0}")]
138    QuinnStreamError(#[from] quinn::ClosedStream),
139
140    /// A Quinn (QUIC) configuration error occurred
141    #[cfg(feature = "__quic")]
142    #[error("error constructing quic configuration: {0}")]
143    QuinnConfigError(#[from] quinn::ConfigError),
144
145    /// QUIC TLS config must include an AES-128-GCM cipher suite
146    #[cfg(feature = "__quic")]
147    #[error("QUIC TLS config must include an AES-128-GCM cipher suite")]
148    QuinnTlsConfigError(#[from] quinn::crypto::rustls::NoInitialCipherSuite),
149
150    /// Unknown QUIC stream used
151    #[cfg(feature = "__quic")]
152    #[error("an unknown quic stream was used")]
153    QuinnUnknownStreamError,
154
155    /// A quic message id should always be 0
156    #[cfg(feature = "__quic")]
157    #[error("quic messages should always be 0, got: {0}")]
158    QuicMessageIdNot0(u16),
159
160    /// A Rustls error occurred
161    #[cfg(feature = "__tls")]
162    #[error("rustls construction error: {0}")]
163    RustlsError(#[from] rustls::Error),
164
165    /// Case randomization is enabled, and a server did not echo a query name back with the same
166    /// case.
167    #[error("case of query name in response did not match")]
168    QueryCaseMismatch,
169
170    /// An upstream response contained a record whose class did not match the IN query class.
171    #[error("foreign class record in response: {record_name} {record_class} {record_type}")]
172    ForeignClassRecord {
173        /// The name of the offending record.
174        record_name: Name,
175        /// The class of the offending record.
176        record_class: DNSClass,
177        /// The type of the offending record.
178        record_type: RecordType,
179    },
180
181    /// Received a truncated response
182    #[error("response was truncated; TCP already tried or no other transport available")]
183    Truncated,
184}
185
186impl NetError {
187    /// Returns true if the domain does not exist
188    #[inline]
189    pub fn is_nx_domain(&self) -> bool {
190        matches!(
191            self,
192            Self::Dns(DnsError::NoRecordsFound(NoRecords {
193                response_code: ResponseCode::NXDomain,
194                ..
195            }))
196        )
197    }
198
199    /// Returns true if the error represents NoRecordsFound
200    #[inline]
201    pub fn is_no_records_found(&self) -> bool {
202        matches!(self, Self::Dns(DnsError::NoRecordsFound { .. }))
203    }
204
205    /// Returns true if the error indicates a failure at the transport layer.
206    ///
207    /// The match is exhaustive so a new variant cannot silently change how a
208    /// name server is penalized. Errors from the query, the response contents,
209    /// or local state are not transport errors.
210    pub fn is_transport_error(&self) -> bool {
211        match self {
212            // Internal resource pressure, not a server property.
213            Self::Busy => false,
214            Self::ConnectionClosed => true,
215
216            // A response header that does not decode as a string.
217            #[cfg(any(feature = "__https", feature = "__h3"))]
218            Self::Decode(_) => false,
219
220            // A response from the server, whatever its contents.
221            Self::Dns(_) => false,
222            Self::ForeignClassRecord { .. } => false,
223            Self::QueryCaseMismatch => false,
224            Self::Truncated => false,
225
226            // An HTTP/2 or HTTP/3 connection or stream failure.
227            #[cfg(any(feature = "__https", feature = "__h3"))]
228            Self::Http { .. } => true,
229            #[cfg(feature = "__https")]
230            Self::H2(_) => true,
231            #[cfg(feature = "__h3")]
232            Self::H3(_) => true,
233            #[cfg(any(feature = "__https", feature = "__h3"))]
234            Self::InvalidContentType(_) => true,
235
236            Self::Io(_) => true,
237
238            // Local failures that no server choice can avoid.
239            Self::Msg(_) => false,
240            Self::Message(_) => false,
241            Self::NoConnections => true,
242
243            // A response header value that does not parse as a number.
244            Self::ParseInt(_) => false,
245
246            // Usually RDATA our code cannot transform, so the zone contents decide
247            // the failure rather than the server or protocol.
248            Self::Proto(_) => false,
249
250            // A DoQ protocol violation by the server.
251            #[cfg(feature = "__quic")]
252            Self::QuicMessageIdNot0(_) => true,
253
254            // A QUIC configuration or connection failure.
255            #[cfg(feature = "__quic")]
256            Self::QuinnConfigError(_) => true,
257            #[cfg(feature = "__quic")]
258            Self::QuinnConnect(_) => true,
259            #[cfg(feature = "__quic")]
260            Self::QuinnConnection(_) => true,
261            #[cfg(feature = "__quic")]
262            Self::QuinnReadError(_) => true,
263            #[cfg(feature = "__quic")]
264            Self::QuinnStreamError(_) => true,
265            #[cfg(feature = "__quic")]
266            Self::QuinnTlsConfigError(_) => true,
267            #[cfg(feature = "__quic")]
268            Self::QuinnUnknownStreamError => true,
269            #[cfg(feature = "__quic")]
270            Self::QuinnWriteError(_) => true,
271
272            // The server responded; only the body exceeded our size limit.
273            #[cfg(any(feature = "__https", feature = "__h3"))]
274            Self::RequestTooLarge => false,
275
276            // A TLS handshake failure.
277            #[cfg(feature = "__tls")]
278            Self::RustlsError(_) => true,
279
280            Self::Timeout => true,
281        }
282    }
283
284    /// Returns true for a transport-level connection error: the connection was
285    /// closed, reset, or refused, as opposed to a timeout or a server-side (DNS)
286    /// error.
287    pub fn is_connection_closed(&self) -> bool {
288        match self {
289            #[cfg(feature = "__https")]
290            Self::H2(err) => {
291                err.is_io() || err.is_go_away() || err.reason() == Some(h2::Reason::REFUSED_STREAM)
292            }
293            #[cfg(feature = "__h3")]
294            Self::H3(err) => err.is_h3_no_error(),
295            Self::ConnectionClosed => true,
296            Self::Io(err) => matches!(
297                err.kind(),
298                io::ErrorKind::ConnectionReset
299                    | io::ErrorKind::ConnectionAborted
300                    | io::ErrorKind::BrokenPipe
301                    | io::ErrorKind::NotConnected
302                    | io::ErrorKind::UnexpectedEof
303            ),
304            #[cfg(feature = "__quic")]
305            Self::QuinnConnection(err) => matches!(
306                err,
307                quinn::ConnectionError::ConnectionClosed(_)
308                    | quinn::ConnectionError::ApplicationClosed(_)
309                    | quinn::ConnectionError::Reset
310            ),
311            _ => false,
312        }
313    }
314
315    /// Returns the SOA record, if the error contains one
316    #[inline]
317    pub fn into_soa(self) -> Option<Box<Record<SOA>>> {
318        match self {
319            Self::Dns(DnsError::NoRecordsFound(NoRecords { soa, .. })) => soa,
320            _ => None,
321        }
322    }
323
324    /// Returns a representative string of the error for use as a metrics label.
325    pub fn as_metrics_label(&self) -> &'static str {
326        match self {
327            Self::Busy => "busy",
328            Self::ConnectionClosed => "connection_closed",
329            #[cfg(any(feature = "__https", feature = "__h3"))]
330            Self::Decode(_) => "http_header_decode",
331            Self::Dns(dns_err) => dns_err.as_metrics_label(),
332            #[cfg(any(feature = "__https", feature = "__h3"))]
333            Self::Http { .. } => "http",
334            #[cfg(feature = "__https")]
335            Self::H2(_) => "http2",
336            #[cfg(feature = "__h3")]
337            Self::H3(_) => "http3",
338            #[cfg(any(feature = "__https", feature = "__h3"))]
339            Self::InvalidContentType(_) => "invalid_content_type",
340            Self::ParseInt(_) => "parse_header_value",
341            Self::NoConnections => "no_connections",
342            Self::Proto(_) => "proto",
343            Self::Io(e) => {
344                use std::io::ErrorKind::*;
345                match e.kind() {
346                    NotFound => "io_not_found",
347                    PermissionDenied => "io_permission_denied",
348                    ConnectionRefused => "io_connection_refused",
349                    ConnectionReset => "io_connection_reset",
350                    HostUnreachable => "io_host_unreachable",
351                    NetworkUnreachable => "io_network_unreachable",
352                    ConnectionAborted => "io_connection_aborted",
353                    NotConnected => "io_not_connected",
354                    AddrInUse => "io_addr_in_use",
355                    AddrNotAvailable => "io_addr_not_available",
356                    NetworkDown => "io_network_down",
357                    BrokenPipe => "io_broken_pipe",
358                    AlreadyExists => "io_already_exists",
359                    WouldBlock => "io_would_block",
360                    InvalidInput => "io_invalid_input",
361                    InvalidData => "io_invalid_data",
362                    TimedOut => "io_timed_out",
363                    WriteZero => "io_write_zero",
364                    QuotaExceeded => "io_quota_exceeded",
365                    ResourceBusy => "io_resource_busy",
366                    Deadlock => "io_deadlock",
367                    Interrupted => "io_interrupted",
368                    Unsupported => "io_unsupported",
369                    OutOfMemory => "io_out_of_memory",
370                    Other => "io_other",
371
372                    // It's highly unlikely that any of these would actually be returned.
373                    NotADirectory => "io_not_a_directory",
374                    IsADirectory => "io_is_a_directory",
375                    DirectoryNotEmpty => "io_directory_not_empty",
376                    ReadOnlyFilesystem => "io_read_only_filesystem",
377                    StaleNetworkFileHandle => "io_stale_network_file_handle",
378                    StorageFull => "io_storage_full",
379                    NotSeekable => "io_not_seekable",
380                    FileTooLarge => "io_file_too_large",
381                    ExecutableFileBusy => "io_executable_file_busy",
382                    CrossesDevices => "io_crosses_devices",
383                    TooManyLinks => "io_too_many_links",
384                    InvalidFilename => "io_invalid_filename",
385                    ArgumentListTooLong => "io_argument_list_too_long",
386                    UnexpectedEof => "io_unexpected_eof",
387
388                    _ => "io_unknown",
389                }
390            }
391            #[cfg(any(feature = "__https", feature = "__h3"))]
392            Self::RequestTooLarge => "request_too_large",
393            Self::Timeout => "timeout",
394            #[cfg(feature = "__quic")]
395            Self::QuinnConnect(_) => "quic_connect",
396            #[cfg(feature = "__quic")]
397            Self::QuinnConnection(_) => "quic_connection",
398            #[cfg(feature = "__quic")]
399            Self::QuinnWriteError(_) => "quic_write",
400            #[cfg(feature = "__quic")]
401            Self::QuinnReadError(_) => "quic_read",
402            #[cfg(feature = "__quic")]
403            Self::QuinnStreamError(_) => "quic_stream",
404            #[cfg(feature = "__quic")]
405            Self::QuinnConfigError(_) => "quic_config",
406            #[cfg(feature = "__quic")]
407            Self::QuinnTlsConfigError(_) => "quic_tls_config_error",
408            #[cfg(feature = "__quic")]
409            Self::QuinnUnknownStreamError => "quic_unknown_stream",
410            #[cfg(feature = "__quic")]
411            Self::QuicMessageIdNot0(_) => "quic_message_id_not_0",
412            #[cfg(feature = "__tls")]
413            Self::RustlsError(_) => "tls",
414            Self::QueryCaseMismatch => "query_case_mismatch",
415            Self::ForeignClassRecord { .. } => "foreign_class_record",
416            Self::Truncated => "truncated",
417
418            // Don't report these because the format is arbitrary, and in the case of Msg, dynamic.
419            Self::Message(_) | Self::Msg(_) => "message",
420        }
421    }
422}
423
424impl From<NoRecords> for NetError {
425    fn from(no_records: NoRecords) -> Self {
426        Self::Dns(DnsError::NoRecordsFound(no_records))
427    }
428}
429
430impl From<DecodeError> for NetError {
431    fn from(e: DecodeError) -> Self {
432        Self::Proto(e.into())
433    }
434}
435
436#[cfg(feature = "__h3")]
437impl From<h3::error::StreamError> for NetError {
438    fn from(e: h3::error::StreamError) -> Self {
439        Self::H3(Arc::new(e))
440    }
441}
442
443#[cfg(feature = "__https")]
444impl From<h2::Error> for NetError {
445    fn from(e: h2::Error) -> Self {
446        Self::H2(Arc::new(e))
447    }
448}
449
450#[cfg(any(feature = "__https", feature = "__h3"))]
451impl From<ToStrError> for NetError {
452    fn from(e: ToStrError) -> Self {
453        Self::Decode(Arc::new(e))
454    }
455}
456
457impl From<io::Error> for NetError {
458    fn from(e: io::Error) -> Self {
459        match e.kind() {
460            io::ErrorKind::TimedOut => Self::Timeout,
461            _ => Self::Io(Arc::new(e)),
462        }
463    }
464}
465
466impl From<String> for NetError {
467    fn from(msg: String) -> Self {
468        Self::Msg(msg)
469    }
470}
471
472impl From<&'static str> for NetError {
473    fn from(msg: &'static str) -> Self {
474        Self::Message(msg)
475    }
476}
477
478/// Semantic DNS errors
479#[derive(Clone, Debug, Error)]
480#[non_exhaustive]
481pub enum DnsError {
482    /// Received an error response code from the server
483    #[error("error response: {0}")]
484    ResponseCode(ResponseCode),
485    /// No records were found for a query
486    #[error("no records found for {:?}", .0.query)]
487    NoRecordsFound(NoRecords),
488    /// No Records and there is a corresponding DNSSEC Proof for NSEC
489    #[cfg(feature = "__dnssec")]
490    #[non_exhaustive]
491    #[error("DNSSEC Negative Record Response for {query}, {proof}")]
492    Nsec {
493        /// Query for which the NSEC was returned
494        query: Box<Query>,
495        /// Response for which the NSEC was returned
496        response: Box<DnsResponse>,
497        /// DNSSEC proof of the record
498        proof: Proof,
499    },
500    /// DNSSEC validation failure
501    #[error("DNSSEC validation failed")]
502    DnssecBogus,
503}
504
505impl DnsError {
506    /// A conversion to determine if the response is an error
507    pub fn from_response(response: DnsResponse) -> Result<DnsResponse, Self> {
508        use ResponseCode::*;
509        debug!("response: {}", *response);
510
511        match response.response_code {
512                Refused => Err(Self::ResponseCode(Refused)),
513                code @ ServFail
514                | code @ FormErr
515                | code @ NotImp
516                | code @ YXDomain
517                | code @ YXRRSet
518                | code @ NXRRSet
519                | code @ NotAuth
520                | code @ NotZone
521                | code @ BADVERS
522                | code @ BADSIG
523                | code @ BADKEY
524                | code @ BADTIME
525                | code @ BADMODE
526                | code @ BADNAME
527                | code @ BADALG
528                | code @ BADTRUNC
529                | code @ BADCOOKIE => Err(Self::ResponseCode(code)),
530                // Some NXDOMAIN responses contain CNAME referrals, that will not be an error
531                code @ NXDomain |
532                // No answers are available, CNAME referrals are not failures
533                code @ NoError
534                if !response.contains_answer() && !response.truncation => {
535                    // TODO: if authoritative, this is cacheable, store a TTL (currently that requires time, need a "now" here)
536                    // let valid_until = if response.authoritative() { now + response.negative_ttl() };
537                    let soa = response.soa().as_ref().map(RecordRef::to_owned);
538
539                    // Collect any referral nameservers and associated glue records
540                    let mut referral_name_servers = vec![];
541                    for ns in response.authorities.iter().filter(|ns| ns.record_type() == RecordType::NS) {
542                        let glue = response
543                            .additionals
544                            .iter()
545                            .filter_map(|record| {
546                                if let RData::NS(ns_data) = &ns.data {
547                                    if record.name == **ns_data && matches!(&record.data, RData::A(_) | RData::AAAA(_)) {
548                                        return Some(Record::to_owned(record));
549                                    }
550                                }
551
552                                None
553                            })
554                            .collect::<Vec<Record>>();
555                        referral_name_servers.push(ForwardNSData { ns: Record::to_owned(ns), glue: glue.into() })
556                    }
557
558                    let option_ns = if !referral_name_servers.is_empty() {
559                        Some(referral_name_servers.into())
560                    } else {
561                        None
562                    };
563
564                    let authorities = if !response.authorities.is_empty() {
565                        Some(response.authorities.to_owned().into())
566                    } else {
567                        None
568                    };
569
570                    let negative_ttl = response.negative_ttl();
571                    let query = response.into_message().queries.drain(..).next().unwrap_or_default();
572
573                    Err(Self::NoRecordsFound(NoRecords {
574                        query: Box::new(query),
575                        soa: soa.map(Box::new),
576                        ns: option_ns,
577                        negative_ttl,
578                        response_code: code,
579                        authorities,
580                    }))
581                }
582                NXDomain
583                | NoError
584                | Unknown(_) => Ok(response),
585            }
586    }
587
588    /// Returns the DNS error as a representative string for use as a metrics label.
589    pub fn as_metrics_label(&self) -> &'static str {
590        use hickory_proto::op::ResponseCode::*;
591        match self {
592            Self::ResponseCode(NoError) => "dns_response_code_noerror",
593            Self::ResponseCode(FormErr) => "dns_response_code_formerror",
594            Self::ResponseCode(ServFail) => "dns_response_code_servfail",
595            Self::ResponseCode(NXDomain) => "dns_response_code_nxdomain",
596            Self::ResponseCode(NotImp) => "dns_response_code_notimp",
597            Self::ResponseCode(Refused) => "dns_response_code_refused",
598            Self::ResponseCode(YXDomain) => "dns_response_code_yxdomain",
599            Self::ResponseCode(YXRRSet) => "dns_response_code_yxrrset",
600            Self::ResponseCode(NXRRSet) => "dns_response_code_nxrrset",
601            Self::ResponseCode(NotAuth) => "dns_response_code_notauth",
602            Self::ResponseCode(NotZone) => "dns_response_code_notzone",
603            Self::ResponseCode(BADVERS) => "dns_response_code_badvers",
604            Self::ResponseCode(BADSIG) => "dns_response_code_badsig",
605            Self::ResponseCode(BADKEY) => "dns_response_code_badkey",
606            Self::ResponseCode(BADTIME) => "dns_response_code_badtime",
607            Self::ResponseCode(BADMODE) => "dns_response_code_badmode",
608            Self::ResponseCode(BADNAME) => "dns_response_code_badname",
609            Self::ResponseCode(BADALG) => "dns_response_code_badalg",
610            Self::ResponseCode(BADTRUNC) => "dns_response_code_badtrunc",
611            Self::ResponseCode(BADCOOKIE) => "dns_response_code_badcookie",
612            Self::ResponseCode(Unknown(_)) => "dns_response_code_unknown",
613            Self::NoRecordsFound(_) => "dns_no_records",
614            #[cfg(feature = "__dnssec")]
615            Self::Nsec { .. } => "dns_nsec",
616            Self::DnssecBogus => "dns_dnssec_bogus",
617        }
618    }
619}
620
621/// Response where no records were found
622#[derive(Clone, Debug)]
623#[non_exhaustive]
624pub struct NoRecords {
625    /// The query for which no records were found.
626    pub query: Box<Query>,
627    /// If an SOA is present, then this is an authoritative response or a referral to another nameserver, see the negative_type field.
628    pub soa: Option<Box<Record<SOA>>>,
629    /// Nameservers may be present in addition to or in lieu of an SOA for a referral
630    /// The tuple struct layout is vec[(Nameserver, [vec of glue records])]
631    pub ns: Option<Arc<[ForwardNSData]>>,
632    /// negative ttl, as determined from DnsResponse::negative_ttl
633    ///  this will only be present if the SOA was also present.
634    pub negative_ttl: Option<u32>,
635    /// ResponseCode, if `NXDOMAIN`, the domain does not exist (and no other types).
636    ///   If `NoError`, then the domain exists but there exist either other types at the same label, or subzones of that label.
637    pub response_code: ResponseCode,
638    /// Authority records from the query. These are important to preserve for DNSSEC validation.
639    pub authorities: Option<Arc<[Record]>>,
640}
641
642impl NoRecords {
643    /// Construct a new [`NoRecords`] from a query and a response code
644    pub fn new(query: impl Into<Box<Query>>, response_code: ResponseCode) -> Self {
645        Self {
646            query: query.into(),
647            soa: None,
648            ns: None,
649            negative_ttl: None,
650            response_code,
651            authorities: None,
652        }
653    }
654}
655
656/// Data needed to process a NS-record-based referral.
657#[derive(Clone, Debug)]
658pub struct ForwardNSData {
659    /// The referant NS record
660    pub ns: Record,
661    /// Any glue records associated with the referant NS record.
662    pub glue: Arc<[Record]>,
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668
669    #[test]
670    fn is_connection_closed_io_kinds() {
671        for kind in [
672            io::ErrorKind::ConnectionReset,
673            io::ErrorKind::ConnectionAborted,
674            io::ErrorKind::BrokenPipe,
675            io::ErrorKind::NotConnected,
676            io::ErrorKind::UnexpectedEof,
677        ] {
678            assert!(
679                NetError::from(io::Error::from(kind)).is_connection_closed(),
680                "{kind:?}"
681            );
682        }
683
684        assert!(
685            !NetError::from(io::Error::from(io::ErrorKind::PermissionDenied))
686                .is_connection_closed()
687        );
688        assert!(!NetError::Timeout.is_connection_closed());
689        assert!(!NetError::Message("server error").is_connection_closed());
690    }
691
692    #[cfg(feature = "__https")]
693    #[test]
694    fn is_connection_closed_h2() {
695        // REFUSED_STREAM: the server never processed the request, so it's safe to retry.
696        assert!(NetError::from(h2::Error::from(h2::Reason::REFUSED_STREAM)).is_connection_closed());
697        // A protocol error mid-exchange is not a clean connection-closed signal.
698        assert!(
699            !NetError::from(h2::Error::from(h2::Reason::INTERNAL_ERROR)).is_connection_closed()
700        );
701    }
702
703    #[cfg(feature = "__quic")]
704    #[test]
705    fn is_connection_closed_quic_excludes_timeout() {
706        assert!(NetError::QuinnConnection(quinn::ConnectionError::Reset).is_connection_closed());
707        assert!(
708            !NetError::QuinnConnection(quinn::ConnectionError::TimedOut).is_connection_closed()
709        );
710    }
711}