webrtc_mdns/message/resource/
opt.rs

1use super::*;
2use crate::error::{Result, *};
3use crate::message::packer::*;
4
5// An OPTResource is an OPT pseudo Resource record.
6//
7// The pseudo resource record is part of the extension mechanisms for DNS
8// as defined in RFC 6891.
9#[derive(Default, Debug, Clone, PartialEq, Eq)]
10pub struct OptResource {
11    pub options: Vec<DnsOption>,
12}
13
14// An Option represents a DNS message option within OPTResource.
15//
16// The message option is part of the extension mechanisms for DNS as
17// defined in RFC 6891.
18#[derive(Default, Debug, Clone, PartialEq, Eq)]
19pub struct DnsOption {
20    pub code: u16, // option code
21    pub data: Vec<u8>,
22}
23
24impl fmt::Display for DnsOption {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(
27            f,
28            "dnsmessage.Option{{Code: {}, Data: {:?}}}",
29            self.code, self.data
30        )
31    }
32}
33
34impl fmt::Display for OptResource {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        let s: Vec<String> = self.options.iter().map(|o| o.to_string()).collect();
37        write!(f, "dnsmessage.OPTResource{{options: {}}}", s.join(","))
38    }
39}
40
41impl ResourceBody for OptResource {
42    fn real_type(&self) -> DnsType {
43        DnsType::Opt
44    }
45
46    fn pack(
47        &self,
48        mut msg: Vec<u8>,
49        _compression: &mut Option<HashMap<String, usize>>,
50        _compression_off: usize,
51    ) -> Result<Vec<u8>> {
52        for opt in &self.options {
53            msg = pack_uint16(msg, opt.code);
54            msg = pack_uint16(msg, opt.data.len() as u16);
55            msg = pack_bytes(msg, &opt.data);
56        }
57        Ok(msg)
58    }
59
60    fn unpack(&mut self, msg: &[u8], mut off: usize, length: usize) -> Result<usize> {
61        let mut opts = vec![];
62        let old_off = off;
63        while off < old_off + length {
64            let (code, new_off) = unpack_uint16(msg, off)?;
65            off = new_off;
66
67            let (l, new_off) = unpack_uint16(msg, off)?;
68            off = new_off;
69
70            let mut opt = DnsOption {
71                code,
72                data: vec![0; l as usize],
73            };
74            if off + l as usize > msg.len() {
75                return Err(Error::ErrCalcLen);
76            }
77            opt.data.copy_from_slice(&msg[off..off + l as usize]);
78            off += l as usize;
79            opts.push(opt);
80        }
81        self.options = opts;
82        Ok(off)
83    }
84}