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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! EDNS options for signaling cryptographic algorithm understanding.
//!
//! The options in this module allow a validating resolver to signal which
//! signature and hash algorithms they support when making queries.  These
//! options are defined in [RFC 6975].
//!
//! There are three options for three different purposes. However, the data
//! for each of them is a sequence of security algorithms. The module only
//! defines one type [`Understood<Variant, Octs>`] which carries
//! the specific variant as its first type parameter. Marker types and
//! type aliases are defined for the three options [Dau], [Dhu], and [N3u]
//! which specific the DNSSEC signature algorithms, DS hash algorithm, and
//! NSEC3 hash algorithms understood by the client, respectively.
//!
//! [RFC 6975]: https://tools.ietf.org/html/rfc6975

use super::super::iana::{OptionCode, SecAlg};
use super::super::message_builder::OptBuilder;
use super::super::wire::{Compose, Composer, ParseError};
use super::{
    BuildDataError, OptData, ComposeOptData, LongOptData, Opt, ParseOptData
};
use octseq::builder::{EmptyBuilder, FromBuilder, OctetsBuilder};
use octseq::octets::{Octets, OctetsFrom};
use octseq::parse::Parser;
use core::{borrow, fmt, hash, mem, slice};
use core::marker::PhantomData;


//------------ Understood ----------------------------------------------------

/// Option data for understood DNSSEC algorithms.
///
/// This type provides the option data for the three options DAU, DHU, and
/// N3U which allow a client to specify the cryptographic algorithms it
/// supports for DNSSEC signatures, DS hashes, and NSEC3 hashes respectively.
/// Each of them contains a sequence of [`SecAlg`] values in wire format.
///
/// Which exact option is to be used is specified via the `Variant` type
/// argument. Three marker types `DauVariant`, `DhuVariant` and `N3uVariant`
/// are defined with accompanying type aliases [`Dau`], [`Dhu`], and [`N3u`].
///
/// You can create a new value from anything that can be turned into an
/// iterator over [`SecAlg`] via the
/// [`from_sec_algs`][Understood::from_sec_algs] associated function.
/// Once you have a value, you can iterate over the algorithms via the
/// [`iter`][Understood::iter] method or use the [`IntoIterator`] implementation
/// for a reference.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Understood<Variant, Octs: ?Sized> {
    /// A marker for the variant.
    marker: PhantomData<Variant>,

    /// The octets with the data.
    ///
    /// These octets contain a sequence of composed [`SecAlg`] values.
    octets: Octs,
}

/// The marker type for the DAU option.
///
/// Use this as the `Variant` type argument of the
/// [`Understood<..>`][Understood] type to select a DAU option.
#[derive(Clone, Copy, Debug)]
pub struct DauVariant;

/// The marker type for the DHU option.
///
/// Use this as the `Variant` type argument of the
/// [`Understood<..>`][Understood] type to select a DHU option.
#[derive(Clone, Copy, Debug)]
pub struct DhuVariant;

/// The marker type for the N3U option.
///
/// Use this as the `Variant` type argument of the
/// [`Understood<..>`][Understood] type to select a N3U option.
#[derive(Clone, Copy, Debug)]
pub struct N3uVariant;

/// A type alias for the DAU option.
pub type Dau<Octs> = Understood<DauVariant, Octs>;

/// A type alias for the DHU option.
pub type Dhu<Octs> = Understood<DhuVariant, Octs>;

/// A type alias for the N3U option.
pub type N3u<Octs> = Understood<N3uVariant, Octs>;

impl<Variant, Octs> Understood<Variant, Octs> {
    /// Creates a new value from an octets sequence.
    ///
    /// Returns an error if the slice does not contain a value in wire
    /// format or is longer than 65,535 octets.
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError>
    where
        Octs: AsRef<[u8]>,
    {
        Understood::<Variant, _>::check_slice(octets.as_ref())?;
        Ok(unsafe { Self::from_octets_unchecked(octets) })
    }

    /// Creates a new value from an octets sequence without checking.
    ///
    /// # Safety
    ///
    /// The caller needs to make sure that the slice contains a sequence of
    /// 16 bit values that is no longer than 65,535 octets.
    pub unsafe fn from_octets_unchecked(octets: Octs) -> Self {
        Understood {
            marker: PhantomData,
            octets
        }
    }

    /// Creates a new value from a sequence of algorithms.
    ///
    /// The operation will fail if the iterator returns more than 32,767
    /// algorithms.
    pub fn from_sec_algs(
        sec_algs: impl IntoIterator<Item = SecAlg>
    ) -> Result<Self, BuildDataError>
    where
        Octs: FromBuilder,
        <Octs as FromBuilder>::Builder: EmptyBuilder
    {
        let mut octets = EmptyBuilder::empty();
        for item in sec_algs {
            item.compose(&mut octets)?;
        }
        let octets = Octs::from_builder(octets);
        LongOptData::check_len(octets.as_ref().len())?;
        Ok(unsafe { Self::from_octets_unchecked(octets) })
    }
}

impl<Variant> Understood<Variant, [u8]> {
    /// Creates a new value from an octets slice.
    ///
    /// Returns an error if the slice does not contain a value in wire
    /// format or is longer than 65,535 octets.
    pub fn from_slice(slice: &[u8]) -> Result<&Self, ParseError> {
        Understood::<Variant, _>::check_slice(slice)?;
        Ok(unsafe { Self::from_slice_unchecked(slice) })
    }

    /// Creates a new value from an octets slice without checking.
    ///
    /// # Safety
    ///
    /// The caller needs to make sure that the slice contains a sequence of
    /// 16 bit values that is no longer than 65,535 octets.
    #[must_use]
    pub unsafe fn from_slice_unchecked(slice: &[u8]) -> &Self {
        // SAFETY: Understood has repr(transparent)
        mem::transmute(slice)
    }

    /// Checks that a slice contains a correctly encoded value.
    fn check_slice(slice: &[u8]) -> Result<(), ParseError> {
        LongOptData::check_len(slice.len())?;
        if slice.len() % usize::from(u16::COMPOSE_LEN) != 0 {
            return Err(ParseError::form_error("invalid understood data"))
        }
        Ok(())
    }
}

impl<Variant, Octs: AsRef<[u8]>> Understood<Variant, Octs> {
    /// Parses a value from its wire format.
    pub fn parse<'a, Src: Octets<Range<'a> = Octs> + ?Sized>(
        parser: &mut Parser<'a, Src>,
    ) -> Result<Self, ParseError> {
        Self::from_octets(parser.parse_octets(parser.remaining())?)
    }
}

impl<Variant, Octs: ?Sized> Understood<Variant, Octs> {
    /// Returns a reference to the underlying octets.
    pub fn as_octets(&self) -> &Octs {
        &self.octets
    }

    /// Converts a value into its underlying octets.
    pub fn into_octets(self) -> Octs
    where
        Octs: Sized,
    {
        self.octets
    }

    /// Returns the data as an octets slice.
    pub fn as_slice(&self) -> &[u8]
    where
        Octs: AsRef<[u8]>,
    {
        self.octets.as_ref()
    }

    /// Returns a reference to a value over an octets slice.
    pub fn for_slice(&self) -> &Understood<Variant, [u8]>
    where
        Octs: AsRef<[u8]>,
    {
        unsafe {
            Understood::<Variant, _>::from_slice_unchecked(
                self.octets.as_ref()
            )
        }
    }

    /// Returns an iterator over the algorithms in the data.
    pub fn iter(&self) -> SecAlgsIter
    where
        Octs: AsRef<[u8]>,
    {
        SecAlgsIter::new(self.octets.as_ref())
    }
}

impl Understood<DauVariant, ()> {
    pub(super) const CODE: OptionCode = OptionCode::DAU;
}

impl Understood<DhuVariant, ()> {
    pub(super) const CODE: OptionCode = OptionCode::DHU;
}

impl Understood<N3uVariant, ()> {
    pub(super) const CODE: OptionCode = OptionCode::N3U;
}

//--- OctetsFrom

impl<Variant, O, OO> OctetsFrom<Understood<Variant, O>>
for Understood<Variant, OO>
where
    OO: OctetsFrom<O>,
{
    type Error = OO::Error;

    fn try_octets_from(
        source: Understood<Variant, O>
    ) -> Result<Self, Self::Error> {
        Ok(unsafe {
            Self::from_octets_unchecked(
                OO::try_octets_from(source.octets)?
            )
        })
    }
}

//--- AsRef, AsMut, Borrow, BorrowMut

impl<Variant, Octs> AsRef<[u8]> for Understood<Variant, Octs>
where Octs: AsRef<[u8]> + ?Sized {
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl<Variant, Octs> borrow::Borrow<[u8]> for Understood<Variant, Octs>
where Octs: AsRef<[u8]> + ?Sized {
    fn borrow(&self) -> &[u8] {
        self.as_slice()
    }
}

//--- PartialEq and Eq

impl<Var, OtherVar, Octs, OtherOcts> PartialEq<Understood<OtherVar, OtherOcts>>
for Understood<Var, Octs>
where
    Octs: AsRef<[u8]> + ?Sized,
    OtherOcts: AsRef<[u8]> + ?Sized,
{
    fn eq(&self, other: &Understood<OtherVar, OtherOcts>) -> bool {
        self.as_slice().eq(other.as_slice())
    }
}

impl<Variant, Octs: AsRef<[u8]> + ?Sized> Eq for Understood<Variant, Octs> { }

//--- Hash

impl<Variant, Octs: AsRef<[u8]>> hash::Hash for Understood<Variant, Octs> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state)
    }
}

//--- OptData etc.

impl<Octs: ?Sized> OptData for Understood<DauVariant, Octs> {
    fn code(&self) -> OptionCode {
        OptionCode::DAU
    }
}

impl<Octs: ?Sized> OptData for Understood<DhuVariant, Octs> {
    fn code(&self) -> OptionCode {
        OptionCode::DHU
    }
}

impl<Octs: ?Sized> OptData for Understood<N3uVariant, Octs> {
    fn code(&self) -> OptionCode {
        OptionCode::N3U
    }
}

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

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

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

impl<Variant, Octs> ComposeOptData for Understood<Variant, Octs>
where
    Self: OptData,
    Octs: AsRef<[u8]> + ?Sized, 
{
    fn compose_len(&self) -> u16 {
        self.octets.as_ref().len().try_into().expect("long option data")
    }

    fn compose_option<Target: OctetsBuilder + ?Sized>(
        &self, target: &mut Target
    ) -> Result<(), Target::AppendError> {
        target.append_slice(self.octets.as_ref())
    }
}

//--- IntoIter

impl<'a, Variant, Octs> IntoIterator for &'a Understood<Variant, Octs>
where
    Octs: AsRef<[u8]> + ?Sized
{
    type Item = SecAlg;
    type IntoIter = SecAlgsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

//--- Display

impl<Variant, Octs> fmt::Display for Understood<Variant, Octs>
where
    Octs: AsRef<[u8]> + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut first = true;

        for v in self.octets.as_ref() {
            if first {
                write!(f, "{}", *v)?;
                first = false;
            } else {
                write!(f, ", {}", *v)?
            }
        }
        Ok(())
    }
}

//--- Debug

impl<Octs: AsRef<[u8]> + ?Sized> fmt::Debug for Understood<DauVariant, Octs> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Understood<DauVariant>")
            .field(&format_args!("{}", self))
            .finish()
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> fmt::Debug for Understood<DhuVariant, Octs> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Understood<DhuVariant>")
            .field(&format_args!("{}", self))
            .finish()
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> fmt::Debug for Understood<N3uVariant, Octs> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Understood<N3uVariant>")
            .field(&format_args!("{}", self))
            .finish()
    }
}

//--- Serialize

#[cfg(feature = "serde")]
impl<V, Octs: AsRef<[u8]>> serde::Serialize for Understood<V, Octs> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer {
        use serde::ser::SerializeSeq;
        let mut list = serializer.serialize_seq(None)?;
        for item in self.iter() {
            list.serialize_element(&item)?;
        }
        list.end()
    }
}

//--- Extended Opt and OptBuilder

impl<Octs: Octets> Opt<Octs> {
    /// Returns the first DAU option if present.
    ///
    /// This option lists the DNSSEC signature algorithms the requester
    /// supports.
    pub fn dau(&self) -> Option<Dau<Octs::Range<'_>>> {
        self.first()
    }

    /// Returns the first DHU option if present.
    ///
    /// This option lists the DS hash algorithms the requester supports.
    pub fn dhu(&self) -> Option<Dhu<Octs::Range<'_>>> {
        self.first()
    }

    /// Returns the first N3U option if present.
    ///
    /// This option lists the NSEC3 hash algorithms the requester supports.
    pub fn n3u(&self) -> Option<N3u<Octs::Range<'_>>> {
        self.first()
    }
}

impl<'a, Target: Composer> OptBuilder<'a, Target> {
    /// Appends a DAU option.
    ///
    /// The DAU option lists the DNSSEC signature algorithms the requester
    /// supports.
    pub fn dau(
        &mut self, algs: &impl AsRef<[SecAlg]>,
    ) -> Result<(), BuildDataError> {
        Ok(self.push_raw_option(
            OptionCode::DAU,
            u16::try_from(
                algs.as_ref().len() * usize::from(SecAlg::COMPOSE_LEN)
            ).map_err(|_| BuildDataError::LongOptData)?,
            |octs| {
                algs.as_ref().iter().try_for_each(|item| item.compose(octs))
            },
        )?)
    }

    /// Appends a DHU option.
    ///
    /// The DHU option lists the DS hash algorithms the requester supports.
    pub fn dhu(
        &mut self, algs: &impl AsRef<[SecAlg]>,
    ) -> Result<(), BuildDataError> {
        Ok(self.push_raw_option(
            OptionCode::DHU,
            u16::try_from(
                algs.as_ref().len() * usize::from(SecAlg::COMPOSE_LEN)
            ).map_err(|_| BuildDataError::LongOptData)?,
            |octs| {
                algs.as_ref().iter().try_for_each(|item| item.compose(octs))
            },
        )?)
    }

    /// Appends a N3U option.
    ///
    /// The N3U option lists the NSEC3 hash algorithms the requester supports.
    pub fn n3u(
        &mut self, algs: &impl AsRef<[SecAlg]>,
    ) -> Result<(), BuildDataError> {
        Ok(self.push_raw_option(
            OptionCode::N3U,
            u16::try_from(
                algs.as_ref().len() * usize::from(SecAlg::COMPOSE_LEN)
            ).map_err(|_| BuildDataError::LongOptData)?,
            |octs| {
                algs.as_ref().iter().try_for_each(|item| item.compose(octs))
            },
        )?)
    }
}

//------------ SecAlgsIter ---------------------------------------------------

pub struct SecAlgsIter<'a>(slice::Iter<'a, u8>);

impl<'a> SecAlgsIter<'a> {
    fn new(slice: &'a [u8]) -> Self {
        SecAlgsIter(slice.iter())
    }
}

impl<'a> Iterator for SecAlgsIter<'a> {
    type Item = SecAlg;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|x| SecAlg::from_int(*x))
    }
}

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

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

    #[test]
    #[allow(clippy::redundant_closure)] // lifetimes ...
    fn dau_compose_parse() {
        test_option_compose_parse(
            &Dau::from_octets("foof").unwrap(),
            |parser| Dau::parse(parser)
        );
    }
}