1#![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#[non_exhaustive]
33#[derive(Error, Clone, Debug)]
34pub enum NetError {
35 #[error("resource too busy")]
41 Busy,
42
43 #[error("connection closed before a response was received")]
45 ConnectionClosed,
46
47 #[cfg(any(feature = "__https", feature = "__h3"))]
49 #[error("header decode error: {0}")]
50 Decode(Arc<ToStrError>),
51
52 #[error("DNS error: {0}")]
54 Dns(#[from] DnsError),
55
56 #[cfg(any(feature = "__https", feature = "__h3"))]
58 #[error("HTTP error {status}: {body}")]
59 Http {
60 status: StatusCode,
62 body: String,
64 },
65
66 #[error("H2 error: {0}")]
68 #[cfg(feature = "__https")]
69 H2(Arc<h2::Error>),
70
71 #[error("H3 error: {0}")]
73 #[cfg(feature = "__h3")]
74 H3(Arc<h3::error::StreamError>),
75
76 #[cfg(any(feature = "__https", feature = "__h3"))]
78 #[error("invalid content type: {0}")]
79 InvalidContentType(String),
80
81 #[error("{0}")]
83 Message(&'static str),
84
85 #[error("{0}")]
87 Msg(String),
88
89 #[error("unable to parse number: {0}")]
91 ParseInt(#[from] ParseIntError),
92
93 #[error("no connections available")]
95 NoConnections,
96
97 #[error("protocol error: {0}")]
99 Proto(#[from] ProtoError),
100
101 #[error("io error: {0}")]
104 Io(Arc<io::Error>),
105
106 #[cfg(any(feature = "__https", feature = "__h3"))]
108 #[error("request too large")]
109 RequestTooLarge,
110
111 #[error("request timed out")]
113 Timeout,
114
115 #[cfg(feature = "__quic")]
117 #[error("error creating quic connection: {0}")]
118 QuinnConnect(#[from] quinn::ConnectError),
119
120 #[cfg(feature = "__quic")]
122 #[error("error with quic connection: {0}")]
123 QuinnConnection(#[from] quinn::ConnectionError),
124
125 #[cfg(feature = "__quic")]
127 #[error("error writing to quic connection: {0}")]
128 QuinnWriteError(#[from] quinn::WriteError),
129
130 #[cfg(feature = "__quic")]
132 #[error("error writing to quic read: {0}")]
133 QuinnReadError(#[from] quinn::ReadExactError),
134
135 #[cfg(feature = "__quic")]
137 #[error("referenced a closed QUIC stream: {0}")]
138 QuinnStreamError(#[from] quinn::ClosedStream),
139
140 #[cfg(feature = "__quic")]
142 #[error("error constructing quic configuration: {0}")]
143 QuinnConfigError(#[from] quinn::ConfigError),
144
145 #[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 #[cfg(feature = "__quic")]
152 #[error("an unknown quic stream was used")]
153 QuinnUnknownStreamError,
154
155 #[cfg(feature = "__quic")]
157 #[error("quic messages should always be 0, got: {0}")]
158 QuicMessageIdNot0(u16),
159
160 #[cfg(feature = "__tls")]
162 #[error("rustls construction error: {0}")]
163 RustlsError(#[from] rustls::Error),
164
165 #[error("case of query name in response did not match")]
168 QueryCaseMismatch,
169
170 #[error("foreign class record in response: {record_name} {record_class} {record_type}")]
172 ForeignClassRecord {
173 record_name: Name,
175 record_class: DNSClass,
177 record_type: RecordType,
179 },
180
181 #[error("response was truncated; TCP already tried or no other transport available")]
183 Truncated,
184}
185
186impl NetError {
187 #[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 #[inline]
201 pub fn is_no_records_found(&self) -> bool {
202 matches!(self, Self::Dns(DnsError::NoRecordsFound { .. }))
203 }
204
205 pub fn is_transport_error(&self) -> bool {
211 match self {
212 Self::Busy => false,
214 Self::ConnectionClosed => true,
215
216 #[cfg(any(feature = "__https", feature = "__h3"))]
218 Self::Decode(_) => false,
219
220 Self::Dns(_) => false,
222 Self::ForeignClassRecord { .. } => false,
223 Self::QueryCaseMismatch => false,
224 Self::Truncated => false,
225
226 #[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 Self::Msg(_) => false,
240 Self::Message(_) => false,
241 Self::NoConnections => true,
242
243 Self::ParseInt(_) => false,
245
246 Self::Proto(_) => false,
249
250 #[cfg(feature = "__quic")]
252 Self::QuicMessageIdNot0(_) => true,
253
254 #[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 #[cfg(any(feature = "__https", feature = "__h3"))]
274 Self::RequestTooLarge => false,
275
276 #[cfg(feature = "__tls")]
278 Self::RustlsError(_) => true,
279
280 Self::Timeout => true,
281 }
282 }
283
284 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 #[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 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 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 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#[derive(Clone, Debug, Error)]
480#[non_exhaustive]
481pub enum DnsError {
482 #[error("error response: {0}")]
484 ResponseCode(ResponseCode),
485 #[error("no records found for {:?}", .0.query)]
487 NoRecordsFound(NoRecords),
488 #[cfg(feature = "__dnssec")]
490 #[non_exhaustive]
491 #[error("DNSSEC Negative Record Response for {query}, {proof}")]
492 Nsec {
493 query: Box<Query>,
495 response: Box<DnsResponse>,
497 proof: Proof,
499 },
500 #[error("DNSSEC validation failed")]
502 DnssecBogus,
503}
504
505impl DnsError {
506 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 code @ NXDomain |
532 code @ NoError
534 if !response.contains_answer() && !response.truncation => {
535 let soa = response.soa().as_ref().map(RecordRef::to_owned);
538
539 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 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#[derive(Clone, Debug)]
623#[non_exhaustive]
624pub struct NoRecords {
625 pub query: Box<Query>,
627 pub soa: Option<Box<Record<SOA>>>,
629 pub ns: Option<Arc<[ForwardNSData]>>,
632 pub negative_ttl: Option<u32>,
635 pub response_code: ResponseCode,
638 pub authorities: Option<Arc<[Record]>>,
640}
641
642impl NoRecords {
643 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#[derive(Clone, Debug)]
658pub struct ForwardNSData {
659 pub ns: Record,
661 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 assert!(NetError::from(h2::Error::from(h2::Reason::REFUSED_STREAM)).is_connection_closed());
697 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}