ms-dnsp 0.1.0

Pure-Rust parser and builder for the MS-DNSP dnsRecord blob stored in Active-Directory-integrated DNS zones.
Documentation
//! The two length-prefixed name encodings MS-DNSP uses inside record data.

use crate::{DnsError, Result};

/// `DNS_COUNT_NAME` — `cchNameLength`, `cLabelCount`, then length-prefixed labels ending in a
/// zero byte. Used by NS / CNAME / PTR / SOA / MX / SRV record data.
///
/// Returns the FQDN (dot-separated, no trailing dot) and advances `cur` past the structure.
pub fn read_count_name(b: &[u8], cur: &mut usize) -> Result<String> {
    let start = *cur;
    let cch = *b.get(start).ok_or(DnsError::Truncated(start))? as usize;
    let label_count = *b.get(start + 1).ok_or(DnsError::Truncated(start + 1))? as usize;
    let raw = b
        .get(start + 2..start + 2 + cch)
        .ok_or(DnsError::Truncated(start + 2))?;
    *cur = start + 2 + cch;

    let mut labels = Vec::with_capacity(label_count);
    let mut i = 0;
    while i < raw.len() {
        let len = raw[i] as usize;
        i += 1;
        if len == 0 {
            break; // root label ends the name
        }
        let label = raw.get(i..i + len).ok_or(DnsError::BadName(start))?;
        labels.push(String::from_utf8_lossy(label).into_owned());
        i += len;
    }
    if label_count != labels.len() {
        return Err(DnsError::BadName(start));
    }
    Ok(labels.join("."))
}

/// Encode an FQDN as `DNS_COUNT_NAME`.
pub fn write_count_name(out: &mut Vec<u8>, fqdn: &str) {
    let labels: Vec<&str> = fqdn.split('.').filter(|l| !l.is_empty()).collect();
    let mut raw = Vec::new();
    for l in &labels {
        raw.push(l.len() as u8);
        raw.extend_from_slice(l.as_bytes());
    }
    raw.push(0); // root
    out.push(raw.len() as u8);
    out.push(labels.len() as u8);
    out.extend_from_slice(&raw);
}

/// `DNS_RPC_NAME` — a single length-prefixed string, used by TXT and friends.
pub fn read_rpc_name(b: &[u8], cur: &mut usize) -> Result<String> {
    let start = *cur;
    let len = *b.get(start).ok_or(DnsError::Truncated(start))? as usize;
    let raw = b
        .get(start + 1..start + 1 + len)
        .ok_or(DnsError::Truncated(start + 1))?;
    *cur = start + 1 + len;
    Ok(String::from_utf8_lossy(raw).into_owned())
}

/// Encode a single `DNS_RPC_NAME` string. Strings longer than 255 bytes are truncated on a
/// character boundary — the wire format has no way to express them.
pub fn write_rpc_name(out: &mut Vec<u8>, s: &str) {
    let mut bytes = s.as_bytes();
    if bytes.len() > 255 {
        let mut end = 255;
        while end > 0 && !s.is_char_boundary(end) {
            end -= 1;
        }
        bytes = &s.as_bytes()[..end];
    }
    out.push(bytes.len() as u8);
    out.extend_from_slice(bytes);
}