1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use byteorder::{BigEndian, ByteOrder};
use std::{collections::HashMap, convert::TryFrom};
use super::{DnsPacketContent, Name, QCLASS, QTYPE};
#[derive(Debug)]
pub struct Question<'a> {
pub qname: Name<'a>,
pub qtype: QTYPE,
pub qclass: QCLASS,
pub unicast_response: bool,
}
impl<'a> Question<'a> {
pub fn new(qname: Name<'a>, qtype: QTYPE, qclass: QCLASS, unicast_response: bool) -> Self {
Self {
qname,
qtype,
qclass,
unicast_response,
}
}
fn append_common(&self, out: &mut Vec<u8>) -> crate::Result<()> {
let mut buf = [0u8; 4];
let qclass = match self.unicast_response {
true => self.qclass as u16 | 0x8000,
false => self.qclass as u16,
};
BigEndian::write_u16(&mut buf[..2], self.qtype as u16);
BigEndian::write_u16(&mut buf[2..], qclass);
out.extend(&buf);
Ok(())
}
}
impl<'a> DnsPacketContent<'a> for Question<'a> {
fn parse(data: &'a [u8], position: usize) -> crate::Result<Self> {
let qname = Name::parse(data, position)?;
let offset = position + qname.len();
let qclass = BigEndian::read_u16(&data[offset + 2..offset + 4]);
Ok(Self {
qname,
qtype: QTYPE::try_from(BigEndian::read_u16(&data[offset..offset + 2]))?,
qclass: QCLASS::try_from(qclass & 0x7FFF)?,
unicast_response: qclass & 0x8000 == 0x8000,
})
}
fn append_to_vec(&self, out: &mut Vec<u8>) -> crate::Result<()> {
self.qname.append_to_vec(out)?;
self.append_common(out)
}
fn compress_append_to_vec(
&self,
out: &mut Vec<u8>,
name_refs: &mut HashMap<u64, usize>,
) -> crate::Result<()> {
self.qname.compress_append_to_vec(out, name_refs)?;
self.append_common(out)
}
fn len(&self) -> usize {
self.qname.len() + 4
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::convert::TryInto;
#[test]
fn parse_question() {
let bytes = b"\x00\x00\x04_srv\x04_udp\x05local\x00\x00\x10\x00\x01";
let question = Question::parse(bytes, 2);
assert!(question.is_ok());
let question = question.unwrap();
assert_eq!(QCLASS::IN, question.qclass);
assert_eq!(QTYPE::TXT, question.qtype);
assert!(!question.unicast_response);
}
#[test]
fn append_to_vec() {
let question = Question::new(
"_srv._udp.local".try_into().unwrap(),
QTYPE::TXT,
QCLASS::IN,
false,
);
let mut bytes = Vec::new();
question.append_to_vec(&mut bytes).unwrap();
assert_eq!(b"\x04_srv\x04_udp\x05local\x00\x00\x10\x00\x01", &bytes[..]);
assert_eq!(bytes.len(), question.len());
}
#[test]
fn unicast_response() {
let mut bytes = Vec::new();
Question::new("x.local".try_into().unwrap(), QTYPE::TXT, QCLASS::IN, true)
.append_to_vec(&mut bytes)
.unwrap();
let parsed = Question::parse(&bytes, 0).unwrap();
assert!(parsed.unicast_response);
}
}