pub mod name;
use std::net::{Ipv4Addr, Ipv6Addr};
use name::{read_count_name, read_rpc_name, write_count_name, write_rpc_name};
pub const HEADER_LEN: usize = 24;
pub const VERSION: u8 = 5;
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DnsError {
#[error("truncated at offset {0}")]
Truncated(usize),
#[error("dnsRecord claims {claimed} data bytes, {actual} present")]
BadDataLength { claimed: usize, actual: usize },
#[error("malformed DNS name at offset {0}")]
BadName(usize),
#[error("record data too short for type {ty}: {len} bytes")]
ShortData { ty: u16, len: usize },
}
pub type Result<T> = std::result::Result<T, DnsError>;
pub mod ty {
pub const ZERO: u16 = 0x0000;
pub const A: u16 = 0x0001;
pub const NS: u16 = 0x0002;
pub const CNAME: u16 = 0x0005;
pub const SOA: u16 = 0x0006;
pub const PTR: u16 = 0x000C;
pub const MX: u16 = 0x000F;
pub const TXT: u16 = 0x0010;
pub const AAAA: u16 = 0x001C;
pub const SRV: u16 = 0x0021;
}
pub mod rank {
pub const CACHE_BIT: u8 = 0x01;
pub const ROOT_HINT: u8 = 0x08;
pub const OUTSIDE_GLUE: u8 = 0x20;
pub const CACHE_NA_ADDITIONAL: u8 = 0x31;
pub const CACHE_NA_AUTHORITY: u8 = 0x41;
pub const CACHE_A_ADDITIONAL: u8 = 0x51;
pub const CACHE_NA_ANSWER: u8 = 0x61;
pub const CACHE_A_AUTHORITY: u8 = 0x71;
pub const CACHE_A_ANSWER: u8 = 0xC1;
pub const GLUE: u8 = 0x80;
pub const NS_GLUE: u8 = 0x82;
pub const ZONE: u8 = 0xF0;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RecordData {
A(Ipv4Addr),
Aaaa(Ipv6Addr),
Ns(String),
Cname(String),
Ptr(String),
Soa {
serial: u32,
refresh: u32,
retry: u32,
expire: u32,
minimum_ttl: u32,
primary_server: String,
responsible_party: String,
},
Mx {
preference: u16,
exchange: String,
},
Srv {
priority: u16,
weight: u16,
port: u16,
target: String,
},
Txt(Vec<String>),
Tombstone(u64),
Unknown {
ty: u16,
bytes: Vec<u8>,
},
}
impl RecordData {
pub fn record_type(&self) -> u16 {
match self {
RecordData::A(_) => ty::A,
RecordData::Aaaa(_) => ty::AAAA,
RecordData::Ns(_) => ty::NS,
RecordData::Cname(_) => ty::CNAME,
RecordData::Ptr(_) => ty::PTR,
RecordData::Soa { .. } => ty::SOA,
RecordData::Mx { .. } => ty::MX,
RecordData::Srv { .. } => ty::SRV,
RecordData::Txt(_) => ty::TXT,
RecordData::Tombstone(_) => ty::ZERO,
RecordData::Unknown { ty, .. } => *ty,
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = Vec::new();
match self {
RecordData::A(ip) => out.extend_from_slice(&ip.octets()),
RecordData::Aaaa(ip) => out.extend_from_slice(&ip.octets()),
RecordData::Ns(n) | RecordData::Cname(n) | RecordData::Ptr(n) => {
write_count_name(&mut out, n)
}
RecordData::Soa {
serial,
refresh,
retry,
expire,
minimum_ttl,
primary_server,
responsible_party,
} => {
for v in [serial, refresh, retry, expire, minimum_ttl] {
out.extend_from_slice(&v.to_be_bytes());
}
write_count_name(&mut out, primary_server);
write_count_name(&mut out, responsible_party);
}
RecordData::Mx {
preference,
exchange,
} => {
out.extend_from_slice(&preference.to_be_bytes());
write_count_name(&mut out, exchange);
}
RecordData::Srv {
priority,
weight,
port,
target,
} => {
out.extend_from_slice(&priority.to_be_bytes());
out.extend_from_slice(&weight.to_be_bytes());
out.extend_from_slice(&port.to_be_bytes());
write_count_name(&mut out, target);
}
RecordData::Txt(strings) => {
for s in strings {
write_rpc_name(&mut out, s);
}
}
RecordData::Tombstone(t) => out.extend_from_slice(&t.to_le_bytes()),
RecordData::Unknown { bytes, .. } => out.extend_from_slice(bytes),
}
out
}
fn parse(ty: u16, b: &[u8]) -> Result<RecordData> {
let short = || DnsError::ShortData { ty, len: b.len() };
Ok(match ty {
ty::A => {
let o: [u8; 4] = b.get(..4).ok_or_else(short)?.try_into().unwrap();
RecordData::A(Ipv4Addr::from(o))
}
ty::AAAA => {
let o: [u8; 16] = b.get(..16).ok_or_else(short)?.try_into().unwrap();
RecordData::Aaaa(Ipv6Addr::from(o))
}
ty::NS => RecordData::Ns(read_count_name(b, &mut 0)?),
ty::CNAME => RecordData::Cname(read_count_name(b, &mut 0)?),
ty::PTR => RecordData::Ptr(read_count_name(b, &mut 0)?),
ty::SOA => {
if b.len() < 20 {
return Err(short());
}
let be = |i: usize| u32::from_be_bytes(b[i..i + 4].try_into().unwrap());
let mut cur = 20;
let primary_server = read_count_name(b, &mut cur)?;
let responsible_party = read_count_name(b, &mut cur)?;
RecordData::Soa {
serial: be(0),
refresh: be(4),
retry: be(8),
expire: be(12),
minimum_ttl: be(16),
primary_server,
responsible_party,
}
}
ty::MX => {
if b.len() < 2 {
return Err(short());
}
let mut cur = 2;
RecordData::Mx {
preference: u16::from_be_bytes(b[..2].try_into().unwrap()),
exchange: read_count_name(b, &mut cur)?,
}
}
ty::SRV => {
if b.len() < 6 {
return Err(short());
}
let be = |i: usize| u16::from_be_bytes(b[i..i + 2].try_into().unwrap());
let mut cur = 6;
RecordData::Srv {
priority: be(0),
weight: be(2),
port: be(4),
target: read_count_name(b, &mut cur)?,
}
}
ty::TXT => {
let mut cur = 0;
let mut strings = Vec::new();
while cur < b.len() {
strings.push(read_rpc_name(b, &mut cur)?);
}
RecordData::Txt(strings)
}
ty::ZERO => {
let o: [u8; 8] = b.get(..8).ok_or_else(short)?.try_into().unwrap();
RecordData::Tombstone(u64::from_le_bytes(o))
}
_ => RecordData::Unknown {
ty,
bytes: b.to_vec(),
},
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DnsRecord {
pub version: u8,
pub rank: u8,
pub flags: u16,
pub serial: u32,
pub ttl: u32,
pub reserved: u32,
pub timestamp: u32,
pub data: RecordData,
}
impl DnsRecord {
pub fn new(data: RecordData) -> Self {
DnsRecord {
version: VERSION,
rank: rank::ZONE,
flags: 0,
serial: 1,
ttl: 3600,
reserved: 0,
timestamp: 0,
data,
}
}
pub fn with_ttl(mut self, ttl: u32) -> Self {
self.ttl = ttl;
self
}
pub fn with_serial(mut self, serial: u32) -> Self {
self.serial = serial;
self
}
pub fn record_type(&self) -> u16 {
self.data.record_type()
}
pub fn is_static(&self) -> bool {
self.timestamp == 0
}
pub fn timestamp_unix(&self) -> Option<i64> {
(self.timestamp != 0).then(|| self.timestamp as i64 * 3600 - 11_644_473_600)
}
pub fn parse(b: &[u8]) -> Result<DnsRecord> {
if b.len() < HEADER_LEN {
return Err(DnsError::Truncated(0));
}
let u16le = |i: usize| u16::from_le_bytes(b[i..i + 2].try_into().unwrap());
let u32le = |i: usize| u32::from_le_bytes(b[i..i + 4].try_into().unwrap());
let data_len = u16le(0) as usize;
let ty = u16le(2);
let body = b.get(HEADER_LEN..).unwrap_or_default();
if body.len() < data_len {
return Err(DnsError::BadDataLength {
claimed: data_len,
actual: body.len(),
});
}
Ok(DnsRecord {
version: b[4],
rank: b[5],
flags: u16le(6),
serial: u32le(8),
ttl: u32::from_be_bytes(b[12..16].try_into().unwrap()),
reserved: u32le(16),
timestamp: u32le(20),
data: RecordData::parse(ty, &body[..data_len])?,
})
}
pub fn to_bytes(&self) -> Vec<u8> {
let data = self.data.to_bytes();
let mut out = Vec::with_capacity(HEADER_LEN + data.len());
out.extend_from_slice(&(data.len() as u16).to_le_bytes());
out.extend_from_slice(&self.record_type().to_le_bytes());
out.push(self.version);
out.push(self.rank);
out.extend_from_slice(&self.flags.to_le_bytes());
out.extend_from_slice(&self.serial.to_le_bytes());
out.extend_from_slice(&self.ttl.to_be_bytes());
out.extend_from_slice(&self.reserved.to_le_bytes());
out.extend_from_slice(&self.timestamp.to_le_bytes());
out.extend_from_slice(&data);
out
}
}