use std::fmt;
#[cfg(feature = "serde-config")]
use serde::{Deserialize, Serialize};
use crate::error::*;
use crate::rr::dnssec::Nsec3HashAlgorithm;
use crate::serialize::binary::*;
#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct NSEC3PARAM {
hash_algorithm: Nsec3HashAlgorithm,
opt_out: bool,
iterations: u16,
salt: Vec<u8>,
}
impl NSEC3PARAM {
pub fn new(
hash_algorithm: Nsec3HashAlgorithm,
opt_out: bool,
iterations: u16,
salt: Vec<u8>,
) -> Self {
Self {
hash_algorithm,
opt_out,
iterations,
salt,
}
}
pub fn hash_algorithm(&self) -> Nsec3HashAlgorithm {
self.hash_algorithm
}
pub fn opt_out(&self) -> bool {
self.opt_out
}
pub fn iterations(&self) -> u16 {
self.iterations
}
pub fn salt(&self) -> &[u8] {
&self.salt
}
pub fn flags(&self) -> u8 {
let mut flags: u8 = 0;
if self.opt_out {
flags |= 0b0000_0001
};
flags
}
}
pub fn read(decoder: &mut BinDecoder<'_>) -> ProtoResult<NSEC3PARAM> {
let hash_algorithm =
Nsec3HashAlgorithm::from_u8(decoder.read_u8()?.unverified())?;
let flags: u8 = decoder
.read_u8()?
.verify_unwrap(|flags| flags & 0b1111_1110 == 0)
.map_err(|flags| ProtoError::from(ProtoErrorKind::UnrecognizedNsec3Flags(flags)))?;
let opt_out: bool = flags & 0b0000_0001 == 0b0000_0001;
let iterations: u16 = decoder.read_u16()?.unverified();
let salt_len: usize = decoder
.read_u8()?
.map(|u| u as usize)
.verify_unwrap(|salt_len| *salt_len <= decoder.len())
.map_err(|_| ProtoError::from("salt_len exceeds buffer length"))?;
let salt: Vec<u8> = decoder.read_vec(salt_len)?.unverified();
Ok(NSEC3PARAM::new(hash_algorithm, opt_out, iterations, salt))
}
pub fn emit(encoder: &mut BinEncoder<'_>, rdata: &NSEC3PARAM) -> ProtoResult<()> {
encoder.emit(rdata.hash_algorithm().into())?;
encoder.emit(rdata.flags())?;
encoder.emit_u16(rdata.iterations())?;
encoder.emit(rdata.salt().len() as u8)?;
encoder.emit_vec(rdata.salt())?;
Ok(())
}
impl fmt::Display for NSEC3PARAM {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
let salt = if self.salt.is_empty() {
"-".to_string()
} else {
data_encoding::HEXUPPER_PERMISSIVE.encode(&self.salt)
};
write!(
f,
"{alg} {flags} {iterations} {salt}",
alg = u8::from(self.hash_algorithm),
flags = self.flags(),
iterations = self.iterations,
salt = salt
)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
use super::*;
#[test]
fn test() {
let rdata = NSEC3PARAM::new(Nsec3HashAlgorithm::SHA1, true, 2, vec![1, 2, 3, 4, 5]);
let mut bytes = Vec::new();
let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata).is_ok());
let bytes = encoder.into_bytes();
println!("bytes: {:?}", bytes);
let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
let read_rdata = read(&mut decoder).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
}