hickory_resolver/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// https://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! Error types for the crate

use std::{fmt, io, sync};

use thiserror::Error;

use crate::proto::{
    rr::{rdata::SOA, Record},
    xfer::retry_dns_handle::RetryableError,
    ProtoError, ProtoErrorKind,
};
#[cfg(feature = "backtrace")]
use crate::proto::{trace, ExtBacktrace};

#[allow(clippy::large_enum_variant)]
/// The error kind for errors that get returned in the crate
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ResolveErrorKind {
    /// An error with an arbitrary message, referenced as &'static str
    #[error("{0}")]
    Message(&'static str),

    /// An error with an arbitrary message, stored as String
    #[error("{0}")]
    Msg(String),

    /// An error got returned by the hickory-proto crate
    #[error("proto error: {0}")]
    Proto(#[from] ProtoError),
}

impl Clone for ResolveErrorKind {
    fn clone(&self) -> Self {
        use self::ResolveErrorKind::*;
        match self {
            Message(msg) => Message(msg),
            Msg(msg) => Msg(msg.clone()),
            // foreign
            Proto(proto) => Self::from(proto.clone()),
        }
    }
}

/// The error type for errors that get returned in the crate
#[derive(Debug, Clone, Error)]
pub struct ResolveError {
    pub(crate) kind: ResolveErrorKind,
    #[cfg(feature = "backtrace")]
    backtrack: Option<ExtBacktrace>,
}

impl ResolveError {
    /// Get the kind of the error
    pub fn kind(&self) -> &ResolveErrorKind {
        &self.kind
    }

    /// Take the kind of the error
    pub fn into_kind(self) -> ResolveErrorKind {
        self.kind
    }

    /// If this is an underlying proto error, return that
    pub fn proto(&self) -> Option<&ProtoError> {
        match &self.kind {
            ResolveErrorKind::Proto(proto) => Some(proto),
            _ => None,
        }
    }

    /// Returns true if the domain does not exist
    pub fn is_nx_domain(&self) -> bool {
        self.proto()
            .map(|proto| proto.is_nx_domain())
            .unwrap_or(false)
    }

    /// Returns true if no records were returned
    pub fn is_no_records_found(&self) -> bool {
        self.proto()
            .map(|proto| proto.is_no_records_found())
            .unwrap_or(false)
    }

    /// Returns the SOA record, if the error contains one
    pub fn into_soa(self) -> Option<Box<Record<SOA>>> {
        match self.kind {
            ResolveErrorKind::Proto(proto) => proto.into_soa(),
            _ => None,
        }
    }
}

impl RetryableError for ResolveError {
    fn should_retry(&self) -> bool {
        match self.kind() {
            ResolveErrorKind::Message(_) | ResolveErrorKind::Msg(_) => false,
            ResolveErrorKind::Proto(proto) => proto.should_retry(),
        }
    }

    fn attempted(&self) -> bool {
        match self.kind() {
            ResolveErrorKind::Proto(e) => e.attempted(),
            _ => true,
        }
    }
}

impl fmt::Display for ResolveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        cfg_if::cfg_if! {
            if #[cfg(feature = "backtrace")] {
                if let Some(backtrace) = &self.backtrack {
                    fmt::Display::fmt(&self.kind, f)?;
                    fmt::Debug::fmt(backtrace, f)
                } else {
                    fmt::Display::fmt(&self.kind, f)
                }
            } else {
                fmt::Display::fmt(&self.kind, f)
            }
        }
    }
}

impl From<ResolveErrorKind> for ResolveError {
    fn from(kind: ResolveErrorKind) -> Self {
        Self {
            kind,
            #[cfg(feature = "backtrace")]
            backtrack: trace!(),
        }
    }
}

impl From<&'static str> for ResolveError {
    fn from(msg: &'static str) -> Self {
        ResolveErrorKind::Message(msg).into()
    }
}

impl TryFrom<ResolveError> for ProtoErrorKind {
    type Error = ResolveError;
    fn try_from(error: ResolveError) -> Result<Self, Self::Error> {
        match error.kind {
            ResolveErrorKind::Proto(p) => Ok(*p.kind),
            _ => Err(error),
        }
    }
}

#[cfg(target_os = "windows")]
#[cfg(feature = "system-config")]
impl From<ipconfig::error::Error> for ResolveError {
    fn from(e: ipconfig::error::Error) -> ResolveError {
        ResolveErrorKind::Msg(format!("failed to read from registry: {}", e)).into()
    }
}

impl From<String> for ResolveError {
    fn from(msg: String) -> Self {
        ResolveErrorKind::Msg(msg).into()
    }
}

impl From<io::Error> for ResolveError {
    fn from(e: io::Error) -> Self {
        ResolveErrorKind::from(ProtoError::from(e)).into()
    }
}

impl From<ProtoError> for ResolveError {
    fn from(e: ProtoError) -> Self {
        ResolveErrorKind::Proto(e).into()
    }
}

impl From<ResolveError> for io::Error {
    fn from(e: ResolveError) -> Self {
        Self::new(io::ErrorKind::Other, e)
    }
}

impl<T> From<sync::PoisonError<T>> for ResolveError {
    fn from(e: sync::PoisonError<T>) -> Self {
        ResolveErrorKind::Msg(format!("lock was poisoned, this is non-recoverable: {e}")).into()
    }
}