mirror of
https://github.com/stalwartlabs/mail-parser.git
synced 2026-11-28 08:01:24 +00:00
MessageStream refactoring.
This commit is contained in:
@@ -26,7 +26,7 @@ impl<'x> Base64Decoder<'x> for MessageStream<'x> {
|
||||
if ch == unsafe { boundary.get_unchecked(match_count) } {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
self.set_pos(pos + match_count);
|
||||
self.set_pos(pos);
|
||||
return true;
|
||||
} else {
|
||||
continue;
|
||||
|
||||
@@ -37,11 +37,8 @@ pub fn get_charset_decoder(charset: &[u8], capacity: usize) -> Option<Box<dyn Wr
|
||||
None
|
||||
}
|
||||
|
||||
fn get_default_decoder(capacity: usize) -> Box<dyn Writer> {
|
||||
Box::new(SingleByteDecoder::new(
|
||||
SingleByteDecoder::ISO_8859_1,
|
||||
capacity,
|
||||
))
|
||||
pub fn get_default_decoder(capacity: usize) -> Box<dyn Writer> {
|
||||
SingleByteDecoder::get_iso_8859_1(capacity)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -53,6 +50,8 @@ mod tests {
|
||||
let inputs = [
|
||||
"l8",
|
||||
"utf-8",
|
||||
"US-Ascii",
|
||||
"csgb18030",
|
||||
"iso-8859-1",
|
||||
"extended_unix_code_packed_format_for_japanese",
|
||||
];
|
||||
|
||||
@@ -1,82 +1,65 @@
|
||||
pub mod map;
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
pub mod multi_byte;
|
||||
pub mod map;
|
||||
pub mod single_byte;
|
||||
pub mod utf8;
|
||||
|
||||
pub trait CharsetDecoder {
|
||||
fn ingest(&mut self, ch: &u8);
|
||||
fn ingest_slice(&mut self, chs: &[u8]) {
|
||||
for ch in chs {
|
||||
self.ingest(ch);
|
||||
}
|
||||
}
|
||||
fn to_string(&mut self) -> Option<String>;
|
||||
}
|
||||
|
||||
/*
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parser::CharsetParser;
|
||||
use super::map::get_charset_decoder;
|
||||
|
||||
#[test]
|
||||
fn decode_charset() {
|
||||
let mut parser = CharsetParser::new();
|
||||
let inputs = [
|
||||
("iso-8859-1".as_bytes(), b"\xe1\xe9\xed\xf3\xfa".to_vec(), "áéíóú"),
|
||||
("iso-8859-5".as_bytes(), b"\xbf\xe0\xd8\xd2\xd5\xe2, \xdc\xd8\xe0".to_vec(), "Привет, мир"),
|
||||
("iso-8859-6".as_bytes(), b"\xe5\xd1\xcd\xc8\xc7 \xc8\xc7\xe4\xd9\xc7\xe4\xe5".to_vec(),"مرحبا بالعالم"),
|
||||
("iso-8859-7".as_bytes(), b"\xc3\xe5\xe9\xdc \xf3\xef\xf5 \xca\xfc\xf3\xec\xe5".to_vec(),"Γειά σου Κόσμε"),
|
||||
("iso-8859-8".as_bytes(), b"\xf9\xec\xe5\xed \xf2\xe5\xec\xed".to_vec(),"שלום עולם"),
|
||||
("iso-8859-11".as_bytes(), b"\xc3\xcb\xd1\xca\xca\xd3\xcb\xc3\xd1\xba\xcd\xd1\xa1\xa2\xc3\xd0\xe4\xb7\xc2\xb7\xd5\xe8\xe3\xaa\xe9\xa1\xd1\xba\xa4\xcd\xc1\xbe\xd4\xc7\xe0\xb5\xcd\xc3\xec".to_vec(),"รหัสสำหรับอักขระไทยที่ใช้กับคอมพิวเตอร์"),
|
||||
("windows-1250".as_bytes(), b"Zelo rada grem v sla\x9a\xe8i\xe8arno".to_vec(),"Zelo rada grem v slaščičarno"),
|
||||
("windows-1251".as_bytes(), b"\xcf\xf0\xe8\xe2\xe5\xf2, \xec\xe8\xf0".to_vec(),"Привет, мир"),
|
||||
("windows-1252".as_bytes(), b"\xa1El \xf1and\xfa comi\xf3 \xf1oquis!".to_vec(),"¡El ñandú comió ñoquis!"),
|
||||
("windows-1253".as_bytes(), b"\xca\xf9\xe4\xe9\xea\xef\xdf \xd3\xf9\xea\xf1\xdc\xf4\xe7\xf2 \xf3\xf4\xef Rust".to_vec(),"Κωδικοί Σωκράτης στο Rust"),
|
||||
("windows-1254".as_bytes(), b"Kebab\xfdm\xfd baharatl\xfd yapma".to_vec(),"Kebabımı baharatlı yapma"),
|
||||
("windows-1255".as_bytes(), b"\xf9\xec\xe5\xed \xf2\xe5\xec\xed".to_vec(),"שלום עולם"),
|
||||
("windows-1256".as_bytes(), b"\xe3\xd1\xcd\xc8\xc7 \xc8\xc7\xe1\xda\xc7\xe1\xe3".to_vec(),"مرحبا بالعالم"),
|
||||
("windows-1257".as_bytes(), b"Mu h\xf5ljuk on angerjaid t\xe4is".to_vec(),"Mu hõljuk on angerjaid täis"),
|
||||
("windows-1258".as_bytes(), b"Xin ch\xe0o".to_vec(),"Xin chào"),
|
||||
("macintosh".as_bytes(), b"\x87\x8e\x92\x97\x9c".to_vec(),"áéíóú"),
|
||||
("ibm850".as_bytes(), b"\x9b\x9c\x9d\x9e".to_vec(),"ø£Ø×"),
|
||||
("koi8-r".as_bytes(), b"\xf0\xd2\xc9\xd7\xc5\xd4, \xcd\xc9\xd2".to_vec(),"Привет, мир"),
|
||||
("koi8-u".as_bytes(), b"\xf0\xd2\xc9\xd7\xa6\xd4 \xf3\xd7\xa6\xd4".to_vec(),"Привіт Світ"),
|
||||
("iso-8859-1", b"\xe1\xe9\xed\xf3\xfa".to_vec(), "áéíóú"),
|
||||
("iso-8859-5", b"\xbf\xe0\xd8\xd2\xd5\xe2, \xdc\xd8\xe0".to_vec(), "Привет, мир"),
|
||||
("iso-8859-6", b"\xe5\xd1\xcd\xc8\xc7 \xc8\xc7\xe4\xd9\xc7\xe4\xe5".to_vec(),"مرحبا بالعالم"),
|
||||
("iso-8859-7", b"\xc3\xe5\xe9\xdc \xf3\xef\xf5 \xca\xfc\xf3\xec\xe5".to_vec(),"Γειά σου Κόσμε"),
|
||||
("iso-8859-8", b"\xf9\xec\xe5\xed \xf2\xe5\xec\xed".to_vec(),"שלום עולם"),
|
||||
("iso-8859-11", b"\xc3\xcb\xd1\xca\xca\xd3\xcb\xc3\xd1\xba\xcd\xd1\xa1\xa2\xc3\xd0\xe4\xb7\xc2\xb7\xd5\xe8\xe3\xaa\xe9\xa1\xd1\xba\xa4\xcd\xc1\xbe\xd4\xc7\xe0\xb5\xcd\xc3\xec".to_vec(),"รหัสสำหรับอักขระไทยที่ใช้กับคอมพิวเตอร์"),
|
||||
("windows-1250", b"Zelo rada grem v sla\x9a\xe8i\xe8arno".to_vec(),"Zelo rada grem v slaščičarno"),
|
||||
("windows-1251", b"\xcf\xf0\xe8\xe2\xe5\xf2, \xec\xe8\xf0".to_vec(),"Привет, мир"),
|
||||
("windows-1252", b"\xa1El \xf1and\xfa comi\xf3 \xf1oquis!".to_vec(),"¡El ñandú comió ñoquis!"),
|
||||
("windows-1253", b"\xca\xf9\xe4\xe9\xea\xef\xdf \xd3\xf9\xea\xf1\xdc\xf4\xe7\xf2 \xf3\xf4\xef Rust".to_vec(),"Κωδικοί Σωκράτης στο Rust"),
|
||||
("windows-1254", b"Kebab\xfdm\xfd baharatl\xfd yapma".to_vec(),"Kebabımı baharatlı yapma"),
|
||||
("windows-1255", b"\xf9\xec\xe5\xed \xf2\xe5\xec\xed".to_vec(),"שלום עולם"),
|
||||
("windows-1256", b"\xe3\xd1\xcd\xc8\xc7 \xc8\xc7\xe1\xda\xc7\xe1\xe3".to_vec(),"مرحبا بالعالم"),
|
||||
("windows-1257", b"Mu h\xf5ljuk on angerjaid t\xe4is".to_vec(),"Mu hõljuk on angerjaid täis"),
|
||||
("windows-1258", b"Xin ch\xe0o".to_vec(),"Xin chào"),
|
||||
("macintosh", b"\x87\x8e\x92\x97\x9c".to_vec(),"áéíóú"),
|
||||
("ibm850", b"\x9b\x9c\x9d\x9e".to_vec(),"ø£Ø×"),
|
||||
("koi8-r", b"\xf0\xd2\xc9\xd7\xc5\xd4, \xcd\xc9\xd2".to_vec(),"Привет, мир"),
|
||||
("koi8-u", b"\xf0\xd2\xc9\xd7\xa6\xd4 \xf3\xd7\xa6\xd4".to_vec(),"Привіт Світ"),
|
||||
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("shift_jis".as_bytes(), b"\x83n\x83\x8D\x81[\x81E\x83\x8F\x81[\x83\x8B\x83h".to_vec(),"ハロー・ワールド"),
|
||||
("shift_jis", b"\x83n\x83\x8D\x81[\x81E\x83\x8F\x81[\x83\x8B\x83h".to_vec(),"ハロー・ワールド"),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("big5".as_bytes(), b"\xa7A\xa6n\xa1A\xa5@\xac\xc9".to_vec(),"你好,世界"),
|
||||
("big5", b"\xa7A\xa6n\xa1A\xa5@\xac\xc9".to_vec(),"你好,世界"),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("euc-jp".as_bytes(), b"\xa5\xcf\xa5\xed\xa1\xbc\xa1\xa6\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9".to_vec(),"ハロー・ワールド"),
|
||||
("euc-jp", b"\xa5\xcf\xa5\xed\xa1\xbc\xa1\xa6\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9".to_vec(),"ハロー・ワールド"),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("euc-kr".as_bytes(), b"\xbe\xc8\xb3\xe7\xc7\xcf\xbc\xbc\xbf\xe4 \xbc\xbc\xb0\xe8".to_vec(),"안녕하세요 세계"),
|
||||
("euc-kr", b"\xbe\xc8\xb3\xe7\xc7\xcf\xbc\xbc\xbf\xe4 \xbc\xbc\xb0\xe8".to_vec(),"안녕하세요 세계"),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("iso-2022-jp".as_bytes(), b"\x1b$B%O%m!<!&%o!<%k%I\x1b(B".to_vec(),"ハロー・ワールド"),
|
||||
("iso-2022-jp", b"\x1b$B%O%m!<!&%o!<%k%I\x1b(B".to_vec(),"ハロー・ワールド"),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("gbk".as_bytes(), b"\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7".to_vec(),"你好,世界"),
|
||||
("gbk", b"\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7".to_vec(),"你好,世界"),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("gb18030".as_bytes(), b"\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7".to_vec(),"你好,世界"),
|
||||
("gb18030", b"\xc4\xe3\xba\xc3\xa3\xac\xca\xc0\xbd\xe7".to_vec(),"你好,世界"),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
("utf-16".as_bytes(), b"\xff\xfe\xe1\x00\xe9\x00\xed\x00\xf3\x00\xfa\x00".to_vec(),"áéíóú"),
|
||||
("utf-16", b"\xff\xfe\xe1\x00\xe9\x00\xed\x00\xf3\x00\xfa\x00".to_vec(),"áéíóú"),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let mut decoder;
|
||||
let mut decoder = get_charset_decoder(input.0.as_bytes(), 100)
|
||||
.expect(&("Failed to find decoder for ".to_owned() + input.0));
|
||||
|
||||
for ch in input.0 {
|
||||
parser.ingest(*ch);
|
||||
}
|
||||
//parser.ingest_slice(input.0);
|
||||
decoder = parser.get_decoder(50).unwrap();
|
||||
decoder.write_bytes(&input.1);
|
||||
assert!(
|
||||
decoder.write_bytes(&input.1),
|
||||
"Failed to decode '{}'",
|
||||
input.2
|
||||
);
|
||||
|
||||
let result = decoder.get_string().unwrap();
|
||||
//println!("{}", result);
|
||||
assert_eq!(result, input.2);
|
||||
|
||||
parser.reset();
|
||||
assert_eq!(decoder.get_string().unwrap_or_else(String::new), input.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -7,7 +7,7 @@ enum HexState {
|
||||
Hex1,
|
||||
}
|
||||
|
||||
fn decode_hex(src: &[u8], dest: &mut dyn Writer) -> bool {
|
||||
pub fn decode_hex(src: &[u8], dest: &mut dyn Writer) -> bool {
|
||||
let mut state = HexState::None;
|
||||
let mut hex1 = 0;
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ pub trait Writer {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
true
|
||||
}
|
||||
|
||||
fn get_bytes(&mut self) -> Option<Box<[u8]>>;
|
||||
|
||||
@@ -37,7 +37,7 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
if ch == unsafe { boundary.get_unchecked(match_count) } {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
self.set_pos(pos + match_count);
|
||||
self.set_pos(pos);
|
||||
return true;
|
||||
} else {
|
||||
continue;
|
||||
|
||||
+59
-87
@@ -1,92 +1,64 @@
|
||||
use crate::{
|
||||
decoders::{
|
||||
base64::Base64Decoder,
|
||||
charsets::{parser::CharsetParser, utf8::Utf8Decoder, CharsetDecoder},
|
||||
charsets::map::{get_charset_decoder, get_default_decoder},
|
||||
quoted_printable::QuotedPrintableDecoder,
|
||||
Decoder, DecoderResult,
|
||||
},
|
||||
parsers::message_stream::MessageStream,
|
||||
};
|
||||
|
||||
pub enum Rfc2047Parser {
|
||||
Charset,
|
||||
Language,
|
||||
Encoding,
|
||||
}
|
||||
|
||||
pub fn parse_encoded_word(stream: &MessageStream) -> Option<String> {
|
||||
let mut ch_parser = CharsetParser::new();
|
||||
let mut ch_decoder: Option<Box<dyn CharsetDecoder>> = None;
|
||||
let mut decoder: Option<Box<dyn Decoder>> = None;
|
||||
let mut state = Rfc2047Parser::Charset;
|
||||
|
||||
while let Some(ch) = stream.next() {
|
||||
match state {
|
||||
Rfc2047Parser::Charset => match ch {
|
||||
b'?' => {
|
||||
ch_decoder = Some(
|
||||
ch_parser
|
||||
.get_decoder(75)
|
||||
.unwrap_or_else(|| Box::new(Utf8Decoder::new(75))),
|
||||
);
|
||||
state = Rfc2047Parser::Encoding;
|
||||
}
|
||||
b'*' => {
|
||||
ch_decoder = Some(
|
||||
ch_parser
|
||||
.get_decoder(75)
|
||||
.unwrap_or_else(|| Box::new(Utf8Decoder::new(75))),
|
||||
);
|
||||
state = Rfc2047Parser::Language;
|
||||
}
|
||||
b' '..=b'z' => ch_parser.ingest(*ch),
|
||||
_ => return None,
|
||||
},
|
||||
Rfc2047Parser::Language => {
|
||||
// Ignore language
|
||||
match ch {
|
||||
b'?' => state = Rfc2047Parser::Encoding,
|
||||
b'\n' | b'=' => return None,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Rfc2047Parser::Encoding => {
|
||||
if decoder.is_none() {
|
||||
match ch {
|
||||
b'q' | b'Q' => decoder = Some(Box::new(QuotedPrintableDecoder::new(true))),
|
||||
b'b' | b'B' => decoder = Some(Box::new(Base64Decoder::new())),
|
||||
_ => return None,
|
||||
}
|
||||
} else if *ch == b'?' {
|
||||
break;
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !stream.skip_byte(&b'?') {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Unwrap decoders and proceed to decode data
|
||||
let mut ch_decoder = ch_decoder?;
|
||||
let mut decoder = decoder?;
|
||||
let charset_start = stream.get_pos();
|
||||
let mut charset_end = charset_start;
|
||||
let backup_pos = charset_start - 1;
|
||||
|
||||
while let Some(ch) = stream.next() {
|
||||
match ch {
|
||||
b'?' => {
|
||||
stream.skip_byte(&b'=');
|
||||
return ch_decoder.to_string();
|
||||
if charset_end == charset_start {
|
||||
charset_end = stream.get_pos() - 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
b'\n' => return None,
|
||||
_ => match decoder.ingest(ch) {
|
||||
DecoderResult::Byte(b) => ch_decoder.ingest(&b),
|
||||
DecoderResult::ByteArray(ba) => ch_decoder.ingest_slice(ba),
|
||||
DecoderResult::NeedData => (),
|
||||
DecoderResult::Error => return None,
|
||||
},
|
||||
b'*' => {
|
||||
if charset_end == charset_start {
|
||||
charset_end = stream.get_pos() - 1;
|
||||
}
|
||||
}
|
||||
b'\n' => {
|
||||
stream.set_pos(backup_pos);
|
||||
return None;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
if !(2..=45).contains(&(charset_end - charset_start)) {
|
||||
stream.set_pos(backup_pos);
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut decoder =
|
||||
get_charset_decoder(stream.get_bytes(charset_start, charset_end).unwrap(), 80)
|
||||
.unwrap_or_else(|| get_default_decoder(80));
|
||||
|
||||
if !(match stream.next() {
|
||||
Some(b'q') | Some(b'Q') if stream.skip_byte(&b'?') => {
|
||||
stream.decode_quoted_printable(b"?=", true, decoder.as_mut())
|
||||
}
|
||||
Some(b'b') | Some(b'B') if stream.skip_byte(&b'?') => {
|
||||
stream.decode_base64(b"?=", true, decoder.as_mut())
|
||||
}
|
||||
_ => false,
|
||||
}) {
|
||||
stream.set_pos(backup_pos);
|
||||
return None;
|
||||
}
|
||||
|
||||
decoder.get_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -97,72 +69,72 @@ mod tests {
|
||||
fn decode_rfc2047() {
|
||||
let inputs = [
|
||||
(
|
||||
"iso-8859-1?q?this=20is=20some=20text?=".to_string(),
|
||||
"?iso-8859-1?q?this=20is=20some=20text?=".to_string(),
|
||||
"this is some text",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"iso-8859-1?q?this is some text?=".to_string(),
|
||||
"?iso-8859-1?q?this is some text?=".to_string(),
|
||||
"this is some text",
|
||||
true,
|
||||
),
|
||||
("US-ASCII?Q?Keith_Moore?=".to_string(), "Keith Moore", false),
|
||||
("?US-ASCII?Q?Keith_Moore?=".to_string(), "Keith Moore", false),
|
||||
(
|
||||
"iso_8859-1:1987?Q?Keld_J=F8rn_Simonsen?=".to_string(),
|
||||
"?iso_8859-1:1987?Q?Keld_J=F8rn_Simonsen?=".to_string(),
|
||||
"Keld Jørn Simonsen",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=".to_string(),
|
||||
"?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=".to_string(),
|
||||
"If you can read this yo",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=".to_string(),
|
||||
"?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=".to_string(),
|
||||
"u understand the example.",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"ISO-8859-1?Q?Olle_J=E4rnefors?=".to_string(),
|
||||
"?ISO-8859-1?Q?Olle_J=E4rnefors?=".to_string(),
|
||||
"Olle Järnefors",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?=".to_string(),
|
||||
"?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?=".to_string(),
|
||||
"Patrik Fältström",
|
||||
true,
|
||||
),
|
||||
("ISO-8859-1*?Q?a?=".to_string(), "a", true),
|
||||
("ISO-8859-1**?Q?a_b?=".to_string(), "a b", true),
|
||||
("?ISO-8859-1*?Q?a?=".to_string(), "a", true),
|
||||
("?ISO-8859-1**?Q?a_b?=".to_string(), "a b", true),
|
||||
(
|
||||
"utf-8?b?VGjDrXMgw61zIHbDoWzDrWQgw5pURjg=?=".to_string(),
|
||||
"?utf-8?b?VGjDrXMgw61zIHbDoWzDrWQgw5pURjg=?=".to_string(),
|
||||
"Thís ís válíd ÚTF8",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"utf-8*unknown?q?Th=C3=ADs_=C3=ADs_v=C3=A1l=C3=ADd_=C3=9ATF8?=".to_string(),
|
||||
"?utf-8*unknown?q?Th=C3=ADs_=C3=ADs_v=C3=A1l=C3=ADd_=C3=9ATF8?=".to_string(),
|
||||
"Thís ís válíd ÚTF8",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"Iso-8859-6?Q?=E5=D1=CD=C8=C7 =C8=C7=E4=D9=C7=E4=E5?=".to_string(),
|
||||
"?Iso-8859-6?Q?=E5=D1=CD=C8=C7 =C8=C7=E4=D9=C7=E4=E5?=".to_string(),
|
||||
"مرحبا بالعالم",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"Iso-8859-6*arabic?b?5dHNyMcgyMfk2cfk5Q==?=".to_string(),
|
||||
"?Iso-8859-6*arabic?b?5dHNyMcgyMfk2cfk5Q==?=".to_string(),
|
||||
"مرحبا بالعالم",
|
||||
true,
|
||||
),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
(
|
||||
"shift_jis?B?g26DjYFbgUWDj4Fbg4uDaA==?=".to_string(),
|
||||
"?shift_jis?B?g26DjYFbgUWDj4Fbg4uDaA==?=".to_string(),
|
||||
"ハロー・ワールド",
|
||||
true,
|
||||
),
|
||||
#[cfg(feature = "multibytedecode")]
|
||||
(
|
||||
"iso-2022-jp?q?=1B$B%O%m!<!&%o!<%k%I=1B(B?=".to_string(),
|
||||
"?iso-2022-jp?q?=1B$B%O%m!<!&%o!<%k%I=1B(B?=".to_string(),
|
||||
"ハロー・ワールド",
|
||||
true,
|
||||
),
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::parsers::{
|
||||
encoded_word::{parse_encoded_word, Rfc2047Parser},
|
||||
message_stream::MessageStream,
|
||||
};
|
||||
use crate::parsers::{encoded_word::parse_encoded_word, message_stream::MessageStream};
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
|
||||
@@ -88,7 +85,11 @@ pub struct AddressParser<'x> {
|
||||
group_comment: Option<Cow<'x, str>>,
|
||||
}
|
||||
|
||||
pub fn add_token<'x>(parser: &mut AddressParser<'x>, stream: &'x MessageStream, add_trail_space: bool) {
|
||||
pub fn add_token<'x>(
|
||||
parser: &mut AddressParser<'x>,
|
||||
stream: &'x MessageStream,
|
||||
add_trail_space: bool,
|
||||
) {
|
||||
if parser.token_start > 0 {
|
||||
let token = stream
|
||||
.get_string(
|
||||
@@ -290,8 +291,7 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
b'@' if parser.state == AddressState::Name => {
|
||||
parser.is_token_email = true;
|
||||
}
|
||||
b'=' if parser.is_token_start && !parser.is_escaped && stream.skip_byte(&b'?') => {
|
||||
let pos_back = stream.get_pos() - 1;
|
||||
b'=' if parser.is_token_start && !parser.is_escaped => {
|
||||
if let Some(token) = parse_encoded_word(stream) {
|
||||
let add_space = parser.state != AddressState::Quote; // Make borrow-checker happy
|
||||
add_token(&mut parser, stream, add_space);
|
||||
@@ -299,10 +299,10 @@ pub fn parse_address<'x>(stream: &'x MessageStream) -> AddressField<'x> {
|
||||
&mut parser.name_tokens
|
||||
} else {
|
||||
&mut parser.comment_tokens
|
||||
}).push(token.into());
|
||||
})
|
||||
.push(token.into());
|
||||
continue;
|
||||
}
|
||||
stream.set_pos(pos_back);
|
||||
}
|
||||
b' ' | b'\t' => {
|
||||
if !parser.is_token_start {
|
||||
|
||||
@@ -2,11 +2,15 @@ use std::{borrow::Cow, collections::HashMap};
|
||||
|
||||
use crate::{
|
||||
decoders::{
|
||||
charsets::{parser::CharsetParser, utf8::Utf8Decoder},
|
||||
hex::HexDecoder,
|
||||
Decoder, DecoderResult,
|
||||
charsets::{
|
||||
map::{get_charset_decoder, get_default_decoder},
|
||||
utf8::Utf8Decoder,
|
||||
},
|
||||
hex::decode_hex,
|
||||
},
|
||||
parsers::{
|
||||
encoded_word::parse_encoded_word, header::HeaderValue, message_stream::MessageStream,
|
||||
},
|
||||
parsers::{encoded_word::parse_encoded_word, message_stream::MessageStream},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
@@ -19,13 +23,6 @@ enum ContentState {
|
||||
Comment,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub struct ContentType<'x> {
|
||||
c_type: Option<Cow<'x, str>>,
|
||||
c_subtype: Option<Cow<'x, str>>,
|
||||
attributes: HashMap<Cow<'x, str>, Cow<'x, str>>,
|
||||
}
|
||||
|
||||
struct ContentTypeParser<'x> {
|
||||
state: ContentState,
|
||||
state_stack: Vec<ContentState>,
|
||||
@@ -165,25 +162,14 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &'x MessageStream)
|
||||
};
|
||||
|
||||
if let Some(charset) = parser.attributes.get(&(attr_name.clone() + "-charset")) {
|
||||
let mut decoder = CharsetParser::new();
|
||||
decoder.ingest_slice(charset.as_bytes());
|
||||
let mut charset_decoder = decoder
|
||||
.get_decoder(75)
|
||||
.unwrap_or_else(|| Box::new(Utf8Decoder::new(75)));
|
||||
let mut qp_decoder = HexDecoder::new();
|
||||
let mut decoder = get_charset_decoder(charset.as_bytes(), 80)
|
||||
.unwrap_or_else(|| get_default_decoder(80));
|
||||
|
||||
for ch in value.as_bytes() {
|
||||
match qp_decoder.ingest(ch) {
|
||||
DecoderResult::Byte(b) => charset_decoder.ingest(&b),
|
||||
DecoderResult::ByteArray(ba) => charset_decoder.ingest_slice(ba),
|
||||
DecoderResult::NeedData => (),
|
||||
DecoderResult::Error => break,
|
||||
if decode_hex(value.as_bytes(), decoder.as_mut()) {
|
||||
if let Some(result) = decoder.get_string() {
|
||||
value = result.into();
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(result) = charset_decoder.to_string() {
|
||||
value = result.into();
|
||||
}
|
||||
}
|
||||
|
||||
let value = if let Some(old_value) = parser.attributes.get(&attr_name) {
|
||||
@@ -205,7 +191,7 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &'x MessageStream)
|
||||
parser.is_token_safe = true;
|
||||
}
|
||||
|
||||
pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'x>> {
|
||||
pub fn parse_content_type<'x>(stream: &'x MessageStream) -> HeaderValue<'x> {
|
||||
let mut parser = ContentTypeParser {
|
||||
state: ContentState::Type,
|
||||
state_stack: Vec::new(),
|
||||
@@ -273,14 +259,33 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ if parser.c_type.is_some() => {
|
||||
return Some(ContentType {
|
||||
c_type: parser.c_type,
|
||||
c_subtype: parser.c_subtype,
|
||||
attributes: parser.attributes,
|
||||
});
|
||||
_ => {
|
||||
return if let Some(content_type) = parser.c_type {
|
||||
if let Some(content_subtype) = parser.c_subtype {
|
||||
if !parser.attributes.is_empty() {
|
||||
HeaderValue::Array(vec![
|
||||
HeaderValue::String(content_type),
|
||||
HeaderValue::String(content_subtype),
|
||||
HeaderValue::Map(parser.attributes),
|
||||
])
|
||||
} else {
|
||||
HeaderValue::Array(vec![
|
||||
HeaderValue::String(content_type),
|
||||
HeaderValue::String(content_subtype),
|
||||
])
|
||||
}
|
||||
} else if !parser.attributes.is_empty() {
|
||||
HeaderValue::Array(vec![
|
||||
HeaderValue::String(content_type),
|
||||
HeaderValue::Map(parser.attributes),
|
||||
])
|
||||
} else {
|
||||
HeaderValue::String(content_type)
|
||||
}
|
||||
} else {
|
||||
HeaderValue::Empty
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
b'/' if parser.state == ContentState::Type => {
|
||||
@@ -323,16 +328,12 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
continue;
|
||||
}
|
||||
ContentState::AttributeValue | ContentState::AttributeQuotedValue
|
||||
if parser.is_token_start && stream.skip_byte(&b'?') =>
|
||||
if parser.is_token_start =>
|
||||
{
|
||||
let pos_back = stream.get_pos() - 1;
|
||||
|
||||
if let Some(token) = parse_encoded_word(stream) {
|
||||
add_partial_value(&mut parser, stream, false);
|
||||
parser.values.push(token.into());
|
||||
continue;
|
||||
} else {
|
||||
stream.set_pos(pos_back);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
@@ -427,15 +428,15 @@ pub fn parse_content_type<'x>(stream: &'x MessageStream) -> Option<ContentType<'
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
HeaderValue::Empty
|
||||
}
|
||||
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use std::{borrow::Cow, collections::HashMap};
|
||||
|
||||
use crate::parsers::message_stream::MessageStream;
|
||||
use crate::parsers::{header::HeaderValue, message_stream::MessageStream};
|
||||
|
||||
use super::{parse_content_type, ContentType};
|
||||
use super::parse_content_type;
|
||||
|
||||
#[test]
|
||||
fn parse_content_fields() {
|
||||
@@ -674,17 +675,18 @@ mod tests {
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
if let Some(result) = parse_content_type(&MessageStream::new(input.0.as_bytes())) {
|
||||
let mut ct = ContentType {
|
||||
c_type: None,
|
||||
c_subtype: None,
|
||||
attributes: HashMap::new(),
|
||||
};
|
||||
let stream = MessageStream::new(input.0.as_bytes());
|
||||
let result = parse_content_type(&stream);
|
||||
let expected = if !input.1.is_empty() {
|
||||
let mut c_type: Option<Cow<str>> = None;
|
||||
let mut c_subtype: Option<Cow<str>> = None;
|
||||
let mut attributes: HashMap<Cow<str>, Cow<str>> = HashMap::new();
|
||||
|
||||
for (count, part) in input.1.split("||").enumerate() {
|
||||
match count {
|
||||
0 => ct.c_type = Some(part.into()),
|
||||
0 => c_type = Some(part.into()),
|
||||
1 => {
|
||||
ct.c_subtype = if part.is_empty() {
|
||||
c_subtype = if part.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(part.into())
|
||||
@@ -692,14 +694,41 @@ mod tests {
|
||||
}
|
||||
_ => {
|
||||
let attr: Vec<&str> = part.split("~~").collect();
|
||||
ct.attributes.insert(attr[0].into(), attr[1].into());
|
||||
attributes.insert(attr[0].into(), attr[1].into());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(result, ct, "failed for {}", input.0.escape_debug());
|
||||
|
||||
if let Some(content_type) = c_type {
|
||||
if let Some(content_subtype) = c_subtype {
|
||||
if !attributes.is_empty() {
|
||||
HeaderValue::Array(vec![
|
||||
HeaderValue::String(content_type),
|
||||
HeaderValue::String(content_subtype),
|
||||
HeaderValue::Map(attributes),
|
||||
])
|
||||
} else {
|
||||
HeaderValue::Array(vec![
|
||||
HeaderValue::String(content_type),
|
||||
HeaderValue::String(content_subtype),
|
||||
])
|
||||
}
|
||||
} else if !attributes.is_empty() {
|
||||
HeaderValue::Array(vec![
|
||||
HeaderValue::String(content_type),
|
||||
HeaderValue::Map(attributes),
|
||||
])
|
||||
} else {
|
||||
HeaderValue::String(content_type)
|
||||
}
|
||||
} else {
|
||||
HeaderValue::Empty
|
||||
}
|
||||
} else {
|
||||
assert!(input.1.is_empty(), "failed for {}", input.0.escape_debug())
|
||||
}
|
||||
HeaderValue::Empty
|
||||
};
|
||||
|
||||
assert_eq!(result, expected, "failed for '{}'", input.0.escape_debug());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-16
@@ -1,8 +1,8 @@
|
||||
use std::fmt;
|
||||
|
||||
use crate::parsers::message_stream::MessageStream;
|
||||
use crate::parsers::{header::HeaderValue, message_stream::MessageStream};
|
||||
|
||||
#[derive(PartialEq)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct DateTime {
|
||||
year: u32,
|
||||
month: u32,
|
||||
@@ -38,7 +38,7 @@ impl fmt::Display for DateTime {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<DateTime> {
|
||||
pub fn parse_date<'x>(stream: &'x MessageStream, abort_on_invalid: bool) -> HeaderValue<'x> {
|
||||
let mut pos = 0;
|
||||
let mut parts = [0u32; 7];
|
||||
let mut parts_sizes = [
|
||||
@@ -151,7 +151,7 @@ pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<Date
|
||||
}
|
||||
|
||||
if pos >= 6 {
|
||||
Some(DateTime {
|
||||
HeaderValue::DateTime(Box::new(DateTime {
|
||||
year: if (1..=99).contains(&parts[2]) {
|
||||
parts[2] + 1900
|
||||
} else {
|
||||
@@ -169,9 +169,9 @@ pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<Date
|
||||
tz_hour: parts[6] / 100,
|
||||
tz_minute: parts[6] % 100,
|
||||
tz_before_gmt: !is_plus,
|
||||
})
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
HeaderValue::Empty
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,7 +194,9 @@ pub static MONTH_MAP: &[u8] = &[
|
||||
];
|
||||
|
||||
mod tests {
|
||||
use crate::parsers::{fields::date::parse_date, message_stream::MessageStream};
|
||||
use crate::parsers::{
|
||||
fields::date::parse_date, header::HeaderValue, message_stream::MessageStream,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_dates() {
|
||||
@@ -259,15 +261,16 @@ mod tests {
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
let result = parse_date(&MessageStream::new(input.0.as_bytes()), false);
|
||||
|
||||
if !input.1.is_empty() {
|
||||
let result = result.unwrap().to_iso8601();
|
||||
//println!("{} -> {}", input.0.escape_debug(), result);
|
||||
assert_eq!(input.1, result);
|
||||
} else {
|
||||
//println!("{} -> None", input.0.escape_debug());
|
||||
assert!(result.is_none());
|
||||
match parse_date(&MessageStream::new(input.0.as_bytes()), false) {
|
||||
HeaderValue::DateTime(date) => {
|
||||
//println!("{} -> {}", input.0.escape_debug(), date.to_iso8601());
|
||||
assert_eq!(input.1, date.to_iso8601());
|
||||
}
|
||||
HeaderValue::Empty => {
|
||||
//println!("{} -> None", input.0.escape_debug());
|
||||
assert!(input.1.is_empty());
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+38
-35
@@ -1,15 +1,8 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::parsers::message_stream::MessageStream;
|
||||
use crate::parsers::{header::HeaderValue, message_stream::MessageStream};
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum IdField<'x> {
|
||||
One(Cow<'x, str>),
|
||||
Many(Vec<Cow<'x, str>>),
|
||||
Empty,
|
||||
}
|
||||
|
||||
pub fn parse_id<'x>(stream: &'x MessageStream) -> IdField<'x> {
|
||||
pub fn parse_id<'x>(stream: &'x MessageStream) -> HeaderValue<'x> {
|
||||
let mut token_start: usize = 0;
|
||||
let mut token_end: usize = 0;
|
||||
let mut is_token_safe = true;
|
||||
@@ -25,9 +18,9 @@ pub fn parse_id<'x>(stream: &'x MessageStream) -> IdField<'x> {
|
||||
}
|
||||
_ => {
|
||||
return match ids.len() {
|
||||
1 => IdField::One(ids.pop().unwrap()),
|
||||
0 => IdField::Empty,
|
||||
_ => IdField::Many(ids),
|
||||
1 => ids.pop().unwrap(),
|
||||
0 => HeaderValue::Empty,
|
||||
_ => HeaderValue::Array(ids),
|
||||
};
|
||||
}
|
||||
},
|
||||
@@ -38,14 +31,12 @@ pub fn parse_id<'x>(stream: &'x MessageStream) -> IdField<'x> {
|
||||
b'>' => {
|
||||
is_id_part = false;
|
||||
if token_start > 0 {
|
||||
let bytes = stream.get_bytes(token_start - 1, token_end).unwrap();
|
||||
|
||||
ids.push(if is_token_safe {
|
||||
Cow::from(unsafe { std::str::from_utf8_unchecked(bytes) })
|
||||
} else {
|
||||
is_token_safe = true;
|
||||
String::from_utf8_lossy(bytes)
|
||||
});
|
||||
ids.push(HeaderValue::String(
|
||||
stream
|
||||
.get_string(token_start - 1, token_end, is_token_safe)
|
||||
.unwrap(),
|
||||
));
|
||||
is_token_safe = true;
|
||||
token_start = 0;
|
||||
} else {
|
||||
continue;
|
||||
@@ -66,54 +57,66 @@ pub fn parse_id<'x>(stream: &'x MessageStream) -> IdField<'x> {
|
||||
token_end = stream.get_pos();
|
||||
}
|
||||
}
|
||||
IdField::Empty
|
||||
HeaderValue::Empty
|
||||
}
|
||||
|
||||
mod tests {
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::parsers::{
|
||||
fields::id::{parse_id, IdField},
|
||||
message_stream::MessageStream,
|
||||
fields::id::parse_id, header::HeaderValue, message_stream::MessageStream,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn parse_message_ids() {
|
||||
let inputs = [
|
||||
(
|
||||
"<1234@local.machine.example>\n".to_string(),
|
||||
"<1234@local.machine.example>\n",
|
||||
vec!["1234@local.machine.example"],
|
||||
),
|
||||
(
|
||||
"<1234@local.machine.example> <3456@example.net>\n".to_string(),
|
||||
"<1234@local.machine.example> <3456@example.net>\n",
|
||||
vec!["1234@local.machine.example", "3456@example.net"],
|
||||
),
|
||||
(
|
||||
"<1234@local.machine.example>\n <3456@example.net> \n".to_string(),
|
||||
"<1234@local.machine.example>\n <3456@example.net> \n",
|
||||
vec!["1234@local.machine.example", "3456@example.net"],
|
||||
),
|
||||
(
|
||||
"<1234@local.machine.example>\n\n <3456@example.net>\n".to_string(),
|
||||
"<1234@local.machine.example>\n\n <3456@example.net>\n",
|
||||
vec!["1234@local.machine.example"],
|
||||
),
|
||||
(
|
||||
" <testabcd.1234@silly.test> \n".to_string(),
|
||||
" <testabcd.1234@silly.test> \n",
|
||||
vec!["testabcd.1234@silly.test"],
|
||||
),
|
||||
(
|
||||
"<5678.21-Nov-1997@example.com>\n".to_string(),
|
||||
"<5678.21-Nov-1997@example.com>\n",
|
||||
vec!["5678.21-Nov-1997@example.com"],
|
||||
),
|
||||
(
|
||||
"<1234 @ local(blah) .machine .example>\n".to_string(),
|
||||
"<1234 @ local(blah) .machine .example>\n",
|
||||
vec!["1234 @ local(blah) .machine .example"],
|
||||
),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
match parse_id(&MessageStream::new(input.0.as_bytes())) {
|
||||
IdField::One(val) => assert_eq!(val, *input.1.first().unwrap()),
|
||||
IdField::Many(val) => assert_eq!(val, input.1),
|
||||
IdField::Empty => panic!("Failed to parse '{}'", input.0),
|
||||
}
|
||||
assert_eq!(
|
||||
if input.1.len() == 1 {
|
||||
HeaderValue::String((*input.1.first().unwrap()).into())
|
||||
} else {
|
||||
HeaderValue::Array(
|
||||
input
|
||||
.1
|
||||
.iter()
|
||||
.map(|x| HeaderValue::String(Cow::Borrowed(x)))
|
||||
.collect::<Vec<HeaderValue>>(),
|
||||
)
|
||||
},
|
||||
parse_id(&MessageStream::new(input.0.as_bytes())),
|
||||
"Failed to parse '{}'",
|
||||
input.0
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::parsers::{encoded_word::parse_encoded_word, message_stream::MessageStream};
|
||||
pub struct UnstructuredParser<'x> {
|
||||
use crate::parsers::{encoded_word::parse_encoded_word, header::HeaderValue, message_stream::MessageStream};
|
||||
struct UnstructuredParser<'x> {
|
||||
token_start: usize,
|
||||
token_end: usize,
|
||||
is_token_safe: bool,
|
||||
@@ -9,7 +9,7 @@ pub struct UnstructuredParser<'x> {
|
||||
tokens: Vec<Cow<'x, str>>,
|
||||
}
|
||||
|
||||
pub fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &'x MessageStream, add_space: bool) {
|
||||
fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &'x MessageStream, add_space: bool) {
|
||||
if parser.token_start > 0 {
|
||||
if !parser.tokens.is_empty() {
|
||||
parser.tokens.push(" ".into());
|
||||
@@ -34,7 +34,7 @@ pub fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &'x MessageStr
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>> {
|
||||
pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> HeaderValue<'x> {
|
||||
let mut parser = UnstructuredParser {
|
||||
token_start: 0,
|
||||
token_end: 0,
|
||||
@@ -58,9 +58,9 @@ pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>>
|
||||
}
|
||||
_ => {
|
||||
return match parser.tokens.len() {
|
||||
1 => parser.tokens.pop(),
|
||||
0 => None,
|
||||
_ => Some(parser.tokens.concat().into()),
|
||||
1 => HeaderValue::String(parser.tokens.pop().unwrap()),
|
||||
0 => HeaderValue::Empty,
|
||||
_ => HeaderValue::String(parser.tokens.concat().into()),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -71,15 +71,11 @@ pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>>
|
||||
}
|
||||
continue;
|
||||
}
|
||||
b'=' if parser.is_token_start && stream.skip_byte(&b'?') => {
|
||||
let pos_back = stream.get_pos() - 1;
|
||||
|
||||
b'=' if parser.is_token_start => {
|
||||
if let Some(token) = parse_encoded_word(stream) {
|
||||
add_token(&mut parser, stream, true);
|
||||
parser.tokens.push(token.into());
|
||||
continue;
|
||||
} else {
|
||||
stream.set_pos(pos_back);
|
||||
}
|
||||
}
|
||||
b'\r' => continue,
|
||||
@@ -102,16 +98,16 @@ pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>>
|
||||
parser.token_end = stream.get_pos();
|
||||
}
|
||||
|
||||
None
|
||||
HeaderValue::Empty
|
||||
}
|
||||
|
||||
mod tests {
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::parsers::{fields::unstructured::parse_unstructured, message_stream::MessageStream};
|
||||
|
||||
#[test]
|
||||
fn parse_unstructured_text() {
|
||||
use std::borrow::Cow;
|
||||
use crate::parsers::{fields::unstructured::parse_unstructured, header::HeaderValue, message_stream::MessageStream};
|
||||
|
||||
let inputs = [
|
||||
("Saying Hello\n".to_string(), "Saying Hello", true),
|
||||
("Re: Saying Hello\r\n".to_string(), "Re: Saying Hello", true),
|
||||
@@ -138,7 +134,7 @@ mod tests {
|
||||
|
||||
for input in inputs {
|
||||
match parse_unstructured(&MessageStream::new(input.0.as_bytes())) {
|
||||
Some(cow) => {
|
||||
HeaderValue::String(cow) => {
|
||||
assert_eq!(cow, input.1);
|
||||
if let Cow::Borrowed(_) = cow {
|
||||
assert!(
|
||||
@@ -156,7 +152,7 @@ mod tests {
|
||||
//println!("'{}' -> Owned", cow);
|
||||
}
|
||||
}
|
||||
None => panic!("Failed to parse '{}'", input.0),
|
||||
_ => panic!("Failed to parse '{}'", input.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+163
-166
@@ -1,210 +1,207 @@
|
||||
use std::borrow::Cow;
|
||||
use std::{borrow::Cow, collections::HashMap};
|
||||
|
||||
use crate::parsers::fields::address::{Address, AddressList};
|
||||
use crate::parsers::message_stream::MessageStream;
|
||||
|
||||
use super::fields::unstructured::parse_unstructured;
|
||||
use super::fields::date::DateTime;
|
||||
|
||||
pub enum Header<'x> {
|
||||
/*Sender(Address),
|
||||
From(Address),
|
||||
To(AddressList),
|
||||
Cc(AddressList),
|
||||
Bcc(AddressList),*/
|
||||
Subject(Cow<'x, str>),
|
||||
Other((&'x str, &'x str)),
|
||||
pub struct Message<'x> {
|
||||
subject: Option<Cow<'x, str>>,
|
||||
}
|
||||
|
||||
impl<'x> Header<'x> {
|
||||
pub fn parse(stream: &'x MessageStream) -> Option<Header<'x>> {
|
||||
while let Some(name) = Header::parse_hdr_name(stream) {
|
||||
let mut hash = name.len();
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum HeaderValue<'x> {
|
||||
Empty,
|
||||
DateTime(Box<DateTime>),
|
||||
String(Cow<'x, str>),
|
||||
Array(Vec<HeaderValue<'x>>),
|
||||
Map(HashMap<Cow<'x, str>, Cow<'x, str>>),
|
||||
}
|
||||
|
||||
if !(2..=25).contains(&hash) {
|
||||
return None;
|
||||
}
|
||||
pub trait MessageHeader<'x> {
|
||||
|
||||
hash += unsafe {
|
||||
*HDR_HASH.get_unchecked(name.get_unchecked(0).to_ascii_lowercase() as usize)
|
||||
as usize
|
||||
+ *HDR_HASH
|
||||
.get_unchecked(name.get_unchecked(hash - 1).to_ascii_lowercase() as usize)
|
||||
as usize
|
||||
};
|
||||
fn set_subject(&mut self, stream: &'x MessageStream);
|
||||
fn set_from(&mut self, stream: &'x MessageStream);
|
||||
|
||||
if !(2..=44).contains(&hash) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
match hash - 2 {
|
||||
0 if name.eq_ignore_ascii_case(b"cc") => {
|
||||
println!("Got 'cc'");
|
||||
}
|
||||
1 if name.eq_ignore_ascii_case(b"bcc") => {
|
||||
println!("Got 'bcc'");
|
||||
}
|
||||
7 if name.eq_ignore_ascii_case(b"resent-cc") => {
|
||||
println!("Got 'resent-cc'");
|
||||
}
|
||||
8 if name.eq_ignore_ascii_case(b"resent-bcc") => {
|
||||
println!("Got 'resent-bcc'");
|
||||
}
|
||||
9 if name.eq_ignore_ascii_case(b"resent-date") => {
|
||||
println!("Got 'resent-date'");
|
||||
}
|
||||
10 if name.eq_ignore_ascii_case(b"content-type") => {
|
||||
println!("Got 'content-type'");
|
||||
}
|
||||
11 if name.eq_ignore_ascii_case(b"resent-sender") => {
|
||||
println!("Got 'resent-sender'");
|
||||
}
|
||||
12 if name.eq_ignore_ascii_case(b"date") => {
|
||||
println!("Got 'date'");
|
||||
}
|
||||
13 if name.eq_ignore_ascii_case(b"list-owner") => {
|
||||
println!("Got 'list-owner'");
|
||||
}
|
||||
14 if name.eq_ignore_ascii_case(b"resent-from") => {
|
||||
println!("Got 'resent-from'");
|
||||
}
|
||||
15 if name.eq_ignore_ascii_case(b"list-archive") => {
|
||||
println!("Got 'list-archive'");
|
||||
}
|
||||
16 if name.eq_ignore_ascii_case(b"received") => {
|
||||
println!("Got 'received'");
|
||||
}
|
||||
17 if name.eq_ignore_ascii_case(b"list-subscribe") => {
|
||||
println!("Got 'list-subscribe'");
|
||||
}
|
||||
18 if name.eq_ignore_ascii_case(b"content-id") => {
|
||||
println!("Got 'content-id'");
|
||||
}
|
||||
19 if name.eq_ignore_ascii_case(b"list-unsubscribe") => {
|
||||
println!("Got 'list-unsubscribe'");
|
||||
}
|
||||
22 if name.eq_ignore_ascii_case(b"list-post") => {
|
||||
println!("Got 'list-post'");
|
||||
}
|
||||
23 if name.eq_ignore_ascii_case(b"message-id") => {
|
||||
println!("Got 'message-id'");
|
||||
}
|
||||
24 if name.eq_ignore_ascii_case(b"sender") => {
|
||||
println!("Got 'sender'");
|
||||
}
|
||||
25 if name.eq_ignore_ascii_case(b"resent-message-id") => {
|
||||
println!("Got 'resent-message-id'");
|
||||
}
|
||||
26 if name.eq_ignore_ascii_case(b"comments") => {
|
||||
println!("Got 'comments'");
|
||||
}
|
||||
27 if name.eq_ignore_ascii_case(b"list-help") => {
|
||||
println!("Got 'list-help'");
|
||||
}
|
||||
28 if name.eq_ignore_ascii_case(b"references") => {
|
||||
println!("Got 'references'");
|
||||
}
|
||||
29 if name.eq_ignore_ascii_case(b"return-path") => {
|
||||
println!("Got 'return-path'");
|
||||
}
|
||||
30 if name.eq_ignore_ascii_case(b"mime-version") => {
|
||||
println!("Got 'mime-version'");
|
||||
}
|
||||
31 if name.eq_ignore_ascii_case(b"keywords") => {
|
||||
println!("Got 'keywords'");
|
||||
}
|
||||
// content disposition!
|
||||
32 if name.eq_ignore_ascii_case(b"content-description") => {
|
||||
println!("Got 'content-description'");
|
||||
}
|
||||
33 if name.eq_ignore_ascii_case(b"content-transfer-encoding") => {
|
||||
println!("Got 'content-transfer-encoding'");
|
||||
}
|
||||
35 if name.eq_ignore_ascii_case(b"subject") => {
|
||||
println!("Got 'subject'");
|
||||
}
|
||||
36 if name.eq_ignore_ascii_case(b"reply-to") => {
|
||||
println!("Got 'reply-to'");
|
||||
}
|
||||
37 if name.eq_ignore_ascii_case(b"resent-to") => {
|
||||
println!("Got 'resent-to'");
|
||||
}
|
||||
39 if name.eq_ignore_ascii_case(b"in-reply-to") => {
|
||||
println!("Got 'in-reply-to'");
|
||||
}
|
||||
40 if name.eq_ignore_ascii_case(b"to") => {
|
||||
println!("Got 'to'");
|
||||
}
|
||||
42 if name.eq_ignore_ascii_case(b"from") => {
|
||||
println!("Got 'from'");
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
enum HeaderParserResult<'x, T> {
|
||||
Supported(HeaderParserFnc<'x, T>),
|
||||
Unsupported(&'x [u8]),
|
||||
Eof,
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
type HeaderParserFnc<'x, T> = fn(&'x mut T, &MessageStream<'x>);
|
||||
|
||||
pub fn parse_hdr_name(stream: &'x MessageStream) -> Option<&'x [u8]> {
|
||||
let mut token_start: usize = 0;
|
||||
let mut token_end: usize = 0;
|
||||
pub fn parse_headers<'x>(stream: &'x MessageStream) {
|
||||
|
||||
while let Some(ch) = stream.next() {
|
||||
match ch {
|
||||
b':' => {
|
||||
if token_start != 0 {
|
||||
return stream.get_bytes(token_start - 1, token_end);
|
||||
}
|
||||
|
||||
|
||||
fn parse_header_name<'x, T>(stream: &'x MessageStream) -> HeaderParserResult<'x, T> {
|
||||
let mut token_start: usize = 0;
|
||||
let mut token_end: usize = 0;
|
||||
let mut token_len: usize = 0;
|
||||
let mut token_hash: usize = 0;
|
||||
let mut last_ch: u8 = 0;
|
||||
|
||||
while let Some(ch) = stream.next() {
|
||||
match ch {
|
||||
b':' => {
|
||||
if token_start != 0 {
|
||||
let field = stream.get_bytes(token_start - 1, token_end).unwrap();
|
||||
|
||||
if (2..=25).contains(&token_len) {
|
||||
token_hash += token_len
|
||||
+ unsafe {
|
||||
*HDR_HASH.get_unchecked(last_ch.to_ascii_lowercase() as usize)
|
||||
} as usize;
|
||||
|
||||
if (4..=62).contains(&token_hash) {
|
||||
let token_hash = token_hash - 4;
|
||||
|
||||
if field.eq_ignore_ascii_case(unsafe {
|
||||
HDR_NAMES.get_unchecked(token_hash)
|
||||
}) {
|
||||
println!("Supported '{}'", std::str::from_utf8(field).unwrap());
|
||||
return HeaderParserResult::Eof;
|
||||
}
|
||||
}
|
||||
}
|
||||
return HeaderParserResult::Unsupported(field);
|
||||
}
|
||||
b' ' | b'\n' | b'\r' => (),
|
||||
_ => {
|
||||
}
|
||||
b'\n' => {
|
||||
if token_start == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if !(*ch).is_ascii_whitespace() {
|
||||
if token_start == 0 {
|
||||
token_start = stream.get_pos();
|
||||
token_end = token_start;
|
||||
} else {
|
||||
token_end = stream.get_pos();
|
||||
last_ch = *ch;
|
||||
}
|
||||
|
||||
token_end = stream.get_pos();
|
||||
if let 0 | 9 = token_len {
|
||||
token_hash +=
|
||||
unsafe { *HDR_HASH.get_unchecked((*ch).to_ascii_lowercase() as usize) }
|
||||
as usize;
|
||||
}
|
||||
token_len += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
HeaderParserResult::Eof
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::parsers::{header::Header, message_stream::MessageStream};
|
||||
use crate::parsers::{header::parse_header_name, message_stream::MessageStream};
|
||||
|
||||
#[test]
|
||||
fn parse_field_name() {
|
||||
fn header_name_parse() {
|
||||
let inputs = [
|
||||
("From: ".to_string(), "from"),
|
||||
("\n\n \nreceived-FROM: ".to_string(), "received-from"),
|
||||
("\n\n \nreceiVED: ".to_string(), "received"),
|
||||
(" subject : ".to_string(), "subject"),
|
||||
("X-Custom-Field : ".to_string(), "x-custom-field"),
|
||||
(" T : ".to_string(), "t"),
|
||||
("mal formed: ".to_string(), "mal formed"),
|
||||
("MIME-version : ".to_string(), "x-custom-field"),
|
||||
];
|
||||
|
||||
for input in inputs {
|
||||
match Header::parse_hdr_name(&MessageStream::new(input.0.as_bytes())) {
|
||||
Some(string) => {
|
||||
assert_eq!(input.1, std::str::from_utf8(string).unwrap().to_lowercase())
|
||||
}
|
||||
None => panic!("Failed to parse '{}'", input.0),
|
||||
}
|
||||
unreachable!();
|
||||
/*match parse_header_name(&MessageStream::new(input.0.as_bytes())) {
|
||||
super::HeaderParserResult::Supported(_) => (),
|
||||
super::HeaderParserResult::Unsupported(_) => (),
|
||||
super::HeaderParserResult::Eof => (),
|
||||
}*/
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static HDR_HASH: &[u8] = &[
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 0, 0, 10, 0, 35, 10, 20, 0, 45, 5, 5, 5, 15, 30, 15, 45, 0, 20, 10, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 20, 5, 0, 0, 0, 0, 5, 5, 63, 15, 15, 25, 20, 10, 0, 63, 0, 0, 15, 63, 63, 63, 63, 20,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63,
|
||||
];
|
||||
|
||||
/*static HDR_FNCS: &[for<'r, 's> fn(&'r mut T, &MessageStream<'s>)] = &[
|
||||
MessageHeader::set_subject,
|
||||
MessageHeader::set_from,
|
||||
];*/
|
||||
|
||||
static HDR_NAMES: &[&[u8]] = &[
|
||||
b"date",
|
||||
b"",
|
||||
b"sender",
|
||||
b"",
|
||||
b"received",
|
||||
b"",
|
||||
b"references",
|
||||
b"",
|
||||
b"cc",
|
||||
b"comments",
|
||||
b"resent-cc",
|
||||
b"content-id",
|
||||
b"",
|
||||
b"resent-message-id",
|
||||
b"reply-to",
|
||||
b"resent-to",
|
||||
b"resent-bcc",
|
||||
b"",
|
||||
b"subject",
|
||||
b"keywords",
|
||||
b"list-help",
|
||||
b"list-owner",
|
||||
b"resent-date",
|
||||
b"to",
|
||||
b"bcc",
|
||||
b"from",
|
||||
b"content-transfer-encoding",
|
||||
b"return-path",
|
||||
b"list-archive",
|
||||
b"resent-sender",
|
||||
b"list-subscribe",
|
||||
b"message-id",
|
||||
b"",
|
||||
b"content-type",
|
||||
b"",
|
||||
b"list-post",
|
||||
b"",
|
||||
b"in-reply-to",
|
||||
b"",
|
||||
b"",
|
||||
b"content-description",
|
||||
b"",
|
||||
b"resent-from",
|
||||
b"",
|
||||
b"",
|
||||
b"content-disposition",
|
||||
b"",
|
||||
b"list-unsubscribe",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"",
|
||||
b"mime-version",
|
||||
];
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
//pub mod encoded_word;
|
||||
//pub mod fields;
|
||||
//pub mod header;
|
||||
pub mod encoded_word;
|
||||
pub mod fields;
|
||||
pub mod header;
|
||||
pub mod message_stream;
|
||||
|
||||
Reference in New Issue
Block a user