use heapless::Vec;
use super::dns::{
DnsWriter, FLAGS_QUERY, FLAGS_RESPONSE, Name, Questions, Record, RecordData, RecordType,
ResourceRecords, Section,
};
use super::{HOST_RECORD_TTL, LOCAL_DOMAIN, OTHER_RECORD_TTL, SUBTYPE_LABEL};
use crate::error::{Error, ErrorCode, Result};
pub const SUBTYPES_MAX: usize = 6;
pub const ADDRESSES_MAX: usize = 4;
pub const ADVERTISEMENTS_MAX: usize = 8;
#[derive(Debug, Clone)]
pub struct Advertisement<'a> {
pub instance: &'a str,
pub service: [&'a str; 2],
pub host: &'a str,
pub port: u16,
pub txt: &'a [u8],
pub subtypes: Vec<&'a str, SUBTYPES_MAX>,
pub addresses: Vec<[u8; 16], ADDRESSES_MAX>,
}
impl<'a> Advertisement<'a> {
#[must_use]
pub fn new(
instance: &'a str,
service: [&'a str; 2],
host: &'a str,
port: u16,
txt: &'a [u8],
) -> Self {
Self {
instance,
service,
host,
port,
txt,
subtypes: Vec::new(),
addresses: Vec::new(),
}
}
pub fn with_subtype(mut self, subtype: &'a str) -> Result<Self> {
self.subtypes
.push(subtype)
.map_err(|_| Error::new(ErrorCode::NoSpace))?;
Ok(self)
}
pub fn with_address(mut self, address: [u8; 16]) -> Result<Self> {
self.addresses
.push(address)
.map_err(|_| Error::new(ErrorCode::NoSpace))?;
Ok(self)
}
#[must_use]
pub fn service_name(&self) -> [&'a str; 3] {
[self.service[0], self.service[1], LOCAL_DOMAIN]
}
#[must_use]
pub fn instance_name(&self) -> [&'a str; 4] {
[
self.instance,
self.service[0],
self.service[1],
LOCAL_DOMAIN,
]
}
#[must_use]
pub fn host_name(&self) -> [&'a str; 2] {
[self.host, LOCAL_DOMAIN]
}
#[must_use]
pub fn subtype_name(&self, subtype: &'a str) -> [&'a str; 5] {
[
subtype,
SUBTYPE_LABEL,
self.service[0],
self.service[1],
LOCAL_DOMAIN,
]
}
}
#[derive(Debug)]
pub struct Records<'a> {
service: [&'a str; 3],
instance: [&'a str; 4],
host: [&'a str; 2],
subtypes: Vec<[&'a str; 5], SUBTYPES_MAX>,
advertisement: &'a Advertisement<'a>,
}
impl<'a> Records<'a> {
#[must_use]
pub fn new(advertisement: &'a Advertisement<'a>) -> Self {
let mut subtypes = Vec::new();
for subtype in &advertisement.subtypes {
let _ = subtypes.push(advertisement.subtype_name(subtype));
}
Self {
service: advertisement.service_name(),
instance: advertisement.instance_name(),
host: advertisement.host_name(),
subtypes,
advertisement,
}
}
#[must_use]
pub fn service_ptr(&self) -> Record<'_> {
Record {
name: &self.service,
kind: RecordType::Ptr,
ttl: OTHER_RECORD_TTL,
cache_flush: false,
data: RecordData::Ptr(&self.instance),
}
}
pub fn subtype_ptrs(&self) -> impl Iterator<Item = Record<'_>> {
self.subtypes.iter().map(|name| Record {
name,
kind: RecordType::Ptr,
ttl: OTHER_RECORD_TTL,
cache_flush: false,
data: RecordData::Ptr(&self.instance),
})
}
#[must_use]
pub fn srv(&self) -> Record<'_> {
Record {
name: &self.instance,
kind: RecordType::Srv,
ttl: HOST_RECORD_TTL,
cache_flush: true,
data: RecordData::Srv {
port: self.advertisement.port,
target: &self.host,
},
}
}
#[must_use]
pub fn txt(&self) -> Record<'_> {
Record {
name: &self.instance,
kind: RecordType::Txt,
ttl: OTHER_RECORD_TTL,
cache_flush: true,
data: RecordData::Txt(self.advertisement.txt),
}
}
pub fn addresses(&self) -> impl Iterator<Item = Record<'_>> {
self.advertisement.addresses.iter().map(|address| Record {
name: &self.host,
kind: RecordType::Aaaa,
ttl: HOST_RECORD_TTL,
cache_flush: true,
data: RecordData::Aaaa(*address),
})
}
pub fn all(&self) -> impl Iterator<Item = Record<'_>> {
core::iter::once(self.service_ptr())
.chain(self.subtype_ptrs())
.chain(core::iter::once(self.srv()))
.chain(core::iter::once(self.txt()))
.chain(self.addresses())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Responder<'a> {
pub advertisements: &'a [Advertisement<'a>],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Answered {
pub answers: usize,
pub additional: usize,
pub unicast: bool,
pub probe: bool,
}
impl Answered {
#[must_use]
pub const fn is_empty(&self) -> bool {
self.answers == 0
}
}
impl<'a> Responder<'a> {
#[must_use]
pub const fn new(advertisements: &'a [Advertisement<'a>]) -> Self {
Self { advertisements }
}
pub fn respond<'b>(&self, query: &[u8], buf: &'b mut [u8]) -> Result<(&'b [u8], Answered)> {
let questions = Questions::decode(query)?;
if questions.is_response() {
return Self::empty(buf, questions.id());
}
let mut unicast = false;
let probe = Self::is_probe(query, &questions);
let sets = Self::record_sets(self.advertisements)?;
let mut writer = DnsWriter::new(buf)?;
let mut answers = 0usize;
let mut additional = 0usize;
for records in &sets {
let mut matched_ptr = false;
let mut matched_instance = false;
for question in questions.clone() {
let question = question?;
unicast |= question.unicast;
if question.kind.answers(RecordType::Ptr) || question.kind == RecordType::Any {
if name_is(&question.name, &records.service) {
writer.answer(&records.service_ptr())?;
answers = answers.saturating_add(1);
matched_ptr = true;
}
for (index, subtype) in records.subtypes.iter().enumerate() {
if name_is(&question.name, subtype)
&& let Some(record) = records.subtype_ptrs().nth(index)
{
writer.answer(&record)?;
answers = answers.saturating_add(1);
matched_ptr = true;
}
}
}
if name_is(&question.name, &records.instance) {
if RecordType::Srv.answers(question.kind) {
writer.answer(&records.srv())?;
answers = answers.saturating_add(1);
matched_instance = true;
}
if RecordType::Txt.answers(question.kind) {
writer.answer(&records.txt())?;
answers = answers.saturating_add(1);
matched_instance = true;
}
}
if name_is(&question.name, &records.host) && RecordType::Aaaa.answers(question.kind)
{
for record in records.addresses() {
writer.answer(&record)?;
answers = answers.saturating_add(1);
}
}
}
if matched_ptr {
writer.additional(&records.srv())?;
writer.additional(&records.txt())?;
additional = additional.saturating_add(2);
}
if matched_ptr || matched_instance {
for record in records.addresses() {
writer.additional(&record)?;
additional = additional.saturating_add(1);
}
}
}
let id = questions.id();
let bytes = writer.finish(id, FLAGS_RESPONSE)?;
Ok((
bytes,
Answered {
answers,
additional,
unicast,
probe,
},
))
}
fn is_probe(query: &[u8], questions: &Questions<'_>) -> bool {
let Ok(records) = ResourceRecords::decode(query) else {
return false;
};
for record in records.section(Section::Authority) {
let Ok(record) = record else { return false };
for question in questions.clone() {
let Ok(question) = question else { return false };
if record.name == question.name
&& record.kind.is_some_and(|kind| kind.answers(question.kind))
{
return true;
}
}
}
false
}
pub fn probe<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let sets = Self::record_sets(self.advertisements)?;
let mut writer = DnsWriter::new(buf)?;
let mut asked: Vec<&[&str], { ADVERTISEMENTS_MAX * 2 }> = Vec::new();
for records in &sets {
for name in [records.instance.as_slice(), records.host.as_slice()] {
if asked.contains(&name) {
continue;
}
asked
.push(name)
.map_err(|_| Error::new(ErrorCode::NoSpace))?;
writer.question(name, RecordType::Any, true)?;
}
}
for records in &sets {
writer.authority(&records.srv())?;
writer.authority(&records.txt())?;
for record in records.addresses() {
writer.authority(&record)?;
}
}
writer.finish(0, FLAGS_QUERY)
}
pub fn announce<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let sets = Self::record_sets(self.advertisements)?;
let mut writer = DnsWriter::new(buf)?;
for records in &sets {
for record in records.all() {
writer.answer(&record)?;
}
}
writer.finish(0, FLAGS_RESPONSE)
}
pub fn goodbye<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
let sets = Self::record_sets(self.advertisements)?;
let mut writer = DnsWriter::new(buf)?;
for records in &sets {
for mut record in records.all() {
record.ttl = 0;
writer.answer(&record)?;
}
}
writer.finish(0, FLAGS_RESPONSE)
}
fn record_sets(
advertisements: &'a [Advertisement<'a>],
) -> Result<Vec<Records<'a>, ADVERTISEMENTS_MAX>> {
let mut sets = Vec::new();
for advertisement in advertisements {
sets.push(Records::new(advertisement))
.map_err(|_| Error::new(ErrorCode::NoSpace))?;
}
Ok(sets)
}
fn empty(buf: &mut [u8], id: u16) -> Result<(&[u8], Answered)> {
let writer = DnsWriter::new(buf)?;
let bytes = writer.finish(id, FLAGS_RESPONSE)?;
Ok((
bytes,
Answered {
answers: 0,
additional: 0,
unicast: false,
probe: false,
},
))
}
}
fn name_is(name: &Name, labels: &[&str]) -> bool {
name.len() == labels.len()
&& name
.labels()
.zip(labels.iter())
.all(|(a, b)| a.eq_ignore_ascii_case(b.as_bytes()))
}