1 //! Serialization/Deserialization logic lives here
4 use alloc::string::String;
10 pub(crate) fn read_u8(inp: &mut &[u8]) -> Result<u8, ()> {
11 let res = *inp.get(0).ok_or(())?;
15 pub(crate) fn read_u16(inp: &mut &[u8]) -> Result<u16, ()> {
16 if inp.len() < 2 { return Err(()); }
17 let mut bytes = [0; 2];
18 bytes.copy_from_slice(&inp[..2]);
20 Ok(u16::from_be_bytes(bytes))
22 pub(crate) fn read_u32(inp: &mut &[u8]) -> Result<u32, ()> {
23 if inp.len() < 4 { return Err(()); }
24 let mut bytes = [0; 4];
25 bytes.copy_from_slice(&inp[..4]);
27 Ok(u32::from_be_bytes(bytes))
30 pub(crate) fn read_name(inp: &mut &[u8]) -> Result<Name, ()> {
31 let mut name = String::with_capacity(1024);
33 let len = read_u8(inp)? as usize;
35 if name.is_empty() { name += "."; }
38 if inp.len() <= len { return Err(()); }
39 name += core::str::from_utf8(&inp[..len]).map_err(|_| ())?;
42 if name.len() > 1024 { return Err(()); }
47 pub(crate) trait Writer { fn write(&mut self, buf: &[u8]); }
48 impl Writer for Vec<u8> { fn write(&mut self, buf: &[u8]) { self.extend_from_slice(buf); } }
49 impl Writer for ring::digest::Context { fn write(&mut self, buf: &[u8]) { self.update(buf); } }
50 pub(crate) fn write_name<W: Writer>(out: &mut W, name: &str) {
51 let canonical_name = name.to_ascii_lowercase();
52 if canonical_name == "." {
55 for label in canonical_name.split(".") {
56 out.write(&(label.len() as u8).to_be_bytes());
57 out.write(label.as_bytes());
61 pub(crate) fn name_len(name: &Name) -> u16 {
62 if name.as_str() == "." {
66 for label in name.split(".") {
67 res += 1 + label.len();
73 pub(crate) fn parse_rr(inp: &mut &[u8]) -> Result<RR, ()> {
74 let name = read_name(inp)?;
75 let ty = read_u16(inp)?;
76 let class = read_u16(inp)?;
77 if class != 1 { return Err(()); } // We only support the INternet
78 let _ttl = read_u32(inp)?;
79 let data_len = read_u16(inp)? as usize;
80 if inp.len() < data_len { return Err(()); }
81 let data = &inp[..data_len];
82 *inp = &inp[data_len..];
86 Ok(RR::Txt(Txt::read_from_data(name, data)?))
89 Ok(RR::CName(CName::read_from_data(name, data)?))
92 Ok(RR::TLSA(TLSA::read_from_data(name, data)?))
95 Ok(RR::DnsKey(DnsKey::read_from_data(name, data)?))
98 Ok(RR::DS(DS::read_from_data(name, data)?))
101 Ok(RR::RRSig(RRSig::read_from_data(name, data)?))
107 pub(crate) fn bytes_to_rsa_pk<'a>(pubkey: &'a [u8])
108 -> Result<signature::RsaPublicKeyComponents<&'a [u8]>, ()> {
109 if pubkey.len() <= 3 { return Err(()); }
114 exponent_length = ((pubkey[1] as usize) << 8) | (pubkey[2] as usize);
117 exponent_length = pubkey[0] as usize;
121 if pubkey.len() <= pos + exponent_length { return Err(()); }
122 Ok(signature::RsaPublicKeyComponents {
123 n: &pubkey[pos + exponent_length..],
124 e: &pubkey[pos..pos + exponent_length]