simple_dns/dns/rdata/
wks.rs

1use std::{borrow::Cow, convert::TryInto};
2
3use crate::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<'a> RR for WKS<'a> {
19    const TYPE_CODE: u16 = 11;
20}
21
22impl<'a> WKS<'a> {
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    fn parse(data: &'a [u8], position: &mut usize) -> crate::Result<Self>
35    where
36        Self: Sized,
37    {
38        let address = u32::from_be_bytes(data[*position..*position + 4].try_into()?);
39        let protocol = data[*position + 4];
40        let bit_map = Cow::Borrowed(&data[*position + 5..]);
41
42        *position += 5 + bit_map.len();
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() + 5
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(&sample_file, &mut 0)?.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}