use tracing::trace;
use super::encoding::Charset;
#[inline]
pub(super) fn is_rfc2616_http_token(c: u8) -> bool {
c.is_ascii_alphanumeric()
|| matches!(
c,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
)
}
#[inline]
fn is_rfc2978_mime_charset(c: u8) -> bool {
c.is_ascii_alphanumeric()
|| matches!(
c,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'+'
| b'-'
| b'^'
| b'_'
| b'`'
| b'{'
| b'}'
| b'~'
)
}
#[inline]
fn is_rfc5987_attr_char(c: u8) -> bool {
is_rfc2616_http_token(c) && !matches!(c, b'*' | b'\'' | b'%')
}
#[inline]
fn is_lws(c: u8) -> bool {
c == b' ' || c == b'\t'
}
#[inline]
fn is_iso8859p1(c: u8) -> bool {
(0x20..=0x7e).contains(&c) || c >= 0xa0
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParseState {
BeforeDispositionType,
DispositionType,
AfterDispositionType,
BeforeParmName,
ParmName,
AfterParmName,
BeforeValue,
QuotedString,
Token,
AfterValue,
BeforeExtValue,
Charset,
Language,
ValueChars,
ValueCharsPctEncoded1,
ValueCharsPctEncoded2,
}
#[derive(Debug, Clone, Copy, Default)]
struct Flags {
filename_found: bool,
ext_filename_found: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FileTarget {
None,
Filename,
ExtFilename,
}
#[inline]
fn commit_value(flags: &mut Flags, in_file_parm: bool, target: FileTarget) {
if !in_file_parm {
return;
}
match target {
FileTarget::Filename => flags.filename_found = true,
FileTarget::ExtFilename => flags.ext_filename_found = true,
FileTarget::None => {}
}
}
pub(super) struct RawFilename {
pub filename_bytes: Vec<u8>,
pub ext_filename_bytes: Vec<u8>,
pub ext_charset: Charset,
}
pub(super) fn parse_raw(header_value: &str) -> Option<(String, RawFilename)> {
let input = header_value.as_bytes();
let mut state = ParseState::BeforeDispositionType;
let mut mark_first: usize = 0;
let mut mark_last: usize = 0;
let mut disposition_type_start: usize = 0;
let mut flags = Flags::default();
let mut disposition_type_end: usize = 0;
let mut disposition_type_started = false;
let mut filename_bytes: Vec<u8> = Vec::new();
let mut ext_filename_bytes: Vec<u8> = Vec::new();
let mut ext_charset = Charset::Unknown;
let mut in_file_parm: bool = false;
let mut quoted_seen: bool = false;
let mut pctval: u8 = 0;
let mut charset_start: usize = 0;
let mut ext_value_bytes: Vec<u8> = Vec::new();
let mut file_target = FileTarget::None;
let mut i = 0;
while i < input.len() {
let c = input[i];
match state {
ParseState::BeforeDispositionType => {
if is_rfc2616_http_token(c) {
if !disposition_type_started {
disposition_type_started = true;
disposition_type_start = i;
}
state = ParseState::DispositionType;
} else if !is_lws(c) {
trace!(
"parse_raw: unexpected byte 0x{:02x} in BeforeDispositionType",
c
);
return None;
}
}
ParseState::DispositionType | ParseState::AfterDispositionType => {
if c == b';' {
if state == ParseState::DispositionType {
disposition_type_end = i;
}
state = ParseState::BeforeParmName;
} else if is_lws(c) {
if state == ParseState::DispositionType {
disposition_type_end = i;
}
state = ParseState::AfterDispositionType;
} else if state == ParseState::AfterDispositionType || !is_rfc2616_http_token(c) {
trace!("parse_raw: unexpected byte 0x{:02x} in DispositionType", c);
return None;
}
}
ParseState::BeforeParmName => {
if is_rfc2616_http_token(c) {
mark_first = i;
state = ParseState::ParmName;
} else if !is_lws(c) {
trace!("parse_raw: unexpected byte 0x{:02x} in BeforeParmName", c);
return None;
}
}
ParseState::ParmName | ParseState::AfterParmName => {
if c == b'=' {
if state == ParseState::ParmName {
mark_last = i;
}
let parm_name = &input[mark_first..mark_last];
file_target = FileTarget::None;
in_file_parm = false;
if parm_name.eq_ignore_ascii_case(b"filename*") {
if flags.ext_filename_found {
trace!("parse_raw: duplicate filename* parameter");
return None;
}
in_file_parm = true;
file_target = FileTarget::ExtFilename;
ext_filename_bytes.clear();
state = ParseState::BeforeExtValue;
} else if parm_name.eq_ignore_ascii_case(b"filename") {
if flags.filename_found {
trace!("parse_raw: duplicate filename parameter");
return None;
}
in_file_parm = !flags.ext_filename_found;
file_target = FileTarget::Filename;
filename_bytes.clear();
state = ParseState::BeforeValue;
} else if parm_name.len() > 1 && parm_name.last() == Some(&b'*') {
state = ParseState::BeforeExtValue;
} else {
state = ParseState::BeforeValue;
}
} else if is_lws(c) {
mark_last = i;
state = ParseState::AfterParmName;
} else if state == ParseState::AfterParmName || !is_rfc2616_http_token(c) {
trace!("parse_raw: unexpected byte 0x{:02x} in ParmName", c);
return None;
}
}
ParseState::BeforeValue => {
if c == b'"' {
quoted_seen = false;
state = ParseState::QuotedString;
} else if is_rfc2616_http_token(c) {
match file_target {
FileTarget::Filename => filename_bytes.push(c),
FileTarget::ExtFilename => ext_filename_bytes.push(c),
FileTarget::None => {}
}
state = ParseState::Token;
} else if !is_lws(c) {
trace!("parse_raw: unexpected byte 0x{:02x} in BeforeValue", c);
return None;
}
}
ParseState::QuotedString => {
if c == b'\\' && !quoted_seen {
quoted_seen = true;
} else if c == b'"' && !quoted_seen {
commit_value(&mut flags, in_file_parm, file_target);
state = ParseState::AfterValue;
} else {
quoted_seen = false;
match file_target {
FileTarget::Filename => filename_bytes.push(c),
FileTarget::ExtFilename => ext_filename_bytes.push(c),
FileTarget::None => {}
}
}
}
ParseState::Token => {
if is_rfc2616_http_token(c) {
match file_target {
FileTarget::Filename => filename_bytes.push(c),
FileTarget::ExtFilename => ext_filename_bytes.push(c),
FileTarget::None => {}
}
} else if c == b';' {
commit_value(&mut flags, in_file_parm, file_target);
state = ParseState::BeforeParmName;
} else if is_lws(c) {
commit_value(&mut flags, in_file_parm, file_target);
state = ParseState::AfterValue;
} else {
trace!("parse_raw: unexpected byte 0x{:02x} in Token", c);
return None;
}
}
ParseState::AfterValue => {
if c == b';' {
state = ParseState::BeforeParmName;
} else if !is_lws(c) {
trace!("parse_raw: unexpected byte 0x{:02x} in AfterValue", c);
return None;
}
}
ParseState::BeforeExtValue => {
if c == b'\'' {
trace!("parse_raw: empty charset in filename*");
return None;
} else if is_rfc2978_mime_charset(c) {
charset_start = i;
state = ParseState::Charset;
} else if !is_lws(c) {
trace!("parse_raw: unexpected byte 0x{:02x} in BeforeExtValue", c);
return None;
}
}
ParseState::Charset => {
if c == b'\'' {
let charset_end = i;
let charset_str = &input[charset_start..charset_end];
if charset_str.eq_ignore_ascii_case(b"utf-8") {
ext_charset = Charset::Utf8;
} else if charset_str.eq_ignore_ascii_case(b"iso-8859-1") {
ext_charset = Charset::Iso8859p1;
} else {
ext_charset = Charset::Unknown;
}
state = ParseState::Language;
} else if !is_rfc2978_mime_charset(c) {
trace!("parse_raw: invalid charset byte 0x{:02x}", c);
return None;
}
}
ParseState::Language => {
if c == b'\'' {
if in_file_parm && file_target == FileTarget::ExtFilename {
ext_filename_bytes.clear();
}
ext_value_bytes.clear();
state = ParseState::ValueChars;
} else if c != b'-' && !c.is_ascii_alphanumeric() {
trace!("parse_raw: invalid language byte 0x{:02x}", c);
return None;
}
}
ParseState::ValueChars => {
if is_rfc5987_attr_char(c) {
ext_value_bytes.push(c);
match file_target {
FileTarget::Filename => filename_bytes.push(c),
FileTarget::ExtFilename => ext_filename_bytes.push(c),
FileTarget::None => {}
}
} else if c == b'%' {
pctval = 0;
state = ParseState::ValueCharsPctEncoded1;
} else if c == b';' || is_lws(c) {
if ext_charset == Charset::Utf8
&& std::str::from_utf8(&ext_value_bytes).is_err()
{
trace!("parse_raw: invalid UTF-8 in utf-8 ext-value");
return None;
}
commit_value(&mut flags, in_file_parm, file_target);
if c == b';' {
state = ParseState::BeforeParmName;
} else {
state = ParseState::AfterValue;
}
} else {
trace!("parse_raw: invalid value-char byte 0x{:02x}", c);
return None;
}
}
ParseState::ValueCharsPctEncoded1 => {
let digit = hex_digit(c);
match digit {
Some(d) => {
pctval = d << 4;
state = ParseState::ValueCharsPctEncoded2;
}
None => {
trace!("parse_raw: expected hex digit, got 0x{:02x}", c);
return None;
}
}
}
ParseState::ValueCharsPctEncoded2 => {
let digit = hex_digit(c);
match digit {
Some(d) => {
let byte = pctval | d;
if ext_charset == Charset::Iso8859p1 && !is_iso8859p1(byte) {
trace!(
"parse_raw: byte 0x{:02x} not valid in iso-8859-1 ext-value",
byte
);
return None;
}
ext_value_bytes.push(byte);
match file_target {
FileTarget::Filename => filename_bytes.push(byte),
FileTarget::ExtFilename => ext_filename_bytes.push(byte),
FileTarget::None => {}
}
state = ParseState::ValueChars;
}
None => {
trace!("parse_raw: expected hex digit, got 0x{:02x}", c);
return None;
}
}
}
}
i += 1;
}
match state {
ParseState::BeforeDispositionType
| ParseState::AfterDispositionType
| ParseState::DispositionType
| ParseState::AfterValue
| ParseState::Token => {}
ParseState::ValueChars => {
if ext_charset == Charset::Utf8 && std::str::from_utf8(&ext_value_bytes).is_err() {
trace!("parse_raw: invalid UTF-8 in utf-8 ext-value at end of input");
return None;
}
}
_ => {
trace!("parse_raw: unexpected end state {:?}", state);
return None;
}
}
if !disposition_type_started {
return None;
}
if disposition_type_end == 0 {
disposition_type_end = input.len();
}
let disposition_type =
std::str::from_utf8(&input[disposition_type_start..disposition_type_end])
.ok()?
.to_owned();
Some((
disposition_type,
RawFilename {
filename_bytes,
ext_filename_bytes,
ext_charset,
},
))
}
#[inline]
pub(super) fn hex_digit(c: u8) -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
b'A'..=b'F' => Some(c - b'A' + 10),
_ => None,
}
}