simple_dns/dns/rdata/
wks.rs

1use std::borrow::Cow;
2
3use crate::{bytes_buffer::BytesBuffer, dns::WireFormat};
4
5use super::RR;
6
7/// The WKS record is used to describe the well known services supported by a particular protocol on a particular internet address.
8#[derive(Debug, PartialEq, Eq, Hash, Clone)]
9pub struct WKS<'a> {
10    /// An 32 bit Internet address
11    pub address: u32,
12    /// An 8 bit IP protocol number
13    pub protocol: u8,
14    /// A variable length bit map.  The bit map must be a multiple of 8 bits long.
15    pub bit_map: Cow<'a, [u8]>,
16}
17
18impl RR for WKS<'_> {
19    const TYPE_CODE: u16 = 11;
20}
21
22impl WKS<'_> {
23    /// Transforms the inner data into its owned type
24    pub fn into_owned<'b>(self) -> WKS<'b> {
25        WKS {
26            address: self.address,
27            protocol: self.protocol,
28            bit_map: self.bit_map.into_owned().into(),
29        }
30    }
31}
32
33impl<'a> WireFormat<'a> for WKS<'a> {
34    const MINIMUM_LEN: usize = 5;
35
36    fn parse(data: &mut BytesBuffer<'a>) -> crate::Result<Self>
37    where
38        Self: Sized,
39    {
40        let address = data.get_u32()?;
41        let protocol = data.get_u8()?;
42        let bit_map = Cow::Borrowed(data.get_remaining());
43
44        Ok(Self {
45            address,
46            protocol,
47            bit_map,
48        })
49    }
50
51    fn write_to<T: std::io::Write>(&self, out: &mut T) -> crate::Result<()> {
52        out.write_all(&self.address.to_be_bytes())?;
53        out.write_all(&[self.protocol])?;
54        out.write_all(&self.bit_map)?;
55
56        Ok(())
57    }
58
59    fn len(&self) -> usize {
60        self.bit_map.len() + Self::MINIMUM_LEN
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use std::net::Ipv4Addr;
67
68    use crate::{dns::WireFormat, rdata::RData, ResourceRecord};
69
70    #[test]
71    fn parse_sample() -> Result<(), Box<dyn std::error::Error>> {
72        let sample_file = std::fs::read("samples/zonefile/WKS.sample")?;
73
74        let sample_rdata = match ResourceRecord::parse(&mut sample_file[..].into())?.rdata {
75            RData::WKS(rdata) => rdata,
76            _ => unreachable!(),
77        };
78
79        let sample_ip: u32 = "10.0.0.1".parse::<Ipv4Addr>()?.into();
80
81        assert_eq!(sample_rdata.address, sample_ip);
82        assert_eq!(sample_rdata.protocol, 6);
83        assert_eq!(sample_rdata.bit_map, vec![224, 0, 5]);
84
85        Ok(())
86    }
87}