use heapless::Vec;
use crate::error::{Error, ErrorCode, Result, bail};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
#[non_exhaustive]
pub enum RecordType {
A = 1,
Ptr = 12,
Txt = 16,
Aaaa = 28,
Srv = 33,
Nsec = 47,
Any = 255,
}
impl RecordType {
#[must_use]
pub const fn value(self) -> u16 {
self as u16
}
#[must_use]
pub const fn from_value(value: u16) -> Option<Self> {
match value {
1 => Some(Self::A),
12 => Some(Self::Ptr),
16 => Some(Self::Txt),
28 => Some(Self::Aaaa),
33 => Some(Self::Srv),
47 => Some(Self::Nsec),
255 => Some(Self::Any),
_ => None,
}
}
#[must_use]
pub const fn answers(self, asked: Self) -> bool {
matches!(asked, Self::Any) || (self as u16) == (asked as u16)
}
}
pub const CLASS_IN: u16 = 1;
pub const CACHE_FLUSH: u16 = 0x8000;
pub const UNICAST_RESPONSE: u16 = 0x8000;
pub const LABEL_MAX: usize = 63;
pub const LABELS_MAX: usize = 8;
const POINTER_LIMIT: usize = 16;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Name {
labels: Vec<Vec<u8, LABEL_MAX>, LABELS_MAX>,
}
impl Name {
#[must_use]
pub const fn root() -> Self {
Self { labels: Vec::new() }
}
pub fn from_labels(labels: &[&[u8]]) -> Result<Self> {
let mut name = Self::root();
for label in labels {
name.push(label)?;
}
Ok(name)
}
pub fn from_strs(labels: &[&str]) -> Result<Self> {
let mut name = Self::root();
for label in labels {
name.push(label.as_bytes())?;
}
Ok(name)
}
pub fn push(&mut self, label: &[u8]) -> Result<()> {
if label.is_empty() || label.len() > LABEL_MAX {
bail!(InvalidArgument)
}
let stored = Vec::from_slice(label).map_err(|_| Error::new(ErrorCode::NoSpace))?;
self.labels
.push(stored)
.map_err(|_| Error::new(ErrorCode::NoSpace))
}
pub fn labels(&self) -> impl Iterator<Item = &[u8]> {
self.labels.iter().map(|label| label.as_slice())
}
#[must_use]
pub fn len(&self) -> usize {
self.labels.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.labels.is_empty()
}
#[must_use]
pub fn eq_ignore_case(&self, other: &Self) -> bool {
self.len() == other.len()
&& self
.labels()
.zip(other.labels())
.all(|(a, b)| a.eq_ignore_ascii_case(b))
}
#[must_use]
pub fn matches(&self, labels: &[&[u8]]) -> bool {
self.len() == labels.len()
&& self
.labels()
.zip(labels.iter())
.all(|(a, b)| a.eq_ignore_ascii_case(b))
}
pub fn decode(buf: &[u8], at: usize) -> Result<(Self, usize)> {
let mut name = Self::root();
let mut cursor = at;
let mut end: Option<usize> = None;
let mut jumps = 0usize;
loop {
let length = *buf.get(cursor).ok_or_else(truncated)?;
match length & 0xC0 {
0x00 => {
let next = cursor.checked_add(1).ok_or_else(malformed)?;
if length == 0 {
return Ok((name, end.unwrap_or(next)));
}
let stop = next
.checked_add(usize::from(length))
.ok_or_else(malformed)?;
let label = buf.get(next..stop).ok_or_else(truncated)?;
name.push(label)?;
cursor = stop;
}
0xC0 => {
let low = *buf
.get(cursor.checked_add(1).ok_or_else(malformed)?)
.ok_or_else(truncated)?;
let target = (usize::from(length & 0x3F) << 8) | usize::from(low);
if target >= cursor {
bail!(DnsMalformed)
}
jumps = jumps.saturating_add(1);
if jumps > POINTER_LIMIT {
bail!(DnsMalformed)
}
if end.is_none() {
end = Some(cursor.checked_add(2).ok_or_else(malformed)?);
}
cursor = target;
}
_ => bail!(DnsMalformed),
}
}
}
}
fn truncated() -> Error {
Error::new(ErrorCode::DnsTruncated)
}
fn malformed() -> Error {
Error::new(ErrorCode::DnsMalformed)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Record<'a> {
pub name: &'a [&'a str],
pub kind: RecordType,
pub ttl: u32,
pub cache_flush: bool,
pub data: RecordData<'a>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecordData<'a> {
Ptr(&'a [&'a str]),
Srv {
port: u16,
target: &'a [&'a str],
},
Txt(&'a [u8]),
Aaaa([u8; 16]),
A([u8; 4]),
}
impl RecordData<'_> {
pub fn write_rdata<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let mut cursor = Cursor::new(buf);
match self {
Self::Ptr(target) => cursor.put_labels(target.iter().map(|l| l.as_bytes()))?,
Self::Srv { port, target } => {
cursor.put_u16(0)?;
cursor.put_u16(0)?;
cursor.put_u16(*port)?;
cursor.put_labels(target.iter().map(|l| l.as_bytes()))?;
}
Self::Txt(bytes) => cursor.put(bytes)?,
Self::Aaaa(address) => cursor.put(address)?,
Self::A(address) => cursor.put(address)?,
}
cursor.finish()
}
#[must_use]
pub const fn kind(&self) -> RecordType {
match self {
Self::Ptr(_) => RecordType::Ptr,
Self::Srv { .. } => RecordType::Srv,
Self::Txt(_) => RecordType::Txt,
Self::Aaaa(_) => RecordType::Aaaa,
Self::A(_) => RecordType::A,
}
}
}
pub const RDATA_MAX: usize = 6 + LABELS_MAX * (LABEL_MAX + 1) + 1;
struct Cursor<'a> {
buf: &'a mut [u8],
at: usize,
}
impl<'a> Cursor<'a> {
const fn new(buf: &'a mut [u8]) -> Self {
Self { buf, at: 0 }
}
fn put(&mut self, bytes: &[u8]) -> Result<()> {
let end = self.at.checked_add(bytes.len()).ok_or_else(no_space)?;
let slot = self.buf.get_mut(self.at..end).ok_or_else(no_space)?;
slot.copy_from_slice(bytes);
self.at = end;
Ok(())
}
fn put_u16(&mut self, value: u16) -> Result<()> {
self.put(&value.to_be_bytes())
}
fn put_labels<'l>(&mut self, labels: impl Iterator<Item = &'l [u8]>) -> Result<()> {
for label in labels {
let length = u8::try_from(label.len()).map_err(|_| Error::new(ErrorCode::NoSpace))?;
if usize::from(length) > LABEL_MAX {
bail!(NoSpace)
}
self.put(&[length])?;
self.put(label)?;
}
self.put(&[0])
}
fn finish(self) -> Result<&'a [u8]> {
self.buf.get(..self.at).ok_or_else(no_space)
}
}
const COMPRESSION_SLOTS: usize = 16;
pub struct DnsWriter<'a, 'n> {
buf: &'a mut [u8],
at: usize,
seen: Vec<(u16, &'n [&'n str]), COMPRESSION_SLOTS>,
counts: [u16; 4],
}
impl<'a, 'n> DnsWriter<'a, 'n> {
pub fn new(buf: &'a mut [u8]) -> Result<Self> {
if buf.len() < HEADER_LEN {
bail!(NoSpace)
}
let mut writer = Self {
buf,
at: 0,
seen: Vec::new(),
counts: [0; 4],
};
writer.at = HEADER_LEN;
Ok(writer)
}
pub fn question(&mut self, name: &'n [&'n str], kind: RecordType, unicast: bool) -> Result<()> {
if self.counts.get(1).copied().unwrap_or(0) != 0 {
bail!(InvalidState)
}
self.name(name)?;
self.u16(kind.value())?;
self.u16(if unicast {
CLASS_IN | UNICAST_RESPONSE
} else {
CLASS_IN
})?;
self.bump(0)
}
pub fn answer(&mut self, record: &Record<'n>) -> Result<()> {
self.record(record)?;
self.bump(1)
}
pub fn authority(&mut self, record: &Record<'n>) -> Result<()> {
self.record(record)?;
self.bump(2)
}
pub fn additional(&mut self, record: &Record<'n>) -> Result<()> {
self.record(record)?;
self.bump(3)
}
#[must_use]
pub const fn counts(&self) -> [u16; 4] {
self.counts
}
pub fn finish(self, id: u16, flags: u16) -> Result<&'a [u8]> {
let header = [
id.to_be_bytes(),
flags.to_be_bytes(),
self.counts.first().copied().unwrap_or(0).to_be_bytes(),
self.counts.get(1).copied().unwrap_or(0).to_be_bytes(),
self.counts.get(2).copied().unwrap_or(0).to_be_bytes(),
self.counts.get(3).copied().unwrap_or(0).to_be_bytes(),
];
let slot = self.buf.get_mut(..HEADER_LEN).ok_or_else(no_space)?;
for (index, pair) in header.iter().enumerate() {
let start = index.saturating_mul(2);
let end = start.saturating_add(2);
if let Some(target) = slot.get_mut(start..end) {
target.copy_from_slice(pair);
}
}
self.buf.get(..self.at).ok_or_else(no_space)
}
fn bump(&mut self, section: usize) -> Result<()> {
let slot = self.counts.get_mut(section).ok_or_else(malformed)?;
*slot = slot.checked_add(1).ok_or_else(no_space)?;
Ok(())
}
fn record(&mut self, record: &Record<'n>) -> Result<()> {
self.name(record.name)?;
self.u16(record.data.kind().value())?;
self.u16(if record.cache_flush {
CLASS_IN | CACHE_FLUSH
} else {
CLASS_IN
})?;
self.u32(record.ttl)?;
let length_at = self.at;
self.u16(0)?;
let start = self.at;
match record.data {
RecordData::Ptr(target) => self.name(target)?,
RecordData::Srv { port, target } => {
self.u16(0)?;
self.u16(0)?;
self.u16(port)?;
self.name(target)?;
}
RecordData::Txt(bytes) => self.bytes(bytes)?,
RecordData::Aaaa(address) => self.bytes(&address)?,
RecordData::A(address) => self.bytes(&address)?,
}
let length = self.at.checked_sub(start).ok_or_else(malformed)?;
let length = u16::try_from(length).map_err(|_| no_space())?;
if let Some(slot) = self.buf.get_mut(length_at..length_at.saturating_add(2)) {
slot.copy_from_slice(&length.to_be_bytes());
}
Ok(())
}
fn name(&mut self, labels: &'n [&'n str]) -> Result<()> {
for skip in 0..labels.len() {
let tail = labels.get(skip..).unwrap_or(&[]);
if let Some(offset) = self.find(tail) {
return self.u16(0xC000 | offset);
}
let offset = u16::try_from(self.at).ok();
if let Some(offset) = offset.filter(|value| *value < 0x4000) {
let _ = self.seen.push((offset, tail));
}
let label = labels.get(skip).ok_or_else(malformed)?;
self.label(label)?;
}
self.byte(0)
}
fn find(&self, tail: &[&str]) -> Option<u16> {
self.seen
.iter()
.find(|(_, seen)| {
seen.len() == tail.len()
&& seen
.iter()
.zip(tail.iter())
.all(|(a, b)| a.as_bytes().eq_ignore_ascii_case(b.as_bytes()))
})
.map(|(offset, _)| *offset)
}
fn label(&mut self, label: &str) -> Result<()> {
let bytes = label.as_bytes();
if bytes.is_empty() || bytes.len() > LABEL_MAX {
bail!(InvalidArgument)
}
self.byte(u8::try_from(bytes.len()).map_err(|_| no_space())?)?;
self.bytes(bytes)
}
fn byte(&mut self, value: u8) -> Result<()> {
self.bytes(&[value])
}
fn u16(&mut self, value: u16) -> Result<()> {
self.bytes(&value.to_be_bytes())
}
fn u32(&mut self, value: u32) -> Result<()> {
self.bytes(&value.to_be_bytes())
}
fn bytes(&mut self, value: &[u8]) -> Result<()> {
let end = self.at.checked_add(value.len()).ok_or_else(no_space)?;
let slot = self.buf.get_mut(self.at..end).ok_or_else(no_space)?;
slot.copy_from_slice(value);
self.at = end;
Ok(())
}
}
pub const HEADER_LEN: usize = 12;
pub const FLAGS_RESPONSE: u16 = 0x8400;
pub const FLAGS_QUERY: u16 = 0x0000;
fn no_space() -> Error {
Error::new(ErrorCode::NoSpace)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Question {
pub name: Name,
pub kind: RecordType,
pub unicast: bool,
}
#[derive(Debug, Clone)]
pub struct Questions<'a> {
buf: &'a [u8],
at: usize,
left: u16,
}
impl<'a> Questions<'a> {
pub fn decode(buf: &'a [u8]) -> Result<Self> {
let header = buf.get(..HEADER_LEN).ok_or_else(truncated)?;
let count = u16::from_be_bytes([
header.get(4).copied().ok_or_else(truncated)?,
header.get(5).copied().ok_or_else(truncated)?,
]);
Ok(Self {
buf,
at: HEADER_LEN,
left: count,
})
}
#[must_use]
pub fn id(&self) -> u16 {
u16::from_be_bytes([
self.buf.first().copied().unwrap_or(0),
self.buf.get(1).copied().unwrap_or(0),
])
}
#[must_use]
pub fn is_response(&self) -> bool {
self.buf.get(2).copied().unwrap_or(0) & 0x80 != 0
}
}
impl Iterator for Questions<'_> {
type Item = Result<Question>;
fn next(&mut self) -> Option<Self::Item> {
if self.left == 0 {
return None;
}
self.left = self.left.saturating_sub(1);
Some(self.read())
}
}
impl Questions<'_> {
fn read(&mut self) -> Result<Question> {
let (name, after) = Name::decode(self.buf, self.at)?;
let kind_at = after;
let class_at = kind_at.checked_add(2).ok_or_else(malformed)?;
let end = class_at.checked_add(2).ok_or_else(malformed)?;
let kind = u16::from_be_bytes([
self.buf.get(kind_at).copied().ok_or_else(truncated)?,
self.buf
.get(kind_at.saturating_add(1))
.copied()
.ok_or_else(truncated)?,
]);
let class = u16::from_be_bytes([
self.buf.get(class_at).copied().ok_or_else(truncated)?,
self.buf
.get(class_at.saturating_add(1))
.copied()
.ok_or_else(truncated)?,
]);
self.at = end;
let kind = if class & !UNICAST_RESPONSE == CLASS_IN {
RecordType::from_value(kind)
} else {
None
};
Ok(Question {
name,
kind: kind.unwrap_or(RecordType::Nsec),
unicast: class & UNICAST_RESPONSE != 0,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Section {
Answer,
Authority,
Additional,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReadRecord<'a> {
pub section: Section,
pub class: u16,
pub name: Name,
pub kind: Option<RecordType>,
pub ttl: u32,
pub cache_flush: bool,
pub data: Option<ReadData<'a>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReadData<'a> {
Ptr(Name),
Srv {
port: u16,
target: Name,
},
Txt(&'a [u8]),
Aaaa([u8; 16]),
A([u8; 4]),
}
impl ReadData<'_> {
pub fn write_rdata<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let mut cursor = Cursor::new(buf);
match self {
Self::Ptr(target) => cursor.put_labels(target.labels())?,
Self::Srv { port, target } => {
cursor.put_u16(0)?;
cursor.put_u16(0)?;
cursor.put_u16(*port)?;
cursor.put_labels(target.labels())?;
}
Self::Txt(bytes) => cursor.put(bytes)?,
Self::Aaaa(address) => cursor.put(address)?,
Self::A(address) => cursor.put(address)?,
}
cursor.finish()
}
}
#[derive(Debug, Clone)]
pub struct ResourceRecords<'a> {
buf: &'a [u8],
at: usize,
left: [u32; 3],
stopped: bool,
}
impl<'a> ResourceRecords<'a> {
pub fn decode(buf: &'a [u8]) -> Result<Self> {
let header = buf.get(..HEADER_LEN).ok_or_else(truncated)?;
let count_at = |index: usize| -> Result<u16> {
let start = index.saturating_mul(2);
Ok(u16::from_be_bytes([
header.get(start).copied().ok_or_else(truncated)?,
header
.get(start.saturating_add(1))
.copied()
.ok_or_else(truncated)?,
]))
};
let questions = count_at(2)?;
let left = [
u32::from(count_at(3)?),
u32::from(count_at(4)?),
u32::from(count_at(5)?),
];
let mut at = HEADER_LEN;
for _ in 0..questions {
let (_, after) = Name::decode(buf, at)?;
at = after.checked_add(4).ok_or_else(malformed)?;
}
Ok(Self {
buf,
at,
left,
stopped: false,
})
}
pub fn section(self, section: Section) -> impl Iterator<Item = Result<ReadRecord<'a>>> {
self.filter(move |record| !matches!(record, Ok(record) if record.section != section))
}
}
impl<'a> Iterator for ResourceRecords<'a> {
type Item = Result<ReadRecord<'a>>;
fn next(&mut self) -> Option<Self::Item> {
if self.stopped {
return None;
}
let index = self.left.iter().position(|left| *left != 0)?;
if let Some(left) = self.left.get_mut(index) {
*left = left.saturating_sub(1);
}
let section = match index {
0 => Section::Answer,
1 => Section::Authority,
_ => Section::Additional,
};
let record = self.read(section);
self.stopped = record.is_err();
Some(record)
}
}
impl<'a> ResourceRecords<'a> {
fn read(&mut self, section: Section) -> Result<ReadRecord<'a>> {
let (name, after) = Name::decode(self.buf, self.at)?;
let be16 = |at: usize| -> Result<u16> {
Ok(u16::from_be_bytes([
self.buf.get(at).copied().ok_or_else(truncated)?,
self.buf
.get(at.saturating_add(1))
.copied()
.ok_or_else(truncated)?,
]))
};
let kind_value = be16(after)?;
let class = be16(after.checked_add(2).ok_or_else(malformed)?)?;
let ttl_at = after.checked_add(4).ok_or_else(malformed)?;
let ttl = u32::from_be_bytes([
self.buf.get(ttl_at).copied().ok_or_else(truncated)?,
self.buf
.get(ttl_at.saturating_add(1))
.copied()
.ok_or_else(truncated)?,
self.buf
.get(ttl_at.saturating_add(2))
.copied()
.ok_or_else(truncated)?,
self.buf
.get(ttl_at.saturating_add(3))
.copied()
.ok_or_else(truncated)?,
]);
let length_at = ttl_at.checked_add(4).ok_or_else(malformed)?;
let length = usize::from(be16(length_at)?);
let start = length_at.checked_add(2).ok_or_else(malformed)?;
let end = start.checked_add(length).ok_or_else(malformed)?;
let rdata = self.buf.get(start..end).ok_or_else(truncated)?;
self.at = end;
let kind = RecordType::from_value(kind_value);
let data = match kind {
Some(RecordType::Ptr) => Some(ReadData::Ptr(Name::decode(self.buf, start)?.0)),
Some(RecordType::Srv) => {
let port = be16(start.checked_add(4).ok_or_else(malformed)?)?;
let target = Name::decode(self.buf, start.checked_add(6).ok_or_else(malformed)?)?.0;
Some(ReadData::Srv { port, target })
}
Some(RecordType::Txt) => Some(ReadData::Txt(rdata)),
Some(RecordType::Aaaa) => {
let address: [u8; 16] = rdata.try_into().map_err(|_| malformed())?;
Some(ReadData::Aaaa(address))
}
Some(RecordType::A) => {
let address: [u8; 4] = rdata.try_into().map_err(|_| malformed())?;
Some(ReadData::A(address))
}
_ => None,
};
Ok(ReadRecord {
section,
class: class & !CACHE_FLUSH,
name,
kind,
ttl,
cache_flush: class & CACHE_FLUSH != 0,
data,
})
}
}