1use crate::{Backend, ExecutorHandle, Instant, deadline};
4use std::io;
5#[derive(Clone, Debug, PartialEq, Eq)]
6pub enum Record {
7 Srv {
8 target: String,
9 port: u16,
10 priority: u16,
11 weight: u16,
12 ttl: u32,
13 },
14 Txt {
15 text: String,
16 ttl: u32,
17 },
18}
19#[derive(Clone, Copy)]
20pub enum Query {
21 Srv,
22 Txt,
23}
24#[cfg(any(test, windows, all(unix, not(target_arch = "wasm32"))))]
25impl Query {
26 fn code(self) -> u16 {
27 match self {
28 Self::Srv => 33,
29 Self::Txt => 16,
30 }
31 }
32}
33pub async fn query<B: Backend>(
34 executor: &ExecutorHandle<B>,
35 name: String,
36 kind: Query,
37 at: Instant,
38) -> io::Result<Vec<Record>> {
39 let result = deadline(executor, at, async {
40 executor
41 .blocking(move || {
42 Ok(turnloop::Payload::Boxed(Box::new(native_query(
43 &name, kind,
44 ))))
45 })
46 .await
47 .map_err(crate::error)
48 })
49 .await?;
50 match result {
51 turnloop::Payload::Boxed(result) => *result
52 .downcast::<io::Result<Vec<Record>>>()
53 .map_err(|_| io::Error::other("invalid DNS worker result"))?,
54 _ => Err(io::Error::other("invalid DNS worker payload")),
55 }
56}
57#[cfg(all(unix, not(target_arch = "wasm32")))]
58fn native_query(name: &str, kind: Query) -> io::Result<Vec<Record>> {
59 use std::sync::{
60 Mutex,
61 atomic::{AtomicU16, Ordering},
62 };
63 static RESOLVER: Mutex<()> = Mutex::new(());
66 static ID: AtomicU16 = AtomicU16::new(1);
67 #[link(name = "resolv")]
68 unsafe extern "C" {
69 #[cfg_attr(target_vendor = "apple", link_name = "res_9_send")]
70 fn res_send(
71 msg: *const u8,
72 msglen: std::ffi::c_int,
73 answer: *mut u8,
74 answerlen: std::ffi::c_int,
75 ) -> std::ffi::c_int;
76 }
77 let mut packet = Vec::with_capacity(512);
78 packet.extend_from_slice(&ID.fetch_add(1, Ordering::Relaxed).to_be_bytes());
79 packet.extend_from_slice(&[1, 0, 0, 1, 0, 0, 0, 0, 0, 0]);
80 for label in name.trim_end_matches('.').split('.') {
81 if label.is_empty() || label.len() > 63 || !label.is_ascii() {
82 return Err(io::ErrorKind::InvalidInput.into());
83 }
84 packet.push(label.len() as u8);
85 packet.extend_from_slice(label.as_bytes());
86 }
87 if packet.len() > 266 {
88 return Err(io::ErrorKind::InvalidInput.into());
89 }
90 packet.push(0);
91 packet.extend_from_slice(&kind.code().to_be_bytes());
92 packet.extend_from_slice(&[0, 1]);
93 let mut answer = vec![0; 65535];
94 let _lock = RESOLVER
95 .lock()
96 .map_err(|_| io::Error::other("resolver lock poisoned"))?;
97 let n = unsafe {
100 res_send(
101 packet.as_ptr(),
102 packet.len() as _,
103 answer.as_mut_ptr(),
104 answer.len() as _,
105 )
106 };
107 if n < 0 {
108 return Err(io::Error::last_os_error());
109 }
110 if n as usize > answer.len() {
111 return Err(io::Error::other("truncated DNS packet"));
112 }
113 answer.truncate(n as usize);
114 if answer.get(..2) != packet.get(..2) {
115 return Err(io::Error::other("DNS query identity mismatch"));
116 }
117 parse(&answer, kind)
118}
119#[cfg(windows)]
120fn native_query(name: &str, kind: Query) -> io::Result<Vec<Record>> {
121 use std::ffi::{CStr, CString};
122 use windows_sys::Win32::NetworkManagement::Dns::*;
123 let name = CString::new(name).map_err(|_| io::ErrorKind::InvalidInput)?;
124 let mut first = std::ptr::null_mut();
125 let status = unsafe {
127 DnsQuery_UTF8(
128 name.as_ptr().cast(),
129 kind.code(),
130 DNS_QUERY_STANDARD,
131 std::ptr::null_mut(),
132 &mut first,
133 std::ptr::null_mut(),
134 )
135 };
136 if status == 9003 || status == 9501 {
137 return Ok(Vec::new());
138 }
139 if status != 0 {
140 return Err(io::Error::from_raw_os_error(status as i32));
141 }
142 struct Records(*mut DNS_RECORDA);
143 impl Drop for Records {
144 fn drop(&mut self) {
145 unsafe {
147 DnsFree(self.0.cast(), DnsFreeRecordList);
148 }
149 }
150 }
151 let records = Records(first);
152 let mut p = records.0;
153 let mut output = Vec::new();
154 while !p.is_null() {
155 let r = unsafe { &*p };
157 if r.wType == 33 {
158 let srv = unsafe { &r.Data.SRV };
160 if srv.pNameTarget.is_null() {
161 return Err(io::Error::other("empty SRV target"));
162 }
163 let target = unsafe { CStr::from_ptr(srv.pNameTarget.cast()) }
165 .to_str()
166 .map_err(io::Error::other)?
167 .to_owned();
168 output.push(Record::Srv {
169 target,
170 port: srv.wPort,
171 priority: srv.wPriority,
172 weight: srv.wWeight,
173 ttl: r.dwTtl,
174 });
175 } else if r.wType == 16 {
176 let txt = unsafe { &r.Data.TXT };
179 let strings = unsafe {
181 std::slice::from_raw_parts(txt.pStringArray.as_ptr(), txt.dwStringCount as usize)
182 };
183 let mut text = String::new();
184 for &ptr in strings {
185 if ptr.is_null() {
186 return Err(io::Error::other("empty TXT pointer"));
187 }
188 text.push_str(
190 unsafe { CStr::from_ptr(ptr.cast()) }
191 .to_str()
192 .map_err(io::Error::other)?,
193 );
194 }
195 output.push(Record::Txt { text, ttl: r.dwTtl });
196 }
197 p = r.pNext;
198 }
199 Ok(output)
200}
201#[cfg(not(any(windows, all(unix, not(target_arch = "wasm32")))))]
202fn native_query(_: &str, _: Query) -> io::Result<Vec<Record>> {
203 Err(io::Error::new(
204 io::ErrorKind::Unsupported,
205 "host has no SRV/TXT resolver capability",
206 ))
207}
208#[cfg(any(test, all(unix, not(target_arch = "wasm32"))))]
209fn parse(bytes: &[u8], kind: Query) -> io::Result<Vec<Record>> {
210 fn invalid() -> io::Error {
211 io::Error::new(io::ErrorKind::InvalidData, "invalid DNS packet")
212 }
213 fn u16_at(b: &[u8], at: usize) -> io::Result<u16> {
214 Ok(u16::from_be_bytes(
215 b.get(at..at + 2)
216 .ok_or_else(invalid)?
217 .try_into()
218 .map_err(|_| invalid())?,
219 ))
220 }
221 fn name(b: &[u8], at: &mut usize) -> io::Result<String> {
222 let mut out = String::new();
223 let mut p = *at;
224 let mut jumped = false;
225 for _ in 0..128 {
226 let len = *b.get(p).ok_or_else(invalid)?;
227 if len & 0xc0 == 0xc0 {
228 let dest = usize::from(u16_at(b, p)? & 0x3fff);
229 if dest >= p {
230 return Err(invalid());
231 }
232 if !jumped {
233 *at = p + 2;
234 jumped = true;
235 }
236 p = dest;
237 } else if len == 0 {
238 if !jumped {
239 *at = p + 1;
240 }
241 return Ok(out);
242 } else {
243 if len > 63 {
244 return Err(invalid());
245 }
246 p += 1;
247 let label =
248 std::str::from_utf8(b.get(p..p + usize::from(len)).ok_or_else(invalid)?)
249 .map_err(|_| invalid())?;
250 if !out.is_empty() {
251 out.push('.');
252 }
253 out.push_str(label);
254 if out.len() > 253 {
255 return Err(invalid());
256 }
257 p += usize::from(len);
258 }
259 }
260 Err(invalid())
261 }
262 let flags = u16_at(bytes, 2)?;
263 if flags & 0x8000 == 0 || flags & 0x0200 != 0 {
264 return Err(invalid());
265 }
266 match flags & 0xf {
267 0 => {}
268 3 => return Ok(Vec::new()),
269 _ => return Err(io::Error::other("DNS server failed query")),
270 }
271 let mut at = 12;
272 for _ in 0..u16_at(bytes, 4)? {
273 name(bytes, &mut at)?;
274 at += 4;
275 }
276 let mut records = Vec::new();
277 for _ in 0..u16_at(bytes, 6)? {
278 name(bytes, &mut at)?;
279 let ty = u16_at(bytes, at)?;
280 let class = u16_at(bytes, at + 2)?;
281 let ttl = u32::from_be_bytes(
282 bytes
283 .get(at + 4..at + 8)
284 .ok_or_else(invalid)?
285 .try_into()
286 .map_err(|_| invalid())?,
287 );
288 let size = usize::from(u16_at(bytes, at + 8)?);
289 at += 10;
290 let end = at.checked_add(size).ok_or_else(invalid)?;
291 let data = bytes.get(at..end).ok_or_else(invalid)?;
292 if class == 1 && ty == kind.code() {
293 if ty == 33 {
294 if size < 7 {
295 return Err(invalid());
296 }
297 let priority = u16_at(bytes, at)?;
298 let weight = u16_at(bytes, at + 2)?;
299 let port = u16_at(bytes, at + 4)?;
300 let mut cursor = at + 6;
301 let target = name(bytes, &mut cursor)?;
302 if cursor != end || target.is_empty() || port == 0 {
303 return Err(invalid());
304 }
305 records.push(Record::Srv {
306 target,
307 port,
308 priority,
309 weight,
310 ttl,
311 });
312 } else {
313 let mut text = Vec::new();
314 let mut p = 0;
315 while p < data.len() {
316 let n = usize::from(data[p]);
317 p += 1;
318 text.extend_from_slice(data.get(p..p + n).ok_or_else(invalid)?);
319 p += n;
320 }
321 records.push(Record::Txt {
322 text: String::from_utf8(text).map_err(|_| invalid())?,
323 ttl,
324 });
325 }
326 }
327 at = end;
328 }
329 Ok(records)
330}
331#[cfg(test)]
332mod tests {
333 use super::*;
334 #[test]
335 fn srv_txt_compression_and_malformed_answers() {
336 let mut answer = vec![0, 1, 0x81, 0x80, 0, 1, 0, 1, 0, 0, 0, 0];
337 answer.extend_from_slice(b"\x01x\x07example\x03com\0\0\x21\0\x01\xc0\x0c\0\x21\0\x01\0\0\0\x3c\0\x0b\0\x01\0\x02\x69\x89\x02db\xc0\x0e");
338 assert_eq!(
339 parse(&answer, Query::Srv).expect("SRV"),
340 vec![Record::Srv {
341 target: "db.example.com".into(),
342 port: 27017,
343 priority: 1,
344 weight: 2,
345 ttl: 60
346 }]
347 );
348 assert!(parse(&answer[..answer.len() - 1], Query::Srv).is_err());
349 let mut txt = vec![0, 1, 0x81, 0x80, 0, 0, 0, 1, 0, 0, 0, 0];
350 txt.extend_from_slice(b"\0\0\x10\0\x01\0\0\0\x3c\0\x06\x02ab\x02cd");
351 assert_eq!(
352 parse(&txt, Query::Txt).expect("TXT"),
353 vec![Record::Txt {
354 text: "abcd".into(),
355 ttl: 60
356 }]
357 );
358 let mut looped = answer.clone();
359 let n = looped.len();
360 looped[n - 2] = 0xc0;
361 looped[n - 1] = (n - 2) as u8;
362 assert!(parse(&looped, Query::Srv).is_err());
363 txt[3] = 2;
364 assert!(parse(&txt, Query::Txt).is_err());
365 txt[3] = 3;
366 assert!(parse(&txt, Query::Txt).expect("NXDOMAIN").is_empty());
367 }
368}