2025-07-01 20:37:00 -07:00
|
|
|
use std::io::{Error, Read, Write};
|
2024-11-03 11:44:03 -08:00
|
|
|
|
|
|
|
|
/// The saslauthd protocol transmits strings as
|
|
|
|
|
/// 16-bit unsigned network-byte-order lengths followed
|
|
|
|
|
/// by the string itself.
|
|
|
|
|
///
|
|
|
|
|
pub fn read_string(stream: &mut impl Read) -> Result<String, Error> {
|
|
|
|
|
let mut length_buffer = [0u8, 0u8];
|
|
|
|
|
|
|
|
|
|
stream.read_exact(&mut length_buffer)?;
|
|
|
|
|
let length = u16::from_be_bytes(length_buffer);
|
|
|
|
|
|
|
|
|
|
let mut string_buffer = vec![0u8; length as usize];
|
|
|
|
|
|
|
|
|
|
stream.read_exact(&mut string_buffer)?;
|
|
|
|
|
|
|
|
|
|
match String::from_utf8(string_buffer) {
|
|
|
|
|
Ok(str) => Ok(str),
|
2025-07-01 20:37:00 -07:00
|
|
|
Err(_err) => Err(Error::other("Invalid UTF-8 sent")),
|
2024-11-03 11:44:03 -08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn write_string(stream: &mut impl Write, s: &str) -> Result<(), Error> {
|
|
|
|
|
let length = s.len();
|
|
|
|
|
|
|
|
|
|
if length > 0xffff {
|
2025-07-01 20:37:00 -07:00
|
|
|
return Err(Error::other("String too long to write"));
|
2024-11-03 11:44:03 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let length_buffer = [(length >> 8) as u8, (length & 0xff) as u8];
|
|
|
|
|
|
|
|
|
|
stream.write_all(&length_buffer)?;
|
|
|
|
|
stream.write_all(s.as_bytes())?;
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|