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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//! EDNS option for extended DNS errors.
//!
//! The option in this module – [`ExtendedError<Octs>`] – allows a server to
//! provide more detailed information why a query has failed.
//!
//! The option is defined in [RFC 8914](https://tools.ietf.org/html/rfc8914).

use super::super::iana::exterr::{ExtendedErrorCode, EDE_PRIVATE_RANGE_BEGIN};
use super::super::iana::OptionCode;
use super::super::message_builder::OptBuilder;
use super::super::wire::ParseError;
use super::super::wire::{Compose, Composer};
use super::{
    BuildDataError, LongOptData, Opt, OptData, ComposeOptData, ParseOptData
};
use octseq::builder::OctetsBuilder;
use octseq::octets::Octets;
use octseq::parse::Parser;
use octseq::str::Str;
use core::{fmt, hash, str};

//------------ ExtendedError -------------------------------------------------

/// Option data for an extended DNS error.
///
/// The Extended DNS Error option allows a server to include more detailed
/// information in a response to a failed query why it did. It contains a
/// standardized [`ExtendedErrorCode`] for machines and an optional UTF-8
/// error text for humans.
#[derive(Clone)]
pub struct ExtendedError<Octs> {
    /// The extended error code.
    code: ExtendedErrorCode,

    /// Optional human-readable error information.
    ///
    /// See `text` for the interpretation of the result.
    text: Option<Result<Str<Octs>, Octs>>,
}

impl<Octs> ExtendedError<Octs> {
    /// Creates a new value from a code and optional text.
    ///
    /// Returns an error if `text` is present but is too long to fit into
    /// an option.
    pub fn new(
        code: ExtendedErrorCode, text: Option<Str<Octs>>
    ) -> Result<Self, LongOptData>
    where Octs: AsRef<[u8]> {
        if let Some(ref text) = text {
            LongOptData::check_len(
                text.len() + usize::from(ExtendedErrorCode::COMPOSE_LEN)
            )?
        }
        Ok(unsafe { Self::new_unchecked(code, text.map(Ok)) })
    }

    /// Creates a new value without checking for the option length.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the length of the wire format of the
    /// value does not exceed 65,535 octets.
    pub unsafe fn new_unchecked(
        code: ExtendedErrorCode, text: Option<Result<Str<Octs>, Octs>>
    ) -> Self {
        Self { code, text }
    }

    /// Returns the error code.
    pub fn code(&self) -> ExtendedErrorCode {
        self.code
    }

    /// Returns the text.
    ///
    /// If there is no text, returns `None`. If there is text and it is
    /// correctly encoded UTF-8, returns `Some(Ok(_))`. If there is text but
    /// it is not UTF-8, returns `Some(Err(_))`.
    pub fn text(&self) -> Option<Result<&Str<Octs>, &Octs>> {
        self.text.as_ref().map(Result::as_ref)
    }

    /// Returns the text as an octets slice.
    pub fn text_slice(&self) -> Option<&[u8]>
    where Octs: AsRef<[u8]> {
        match self.text {
            Some(Ok(ref text)) => Some(text.as_slice()),
            Some(Err(ref text)) => Some(text.as_ref()),
            None => None
        }
    }

    /// Sets the text field.
    pub fn set_text(&mut self, text: Str<Octs>) {
        self.text = Some(Ok(text));
    }

    /// Returns true if the code is in the private range.
    pub fn is_private(&self) -> bool {
        self.code().to_int() >= EDE_PRIVATE_RANGE_BEGIN
    }

    pub fn parse<'a, Src: Octets<Range<'a> = Octs> + ?Sized>(
        parser: &mut Parser<'a, Src>
    ) -> Result<Self, ParseError>
    where Octs: AsRef<[u8]> {
        let code = ExtendedErrorCode::parse(parser)?;
        let text = match parser.remaining() {
            0 => None,
            n => {
                Some(Str::from_utf8(parser.parse_octets(n)?).map_err(|err| {
                    err.into_octets()
                }))
            }
        };
        Ok(unsafe { Self::new_unchecked(code, text) })
    }
}

//--- From and TryFrom

impl<Octs> From<ExtendedErrorCode> for ExtendedError<Octs> {
    fn from(code: ExtendedErrorCode) -> Self {
        Self { code, text: None }
    }
}

impl<Octs> From<u16> for ExtendedError<Octs> {
    fn from(code: u16) -> Self {
        Self {
            code: ExtendedErrorCode::from_int(code),
            text: None,
        }
    }
}

impl<Octs> TryFrom<(ExtendedErrorCode, Str<Octs>)> for ExtendedError<Octs> 
where Octs: AsRef<[u8]> {
    type Error = LongOptData;

    fn try_from(
        (code, text): (ExtendedErrorCode, Str<Octs>)
    ) -> Result<Self, Self::Error> {
        Self::new(code, Some(text))
    }
}

//--- OptData, ParseOptData, and ComposeOptData

impl<Octs> OptData for ExtendedError<Octs> {
    fn code(&self) -> OptionCode {
        OptionCode::ExtendedError
    }
}

impl<'a, Octs> ParseOptData<'a, Octs> for ExtendedError<Octs::Range<'a>> 
where Octs: Octets + ?Sized {
    fn parse_option(
        code: OptionCode,
        parser: &mut Parser<'a, Octs>,
    ) -> Result<Option<Self>, ParseError> {
        if code == OptionCode::ExtendedError {
            Self::parse(parser).map(Some)
        }
        else {
            Ok(None)
        }
    }
}

impl<Octs: AsRef<[u8]>> ComposeOptData for ExtendedError<Octs> {
    fn compose_len(&self) -> u16 {
        if let Some(text) = self.text_slice() {
            text.len().checked_add(
                ExtendedErrorCode::COMPOSE_LEN.into()
            ).expect("long option data").try_into().expect("long option data")
        }
        else {
            ExtendedErrorCode::COMPOSE_LEN
        }
    }

    fn compose_option<Target: OctetsBuilder + ?Sized>(
        &self, target: &mut Target
    ) -> Result<(), Target::AppendError> {
        self.code.to_int().compose(target)?;
        if let Some(text) = self.text_slice() {
            target.append_slice(text)?;
        }
        Ok(())
    }
}

//--- Display and Debug

impl<Octs: AsRef<[u8]>> fmt::Display for ExtendedError<Octs> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.code.fmt(f)?;
        match self.text {
            Some(Ok(ref text)) => write!(f, " {}", text)?,
            Some(Err(ref text)) => {
                let mut text = text.as_ref();
                f.write_str(" ")?;
                while !text.is_empty() {
                    let tail = match str::from_utf8(text) {
                        Ok(text) => {
                            f.write_str(text)?;
                            break;
                        }
                        Err(err) => {
                            let (head, tail) = text.split_at(
                                err.valid_up_to()
                            );
                            f.write_str(
                                unsafe {
                                    str::from_utf8_unchecked(head)
                                }
                            )?;
                            f.write_str("\u{FFFD}")?;

                            if let Some(err_len) = err.error_len() {
                                &tail[err_len..]
                            }
                            else {
                                break;
                            }
                        }
                    };
                    text = tail;
                }
            }
            None => { }
        }
        Ok(())
    }
}

impl<Octs: AsRef<[u8]>> fmt::Debug for ExtendedError<Octs> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ExtendedError")
            .field("code", &self.code)
            .field("text", &self.text.as_ref().map(|text| {
                text.as_ref().map_err(|err| err.as_ref())
            }))
            .finish()
    }
}

//--- PartialEq and Eq

impl<Octs, Other> PartialEq<ExtendedError<Other>> for ExtendedError<Octs>
where
    Octs: AsRef<[u8]>,
    Other: AsRef<[u8]>,
{ 
    fn eq(&self, other: &ExtendedError<Other>) -> bool {
       self.code.eq(&other.code) && self.text_slice().eq(&other.text_slice())
    }
}

impl<Octs: AsRef<[u8]>> Eq for ExtendedError<Octs> { }

//--- Hash

impl<Octs: AsRef<[u8]>> hash::Hash for ExtendedError<Octs> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.code.hash(state);
        self.text_slice().hash(state);
    }
}

//--- Extended Opt and OptBuilder

impl<Octs: Octets> Opt<Octs> {
    /// Returns the first extended DNS error option if present.
    ///
    /// The extended DNS error option carries additional error information in
    /// a failed answer.
    pub fn extended_error(&self) -> Option<ExtendedError<Octs::Range<'_>>> {
        self.first()
    }
}

impl<'a, Target: Composer> OptBuilder<'a, Target> {
    /// Appends an extended DNS error option.
    ///
    /// The extended DNS error option carries additional error information in
    /// a failed answer. The `code` argument is a standardized error code
    /// while the optional `text` carries human-readable information.
    ///
    /// The method fails if `text` is too long to be part of an option or if
    /// target runs out of space.
    pub fn extended_error<Octs: AsRef<[u8]>>(
        &mut self, code: ExtendedErrorCode, text: Option<&Str<Octs>>
    ) -> Result<(), BuildDataError> {
        self.push(
            &ExtendedError::new(
                code,
                text.map(|text| {
                    unsafe { Str::from_utf8_unchecked(text.as_slice()) }
                })
            )?
        )?;
        Ok(())
    }
}

//============ Tests =========================================================

#[cfg(all(test, feature="std", feature = "bytes"))]
mod tests {
    use super::*;
    use super::super::test::test_option_compose_parse;

    #[test]
    #[allow(clippy::redundant_closure)] // lifetimes ...
    fn nsid_compose_parse() {
        let ede = ExtendedError::new(
            ExtendedErrorCode::StaleAnswer,
            Some(Str::from_string("some text".into()))
        ).unwrap();
        test_option_compose_parse(
            &ede,
            |parser| ExtendedError::parse(parser)
        );
    }

    #[test]
    fn private() {
        let ede: ExtendedError<&[u8]> = ExtendedErrorCode::DnssecBogus.into();
        assert!(!ede.is_private());

        let ede: ExtendedError<&[u8]> = EDE_PRIVATE_RANGE_BEGIN.into();
        assert!(ede.is_private());
    }
}