use crate::ber;
use crate::Error;
use uuid::Uuid;
pub const OID: &str = "1.2.840.113556.1.4.529";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtendedDnFormat {
Hex = 0,
Standard = 1,
}
#[derive(Debug, Clone)]
pub struct ExtendedDnRequest {
pub format: ExtendedDnFormat,
}
impl ExtendedDnRequest {
pub fn new(format: ExtendedDnFormat) -> Self {
Self { format }
}
pub fn encode(&self) -> Vec<u8> {
let mut body = Vec::with_capacity(6);
ber::write_u32(&mut body, self.format as u32);
ber::wrap_sequence(&body)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtendedDn {
pub guid: Uuid,
pub sid: Option<Vec<u8>>,
pub dn: String,
}
impl ExtendedDn {
pub fn parse(s: &str) -> Result<Self, Error> {
let rest = s
.strip_prefix("<GUID=")
.ok_or(Error::Malformed("missing <GUID= prefix"))?;
let (guid_str, rest) = rest
.split_once(">;")
.ok_or(Error::Malformed("unterminated GUID segment"))?;
let guid = parse_guid(guid_str)?;
let (sid, dn) = if let Some(after_sid_tag) = rest.strip_prefix("<SID=") {
let (sid_str, dn) = after_sid_tag
.split_once(">;")
.ok_or(Error::Malformed("unterminated SID segment"))?;
(Some(parse_sid(sid_str)?), dn.to_string())
} else {
(None, rest.to_string())
};
Ok(Self { guid, sid, dn })
}
}
fn parse_guid(s: &str) -> Result<Uuid, Error> {
if s.contains('-') {
return Uuid::parse_str(s).map_err(|_| Error::Malformed("bad GUID"));
}
if s.len() != 32 {
return Err(Error::Malformed("hex GUID must be 32 chars"));
}
let mut bytes = [0u8; 16];
for i in 0..16 {
bytes[i] = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16)
.map_err(|_| Error::Malformed("bad hex in GUID"))?;
}
bytes[0..4].reverse();
bytes[4..6].reverse();
bytes[6..8].reverse();
Ok(Uuid::from_bytes(bytes))
}
fn parse_sid(s: &str) -> Result<Vec<u8>, Error> {
Ok(s.as_bytes().to_vec())
}