simple_dns/dns/rdata/
srv.rs1use crate::bytes_buffer::BytesBuffer;
2use crate::dns::WireFormat;
3use crate::Name;
4
5use super::RR;
6
7#[derive(Debug, PartialEq, Eq, Hash, Clone)]
9pub struct SRV<'a> {
10 pub priority: u16,
14 pub weight: u16,
18 pub port: u16,
20 pub target: Name<'a>,
22}
23
24impl RR for SRV<'_> {
25 const TYPE_CODE: u16 = 33;
26}
27
28impl SRV<'_> {
29 pub fn into_owned<'b>(self) -> SRV<'b> {
31 SRV {
32 priority: self.priority,
33 weight: self.weight,
34 port: self.port,
35 target: self.target.into_owned(),
36 }
37 }
38}
39
40impl<'a> WireFormat<'a> for SRV<'a> {
41 const MINIMUM_LEN: usize = 6;
42
43 fn parse(data: &mut BytesBuffer<'a>) -> crate::Result<Self>
44 where
45 Self: Sized,
46 {
47 let priority = data.get_u16()?;
48 let weight = data.get_u16()?;
49 let port = data.get_u16()?;
50 let target = Name::parse(data)?;
51
52 Ok(Self {
53 priority,
54 weight,
55 port,
56 target,
57 })
58 }
59
60 fn write_to<T: std::io::Write>(&self, out: &mut T) -> crate::Result<()> {
61 out.write_all(&self.priority.to_be_bytes())?;
62 out.write_all(&self.weight.to_be_bytes())?;
63 out.write_all(&self.port.to_be_bytes())?;
64
65 self.target.write_to(out)
66 }
67
68 fn len(&self) -> usize {
69 self.target.len() + Self::MINIMUM_LEN
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use std::{collections::HashMap, io::Cursor};
76
77 use crate::{rdata::RData, ResourceRecord};
78
79 use super::*;
80
81 #[test]
82 fn parse_and_write_srv() {
83 let srv = SRV {
84 priority: 1,
85 weight: 2,
86 port: 3,
87 target: Name::new("_srv._tcp.example.com").unwrap(),
88 };
89
90 let mut bytes = Vec::new();
91 assert!(srv.write_to(&mut bytes).is_ok());
92
93 let srv = SRV::parse(&mut bytes[..].into());
94 assert!(srv.is_ok());
95 let srv = srv.unwrap();
96
97 assert_eq!(1, srv.priority);
98 assert_eq!(2, srv.weight);
99 assert_eq!(3, srv.port);
100 assert_eq!(bytes.len(), srv.len());
101 }
102
103 #[test]
104 fn srv_should_not_be_compressed() {
105 let srv = SRV {
106 priority: 1,
107 weight: 2,
108 port: 3,
109 target: Name::new("_srv._tcp.example.com").unwrap(),
110 };
111
112 let mut plain = Vec::new();
113 let mut compressed = Cursor::new(Vec::new());
114 let mut names = HashMap::new();
115
116 assert!(srv.write_to(&mut plain).is_ok());
117 assert!(srv.write_compressed_to(&mut compressed, &mut names).is_ok());
118
119 assert_eq!(plain, compressed.into_inner());
120 }
121
122 #[test]
123 fn parse_sample() -> Result<(), Box<dyn std::error::Error>> {
124 let sample_file = std::fs::read("samples/zonefile/SRV.sample")?;
125
126 let sample_rdata = match ResourceRecord::parse(&mut sample_file[..].into())?.rdata {
127 RData::SRV(rdata) => rdata,
128 _ => unreachable!(),
129 };
130
131 assert_eq!(sample_rdata.priority, 65535);
132 assert_eq!(sample_rdata.weight, 65535);
133 assert_eq!(sample_rdata.port, 65535);
134 assert_eq!(sample_rdata.target, "old-slow-box.sample".try_into()?);
135
136 Ok(())
137 }
138}