use std::fmt;
use crate::{Error, Result};
pub const fn align4(length: usize) -> usize {
match length.checked_add(3) {
Some(sum) => sum & !3,
None => usize::MAX,
}
}
pub const fn padding_for(length: usize) -> usize {
align4(length) - length
}
pub const MAX_STRING: u32 = 1024;
pub const MAX_AUTH_BODY: u32 = 400;
#[derive(Clone, PartialEq, Eq, Hash, Default)]
pub struct Utf16LeString(Vec<u8>);
impl Utf16LeString {
pub fn new(text: &str) -> Self {
let mut bytes = Vec::with_capacity(text.len() * 2);
for unit in text.encode_utf16() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
Self(bytes)
}
pub fn from_bytes(bytes: &[u8]) -> Self {
Self(bytes.to_vec())
}
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn len_bytes(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn to_string_lossy(&self) -> String {
let mut units = Vec::with_capacity(self.0.len() / 2);
let mut chunks = self.0.chunks_exact(2);
for pair in chunks.by_ref() {
let (Some(&low), Some(&high)) = (pair.first(), pair.get(1)) else {
continue;
};
units.push(u16::from_le_bytes([low, high]));
}
let mut text: String = char::decode_utf16(units)
.map(|unit| unit.unwrap_or(char::REPLACEMENT_CHARACTER))
.collect();
if !chunks.remainder().is_empty() {
text.push(char::REPLACEMENT_CHARACTER);
}
text
}
}
impl From<&str> for Utf16LeString {
fn from(text: &str) -> Self {
Self::new(text)
}
}
impl fmt::Display for Utf16LeString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_string_lossy())
}
}
impl fmt::Debug for Utf16LeString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}/{}B", self.to_string_lossy(), self.0.len())
}
}
#[derive(Clone, Default)]
pub struct Writer {
buf: Vec<u8>,
}
impl Writer {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
buf: Vec::with_capacity(capacity),
}
}
pub fn as_bytes(&self) -> &[u8] {
&self.buf
}
pub fn into_bytes(self) -> Vec<u8> {
self.buf
}
pub fn len(&self) -> usize {
self.buf.len()
}
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
pub fn u32(&mut self, value: u32) {
self.buf.extend_from_slice(&value.to_be_bytes());
}
pub fn i32(&mut self, value: i32) {
self.buf.extend_from_slice(&value.to_be_bytes());
}
pub fn u64(&mut self, value: u64) {
self.buf.extend_from_slice(&value.to_be_bytes());
}
pub fn bool(&mut self, value: bool) {
self.u32(u32::from(value));
}
pub fn raw(&mut self, data: &[u8]) {
self.buf.extend_from_slice(data);
}
fn pad_field(&mut self, field_len: usize) {
self.buf
.extend(std::iter::repeat_n(0u8, padding_for(field_len)));
}
pub fn opaque_fixed(&mut self, data: &[u8]) {
self.raw(data);
self.pad_field(data.len());
}
pub fn opaque_var(&mut self, data: &[u8]) {
self.u32(u32::try_from(data.len()).unwrap_or(u32::MAX));
self.raw(data);
self.pad_field(data.len());
}
pub fn ascii_string(&mut self, text: &str) {
let ascii: Vec<u8> = text
.chars()
.map(|c| {
if c.is_ascii() {
u8::try_from(c).unwrap_or(b'?')
} else {
b'?'
}
})
.collect();
self.opaque_var(&ascii);
}
pub fn utf16le_string(&mut self, text: &Utf16LeString) {
self.opaque_var(text.as_bytes());
}
pub fn u32_array(&mut self, values: &[u32]) {
self.u32(u32::try_from(values.len()).unwrap_or(u32::MAX));
for &value in values {
self.u32(value);
}
}
}
impl fmt::Debug for Writer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "xdr::Writer({} bytes)", self.buf.len())
}
}
#[derive(Clone)]
pub struct Reader<'a> {
data: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Self { data, pos: 0 }
}
pub fn position(&self) -> usize {
self.pos
}
pub fn remaining(&self) -> usize {
self.data.len().saturating_sub(self.pos)
}
pub fn at_end(&self) -> bool {
self.remaining() == 0
}
pub fn rest(&mut self) -> &'a [u8] {
let tail = self.data.get(self.pos..).unwrap_or(&[]);
self.pos = self.data.len();
tail
}
pub fn peek_rest(&self) -> &'a [u8] {
self.data.get(self.pos..).unwrap_or(&[])
}
fn take(&mut self, count: usize) -> Result<&'a [u8]> {
let end = self.pos.checked_add(count).ok_or(Error::Truncated {
need: count,
at: self.pos,
have: self.remaining(),
})?;
let slice = self.data.get(self.pos..end).ok_or(Error::Truncated {
need: count,
at: self.pos,
have: self.remaining(),
})?;
self.pos = end;
Ok(slice)
}
pub fn skip(&mut self, count: usize) -> Result<()> {
self.take(align4(count)).map(|_| ())
}
pub fn u32(&mut self) -> Result<u32> {
let at = self.pos;
let bytes = self.take(4)?;
let array: [u8; 4] = bytes
.try_into()
.map_err(|_| Error::malformed(at, "a four-byte read returned a short slice"))?;
Ok(u32::from_be_bytes(array))
}
pub fn i32(&mut self) -> Result<i32> {
Ok(i32::from_be_bytes(self.u32()?.to_be_bytes()))
}
pub fn u64(&mut self) -> Result<u64> {
let at = self.pos;
let bytes = self.take(8)?;
let array: [u8; 8] = bytes
.try_into()
.map_err(|_| Error::malformed(at, "an eight-byte read returned a short slice"))?;
Ok(u64::from_be_bytes(array))
}
pub fn bool(&mut self) -> Result<bool> {
Ok(self.u32()? != 0)
}
pub fn opaque_fixed(&mut self, length: usize) -> Result<&'a [u8]> {
let at = self.pos;
let padded = align4(length);
if padded > self.remaining() {
return Err(Error::Truncated {
need: padded,
at,
have: self.remaining(),
});
}
let slice = self.take(length)?;
self.take(padding_for(length))?;
Ok(slice)
}
pub fn opaque_var(&mut self, limit: u32, what: &'static str) -> Result<&'a [u8]> {
let at = self.pos;
let length = self.u32()?;
if length > limit {
self.pos = at;
return Err(Error::ImplausibleLength {
what,
length: u64::from(length),
limit: u64::from(limit),
});
}
let length = usize::try_from(length)
.map_err(|_| Error::malformed(at, "length does not fit this platform's usize"))?;
if align4(length) > self.remaining() {
let have = self.remaining();
self.pos = at;
return Err(Error::Truncated {
need: align4(length),
at: at + 4,
have,
});
}
self.opaque_fixed(length)
}
pub fn ascii_string(&mut self, limit: u32) -> Result<String> {
let bytes = self.opaque_var(limit, "an ASCII string")?;
Ok(bytes
.iter()
.map(|&b| if b.is_ascii() { char::from(b) } else { '?' })
.collect())
}
pub fn utf16le_string(&mut self, limit: u32) -> Result<Utf16LeString> {
Ok(Utf16LeString::from_bytes(
self.opaque_var(limit, "a UTF-16LE string")?,
))
}
pub fn u32_array(&mut self, limit: u32) -> Result<Vec<u32>> {
let at = self.pos;
let count = self.u32()?;
if count > limit {
self.pos = at;
return Err(Error::ImplausibleLength {
what: "an array of 32-bit words",
length: u64::from(count),
limit: u64::from(limit),
});
}
let count = usize::try_from(count)
.map_err(|_| Error::malformed(at, "count does not fit this platform's usize"))?;
if count.saturating_mul(4) > self.remaining() {
let have = self.remaining();
self.pos = at;
return Err(Error::Truncated {
need: count.saturating_mul(4),
at: at + 4,
have,
});
}
let mut values = Vec::with_capacity(count);
for _ in 0..count {
values.push(self.u32()?);
}
Ok(values)
}
}
impl fmt::Debug for Reader<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "xdr::Reader(at {} of {})", self.pos, self.data.len())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn align4_rounds_up_to_the_next_word() {
assert_eq!(
[0, 1, 3, 4, 5, 8].map(align4),
[0, 4, 4, 4, 8, 8],
"XDR pads every field up to four bytes"
);
}
#[test]
fn integers_are_big_endian() {
let mut writer = Writer::new();
writer.u32(1);
assert_eq!(writer.as_bytes(), b"\x00\x00\x00\x01");
let mut writer = Writer::new();
writer.u32(0xdead_beef);
assert_eq!(writer.as_bytes(), &[0xde, 0xad, 0xbe, 0xef]);
assert_eq!(
Reader::new(&[0xde, 0xad, 0xbe, 0xef]).u32().unwrap(),
0xdead_beef
);
}
#[test]
fn a_utf16le_prefix_counts_bytes_not_characters() {
let mut writer = Writer::new();
writer.utf16le_string(&Utf16LeString::new("/C/"));
let encoded = writer.into_bytes();
assert_eq!(
encoded.get(..4),
Some(b"\x00\x00\x00\x06".as_slice()),
"the prefix must be the BYTE count, not the character count"
);
assert_eq!(encoded.get(4..10), Some(b"/\x00C\x00/\x00".as_slice()));
assert_eq!(encoded.len(), 12);
assert_eq!(
encoded,
[
0x00, 0x00, 0x00, 0x06, 0x2f, 0x00, 0x43, 0x00, 0x2f, 0x00, 0x00, 0x00
]
);
}
#[test]
fn the_sd_export_name_encodes_as_captured() {
let mut writer = Writer::new();
writer.utf16le_string(&Utf16LeString::new("/B/"));
assert_eq!(
writer.into_bytes(),
[
0x00, 0x00, 0x00, 0x06, 0x2f, 0x00, 0x42, 0x00, 0x2f, 0x00, 0x00, 0x00
]
);
}
#[test]
fn utf16le_strings_round_trip() {
for name in ["/B/", "/C/", "/", "PIONEER", "export.pdb", "/C/EXPORT"] {
let mut writer = Writer::new();
writer.utf16le_string(&Utf16LeString::new(name));
let encoded = writer.into_bytes();
let decoded = Reader::new(&encoded).utf16le_string(MAX_STRING).unwrap();
assert_eq!(decoded.to_string_lossy(), name, "round trip of {name:?}");
}
}
#[test]
fn a_non_ascii_name_encodes_to_its_utf16le_code_units() {
let name = Utf16LeString::new("カガミ");
assert_eq!(name.as_bytes(), &[0xab, 0x30, 0xac, 0x30, 0xdf, 0x30]);
assert_eq!(name.len_bytes(), 6, "three characters, six bytes");
assert_eq!(name.to_string_lossy(), "カガミ");
}
#[test]
fn a_name_outside_the_basic_plane_uses_a_surrogate_pair() {
let name = Utf16LeString::new("🎧");
assert_eq!(name.as_bytes(), &[0x3c, 0xd8, 0xa7, 0xdf]);
assert_eq!(
name.len_bytes(),
4,
"one character, two code units, four bytes"
);
assert_eq!(name.to_string_lossy(), "🎧");
}
#[test]
fn malformed_utf16_survives_a_round_trip_rather_than_being_normalised() {
let raw = [0x3c, 0xd8, 0x41, 0x00, 0x7f];
let name = Utf16LeString::from_bytes(&raw);
assert_eq!(name.as_bytes(), raw);
assert_eq!(name.to_string_lossy(), "\u{fffd}A\u{fffd}");
let mut writer = Writer::new();
writer.utf16le_string(&name);
let encoded = writer.into_bytes();
let decoded = Reader::new(&encoded).utf16le_string(MAX_STRING).unwrap();
assert_eq!(decoded.as_bytes(), raw, "bytes must survive verbatim");
}
#[test]
fn an_ascii_string_is_not_utf16() {
let mut writer = Writer::new();
writer.ascii_string("169.254.0.0/255.255.0.0");
let encoded = writer.into_bytes();
assert_eq!(encoded.get(..4), Some(b"\x00\x00\x00\x17".as_slice()));
assert_eq!(
encoded.get(4..27),
Some(b"169.254.0.0/255.255.0.0".as_slice())
);
assert_eq!(encoded.len(), 28, "23 bytes padded to 24, plus the prefix");
}
#[test]
fn a_thirty_two_byte_filehandle_travels_bare_and_unprefixed() {
let handle: Vec<u8> = (0..32).collect();
let mut writer = Writer::new();
writer.opaque_fixed(&handle);
let encoded = writer.into_bytes();
assert_eq!(encoded, handle, "already aligned: no prefix, no padding");
assert_eq!(Reader::new(&encoded).opaque_fixed(32).unwrap(), handle);
}
#[test]
fn padding_is_skipped_rather_than_checked() {
let captured = [
0x00, 0x00, 0x00, 0x06, 0x2f, 0x00, 0x43, 0x00, 0x2f, 0x00, 0x00, 0x11,
];
let mut reader = Reader::new(&captured);
let path = reader.utf16le_string(MAX_STRING).unwrap();
assert_eq!(path.to_string_lossy(), "/C/");
assert!(
reader.at_end(),
"the two padding bytes must be consumed, whatever they hold"
);
}
#[test]
fn opaque_fixed_pads_an_unaligned_length() {
let mut writer = Writer::new();
writer.opaque_fixed(b"abc");
assert_eq!(writer.into_bytes(), b"abc\x00");
}
#[test]
fn a_field_is_padded_by_its_own_length_not_by_the_buffers() {
let mut writer = Writer::new();
writer.raw(&[0xaa]);
writer.opaque_fixed(b"abc");
assert_eq!(
writer.into_bytes(),
b"\xaaabc\x00",
"three bytes still take one byte of padding"
);
let mut writer = Writer::new();
writer.raw(&[0xaa, 0xbb, 0xcc]);
writer.opaque_var(b"ab");
assert_eq!(
writer.into_bytes(),
b"\xaa\xbb\xcc\x00\x00\x00\x02ab\x00\x00",
"two bytes still take two of padding"
);
}
#[test]
fn opaque_var_pads_to_four() {
let mut writer = Writer::new();
writer.opaque_var(b"hello");
let encoded = writer.into_bytes();
assert_eq!(encoded, b"\x00\x00\x00\x05hello\x00\x00\x00");
assert_eq!(
Reader::new(&encoded)
.opaque_var(MAX_STRING, "test")
.unwrap(),
b"hello"
);
}
#[test]
fn an_absurd_length_is_rejected_without_allocating() {
let hostile = b"\xff\xff\xff\xfftiny";
let error = Reader::new(hostile)
.opaque_var(MAX_STRING, "a UTF-16LE string")
.unwrap_err();
assert!(
matches!(error, Error::ImplausibleLength { length, .. } if length == 0xffff_ffff),
"expected ImplausibleLength, got {error:?}"
);
assert!(
!error.is_truncated(),
"a hostile prefix is not a short datagram; more bytes will not help"
);
}
#[test]
fn a_length_beyond_the_datagram_is_truncation_not_garbage() {
let short = b"\x00\x00\x01\x00only eight";
let error = Reader::new(short)
.opaque_var(MAX_STRING, "a UTF-16LE string")
.unwrap_err();
assert!(
error.is_truncated(),
"a plausible length with too few bytes means the datagram was cut short: {error:?}"
);
}
#[test]
fn a_failed_read_leaves_the_position_where_it_was() {
let mut reader = Reader::new(b"\xff\xff\xff\xfftiny");
assert!(reader.opaque_var(MAX_STRING, "test").is_err());
assert_eq!(
reader.position(),
0,
"a caller that stops at the first error must stop at the right offset"
);
}
#[test]
fn reading_past_the_end_is_truncation() {
let mut reader = Reader::new(b"\x00\x00\x00\x01");
assert_eq!(reader.u32().unwrap(), 1);
assert!(reader.at_end());
let error = reader.u32().unwrap_err();
assert!(error.is_truncated(), "got {error:?}");
}
#[test]
fn an_array_count_is_capped_before_allocating() {
let error = Reader::new(b"\xff\xff\xff\xff").u32_array(16).unwrap_err();
assert!(
matches!(error, Error::ImplausibleLength { .. }),
"{error:?}"
);
}
#[test]
fn an_empty_gid_array_is_a_bare_zero() {
let mut writer = Writer::new();
writer.u32_array(&[]);
assert_eq!(writer.as_bytes(), b"\x00\x00\x00\x00");
assert_eq!(
Reader::new(b"\x00\x00\x00\x00").u32_array(16).unwrap(),
Vec::<u32>::new()
);
}
#[test]
fn booleans_round_trip() {
for value in [true, false] {
let mut writer = Writer::new();
writer.bool(value);
assert_eq!(Reader::new(writer.as_bytes()).bool().unwrap(), value);
}
assert!(
Reader::new(b"\x00\x00\x00\x02").bool().unwrap(),
"any non-zero word is true"
);
}
#[test]
fn a_signed_word_reads_back_signed() {
let mut writer = Writer::new();
writer.i32(-1);
assert_eq!(writer.as_bytes(), b"\xff\xff\xff\xff");
assert_eq!(Reader::new(b"\xff\xff\xff\xff").i32().unwrap(), -1);
}
}