use crate::{Error, PRE_ENCAPSULATION_BOUNDARY, Result};
use core::str;
pub(crate) const CHAR_NUL: u8 = 0x00;
pub(crate) const CHAR_HT: u8 = 0x09;
pub(crate) const CHAR_SP: u8 = 0x20;
pub(crate) const CHAR_CR: u8 = 0x0d;
pub(crate) const CHAR_LF: u8 = 0x0a;
pub(crate) const CHAR_COLON: u8 = 0x3A;
pub(crate) fn is_labelchar(char: u8) -> bool {
matches!(char, 0x21..=0x2C | 0x2E..=0x7E)
}
pub(crate) fn is_allowed_in_label(char: u8) -> bool {
is_labelchar(char) || matches!(char, CHAR_HT | CHAR_SP)
}
pub(crate) fn is_wsp(char: u8) -> bool {
matches!(char, CHAR_HT | CHAR_SP)
}
pub(crate) fn strip_preamble(mut bytes: &[u8]) -> Result<&[u8]> {
if bytes.starts_with(PRE_ENCAPSULATION_BOUNDARY) {
return Ok(bytes);
}
while let Some((byte, remaining)) = bytes.split_first() {
match *byte {
CHAR_NUL => {
return Err(Error::Preamble);
}
CHAR_LF if remaining.starts_with(PRE_ENCAPSULATION_BOUNDARY) => {
return Ok(remaining);
}
_ => (),
}
bytes = remaining;
}
Err(Error::Preamble)
}
pub(crate) fn strip_leading_eol(bytes: &[u8]) -> Option<&[u8]> {
match bytes {
[CHAR_LF, rest @ ..] => Some(rest),
[CHAR_CR, CHAR_LF, rest @ ..] => Some(rest),
[CHAR_CR, rest @ ..] => Some(rest),
_ => None,
}
}
pub(crate) fn strip_trailing_eol(bytes: &[u8]) -> Option<&[u8]> {
match bytes {
[head @ .., CHAR_CR, CHAR_LF] => Some(head),
[head @ .., CHAR_LF] => Some(head),
[head @ .., CHAR_CR] => Some(head),
_ => None,
}
}
pub(crate) fn split_label(bytes: &[u8]) -> Option<(&str, &[u8])> {
let mut n = 0usize;
let mut last_was_wsp = false;
for &char in bytes {
if is_labelchar(char) {
last_was_wsp = false;
} else if char == b'-' {
break;
} else if n != 0 && is_wsp(char) {
if last_was_wsp {
return None;
}
last_was_wsp = true;
} else {
return None;
}
n = n.checked_add(1)?;
}
let (raw_label, rest) = bytes.split_at(n);
let label = str::from_utf8(raw_label).ok()?;
match rest {
[b'-', b'-', b'-', b'-', b'-', body @ ..] => Some((label, strip_leading_eol(body)?)),
_ => None,
}
}
pub(crate) fn validate_label(label: &[u8]) -> Result<()> {
let mut last_was_wsp = false;
for &char in label {
if !is_allowed_in_label(char) {
return Err(Error::Label);
}
if is_wsp(char) {
if last_was_wsp {
return Err(Error::Label);
}
last_was_wsp = true;
} else {
last_was_wsp = false;
}
}
Ok(())
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn split_label_empty() {
let (label, body) = split_label(b"-----\nBODY").unwrap();
assert_eq!(label, "");
assert_eq!(body, b"BODY");
}
#[test]
fn split_label_with_text() {
let (label, body) = split_label(b"PRIVATE KEY-----\nBODY").unwrap();
assert_eq!(label, "PRIVATE KEY");
assert_eq!(body, b"BODY");
}
#[test]
fn split_label_with_repeat_wsp_is_err() {
assert!(split_label(b"PRIVATE KEY-----\nBODY").is_none());
}
#[test]
fn validate_private_key_label() {
assert_eq!(validate_label(b"PRIVATE KEY"), Ok(()));
}
#[test]
fn validate_private_key_label_reject_double_space() {
assert_eq!(validate_label(b"PRIVATE KEY"), Err(Error::Label));
}
}