#[cfg(test)]
mod textattrs_test;
use crate::attributes::*;
use crate::checks::*;
use crate::message::*;
use shared::error::*;
use std::fmt;
pub const MAX_USERNAME_B: usize = 508;
pub const MAX_TEXT_B: usize = 509;
pub const MAX_TEXT_CHARS: usize = 128;
pub const MAX_ALTERNATE_DOMAIN_B: usize = 255;
pub type Username = TextAttribute;
pub type Realm = TextAttribute;
pub type Nonce = TextAttribute;
pub type Software = TextAttribute;
pub type AlternateDomain = TextAttribute;
fn is_dns_name(name: &str) -> bool {
let name = name.strip_suffix('.').unwrap_or(name);
!name.is_empty()
&& name.len() <= MAX_ALTERNATE_DOMAIN_B
&& name.split('.').all(|label| {
(1..=63).contains(&label.len())
&& label
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
&& !label.starts_with('-')
&& !label.ends_with('-')
})
}
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub struct TextAttribute {
pub attr: AttrType,
pub text: String,
}
impl fmt::Display for TextAttribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.text)
}
}
impl Setter for TextAttribute {
fn add_to(&self, m: &mut Message) -> Result<()> {
let text = self.text.as_bytes();
let (max_len, max_chars) = match self.attr {
ATTR_USERNAME => (MAX_USERNAME_B, None),
ATTR_REALM | ATTR_SOFTWARE | ATTR_NONCE => (MAX_TEXT_B, Some(MAX_TEXT_CHARS)),
ATTR_ALTERNATE_DOMAIN => (MAX_ALTERNATE_DOMAIN_B, None),
_ => return Err(Error::Other(format!("Unsupported AttrType {}", self.attr))),
};
check_overflow(self.attr, text.len(), max_len)?;
if let Some(max_chars) = max_chars
&& self.text.chars().count() >= max_chars
{
return Err(Error::ErrAttributeSizeOverflow);
}
if self.attr == ATTR_ALTERNATE_DOMAIN && !is_dns_name(&self.text) {
return Err(Error::Other(format!(
"ALTERNATE-DOMAIN {:?} is not a DNS name",
self.text
)));
}
m.add(self.attr, text);
Ok(())
}
}
impl Getter for TextAttribute {
fn get_from(&mut self, m: &Message) -> Result<()> {
let attr = self.attr;
*self = TextAttribute::get_from_as(m, attr)?;
Ok(())
}
}
impl TextAttribute {
pub fn new(attr: AttrType, text: String) -> Self {
TextAttribute { attr, text }
}
pub fn get_from_as(m: &Message, attr: AttrType) -> Result<Self> {
match attr {
ATTR_USERNAME => {}
ATTR_REALM => {}
ATTR_SOFTWARE => {}
ATTR_NONCE => {}
ATTR_ALTERNATE_DOMAIN => {}
_ => return Err(Error::Other(format!("Unsupported AttrType {attr}"))),
};
let a = m.get(attr)?;
let text = String::from_utf8(a)?;
if attr == ATTR_ALTERNATE_DOMAIN && !is_dns_name(&text) {
return Err(Error::Other(format!(
"ALTERNATE-DOMAIN {text:?} is not a DNS name"
)));
}
Ok(TextAttribute { attr, text })
}
}