flex_dns/rdata/
key.rs

1use crate::{Buffer, DnsMessage, DnsMessageError, MutBuffer};
2use crate::characters::Characters;
3use crate::parse::Parse;
4use crate::rdata::{RData, RDataParse};
5use crate::write::WriteBytes;
6
7/// # Key
8/// This record is used to store a public key that can be used to verify DNSSEC signatures
9#[derive(Copy, Clone, Debug, PartialEq)]
10pub struct Key<'a> {
11    /// The flags field is used to store flags specific to the algorithm
12    pub flags: u16,
13    /// The protocol field is used to store the protocol number for which this key is used
14    pub protocol: u8,
15    /// The algorithm field is used to store the algorithm number for this key
16    pub algorithm: u8,
17    /// The public key is stored as a character string
18    pub public_key: Characters<'a>,
19}
20
21impl<'a> RDataParse<'a> for Key<'a> {
22    #[inline]
23    fn parse(rdata: &RData<'a>, i: &mut usize) -> Result<Self, DnsMessageError> {
24        let flags = u16::parse(rdata, i)?;
25        let protocol = u8::parse(rdata, i)?;
26        let algorithm = u8::parse(rdata, i)?;
27        let public_key = Characters::parse(rdata, i)?;
28
29        Ok(Self {
30            flags,
31            protocol,
32            algorithm,
33            public_key,
34        })
35    }
36}
37
38impl<'a> WriteBytes for Key<'a> {
39    #[inline]
40    fn write<
41        const PTR_STORAGE: usize,
42        const DNS_SECTION: usize,
43        B: MutBuffer + Buffer,
44    >(&self, message: &mut DnsMessage<PTR_STORAGE, DNS_SECTION, B>) -> Result<usize, DnsMessageError> {
45        let mut bytes = 0;
46
47        bytes += self.flags.write(message)?;
48        bytes += self.protocol.write(message)?;
49        bytes += self.algorithm.write(message)?;
50        bytes += self.public_key.write(message)?;
51
52        Ok(bytes)
53    }
54}
55
56#[cfg(test)]
57mod test {
58    use crate::rdata::testutils::parse_write_test;
59
60    use super::*;
61
62    parse_write_test!(
63        8,
64        [
65            0x00, 0x0e, // flags
66            0xc4, // protocol
67            0x4c, // algorithm
68            0x03, // length
69            b'w', b'w', b'w', // "www"
70        ],
71        Key {
72            flags: 14,
73            protocol: 196,
74            algorithm: 76,
75            public_key: unsafe { Characters::new_unchecked(b"www") },
76        },
77    );
78}