Unstructured field parser.

This commit is contained in:
Mauro D
2021-10-07 15:14:42 +00:00
parent 9876382d2a
commit f70ff1f95e
9 changed files with 553 additions and 333 deletions
+3 -3
View File
@@ -1,7 +1,8 @@
pub mod parser;
pub mod single_byte;
#[cfg(feature = "multibytedecode")]
pub mod multi_byte;
pub mod parser;
pub mod single_byte;
pub mod utf8;
pub trait CharsetDecoder {
fn ingest(&mut self, ch: &u8);
@@ -77,4 +78,3 @@ mod tests {
}
}
}
+98
View File
@@ -0,0 +1,98 @@
use std::char::REPLACEMENT_CHARACTER;
use super::CharsetDecoder;
enum Utf8State {
Start,
Shift12,
Shift6,
Shift0
}
pub struct Utf8Decoder {
state: Utf8State,
char: u32,
result: String,
}
impl CharsetDecoder for Utf8Decoder {
fn ingest(&mut self, ch: &u8) {
match self.state {
Utf8State::Start => {
if *ch < 0x80 {
self.result.push(unsafe{ char::from_u32_unchecked(*ch as u32) });
} else if (*ch & 0xe0) == 0xc0 {
self.char = (*ch as u32 & 0x1f) << 6;
self.state = Utf8State::Shift0;
} else if (*ch & 0xf0) == 0xe0 {
self.char = (*ch as u32 & 0x0f) << 12;
self.state = Utf8State::Shift6;
} else if (*ch & 0xf8) == 0xf0 && (*ch <= 0xf4) {
self.char = (*ch as u32 & 0x07) << 18;
self.state = Utf8State::Shift12;
} else {
self.result.push(REPLACEMENT_CHARACTER);
}
},
Utf8State::Shift12 => {
self.char |= (*ch as u32 & 0x3f) << 12;
self.state = Utf8State::Shift6;
},
Utf8State::Shift6 => {
self.char |= (*ch as u32 & 0x3f) << 6;
self.state = Utf8State::Shift0;
},
Utf8State::Shift0 => {
self.char |= *ch as u32 & 0x3f;
self.state = Utf8State::Start;
self.result.push(char::from_u32(self.char).unwrap_or(REPLACEMENT_CHARACTER));
self.char = 0;
},
}
}
fn to_string(&mut self) -> Option<String> {
if !self.result.is_empty() {
Some(std::mem::take(&mut self.result))
} else {
None
}
}
}
impl Utf8Decoder {
pub fn new(capacity: usize) -> Utf8Decoder {
Utf8Decoder {
result: String::with_capacity(capacity),
state: Utf8State::Start,
char: 0
}
}
}
#[cfg(test)]
mod tests {
use crate::decoders::charsets::CharsetDecoder;
use super::Utf8Decoder;
#[test]
fn decode_utf8() {
let inputs = [
(b"Lorem ipsum".to_vec(), "Lorem ipsum"),
(b"Th\xc3\xads \xc3\xads v\xc3\xa1l\xc3\xadd \xc3\x9aTF8".to_vec(), "Thís ís válíd ÚTF8"),
(b"\xe3\x83\x8f\xe3\x83\xad\xe3\x83\xbc\xe3\x83\xbb\xe3\x83\xaf\xe3\x83\xbc\xe3\x83\xab\xe3\x83\x89".to_vec(), "ハロー・ワールド"),
(b"\xec\x95\x88\xeb\x85\x95\xed\x95\x98\xec\x84\xb8\xec\x9a\x94 \xec\x84\xb8\xea\xb3\x84".to_vec(), "안녕하세요 세계"),
(b"love: \xe2\x9d\xa4\xef\xb8\x8f".to_vec(), "love: ❤️"),
(b"\xec \x95\x88 \xeb\x85\x95 \xed\x95\x98\xec\x84\xb8 \xec\x9a\x94 \xec\x84\xb8\xea\xb3 \x84".to_vec(), "정� 녕 하세 요 세고�"),
];
for input in inputs {
let mut parser = Utf8Decoder::new(10);
parser.ingest_slice(&input.0);
assert_eq!(parser.to_string().unwrap(), input.1);
}
}
}
+14 -7
View File
@@ -44,7 +44,7 @@ mod decoders;
headers: Vec<Header<'x>>,
}*/
use crate::parsers::message_stream::MessageStream;
use crate::parsers::header::Header;
//use crate::parsers::header::Header;
static HEX_TO_VAL: &'static [i8] = &[
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
@@ -85,17 +85,24 @@ fn main() {
)
.to_string();
//let mut parser = MessageStream::new(unsafe { mail.as_bytes_mut() });
unsafe {
let counter: usize = 0;
//let mut parser = MessageStream::new(mail.into_bytes().into_boxed_slice() );
//let hdr = Header::parse(&mut parser);
}
/*let coco = mail.as_bytes();
let pepe = "coco".as_bytes();
for ch in coco {
let t = pepe.iter();
println!("{:?}", std::str::from_utf8(&coco[1..3]).unwrap());
}*/
/*while let Some(&ch) = parser.next_test() {
println!("{}", std::str::from_utf8(parser.get_bytes(1, 3).unwrap()).unwrap());
println!("{}", ch);
}*/
/*static HASH_VALUES: &'static [i8] =
+136 -36
View File
@@ -1,64 +1,164 @@
use std::borrow::{Borrow, Cow};
use std::borrow::Cow;
use crate::parsers::{message_stream::MessageStream, rfc2047::Rfc2047Parser};
enum UnstructState {
enum UnstructuredState {
Lf,
Space,
Char
Char,
}
pub fn parse_unstructured<'x>(stream: &'x mut MessageStream) -> Option<Cow<'x, str>> {
let mut token_start: isize = -1;
let mut token_end: isize = -1;
let mut state = UnstructState::Space;
//let mut tokens = Vec::new();
fn add_token<'x>(
mut tokens: Vec<Cow<'x, str>>,
stream: &'x MessageStream,
token_start: usize,
token_end: usize,
is_token_safe: bool,
) -> Vec<Cow<'x, str>> {
let bytes = stream.get_bytes(token_start - 1, token_end).unwrap();
while let Some(ch) = stream.next_mut() {
if !tokens.is_empty() {
tokens.push(Cow::from(" ".to_string()));
}
tokens.push(if is_token_safe {
Cow::from(unsafe { std::str::from_utf8_unchecked(bytes) })
} else {
String::from_utf8_lossy(bytes)
});
tokens
}
pub fn parse_unstructured<'x>(stream: &'x MessageStream) -> Option<Cow<'x, str>> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut is_token_safe = true;
let mut state = UnstructuredState::Space;
let mut tokens: Vec<Cow<str>> = Vec::new();
while let Some(ch) = stream.next() {
match ch {
b'\n' => {
if let UnstructState::Lf = state {
if let UnstructuredState::Lf = state {
stream.rewind(1);
break;
} else if token_start > 0 {
tokens = add_token(tokens, stream, token_start, token_end, is_token_safe);
token_start = 0;
is_token_safe = true;
}
state = UnstructState::Lf;
token_start = -1;
},
state = UnstructuredState::Lf;
}
b' ' | b'\t' | b'\r' => {
state = UnstructState::Space;
},
state = UnstructuredState::Space;
}
_ => {
if *ch > 126 {
*ch = b'!';
if *ch > 0x7f && is_token_safe {
is_token_safe = false;
}
match state {
UnstructState::Lf => {
UnstructuredState::Lf => {
stream.rewind(1);
break;
},
UnstructState::Space => {
if token_start == -1 {
//token_start = stream.get_read_pos();
}
/*if *ch == b'=' && stream.skip_byte(b'?') {
tokens.push(stream.end_write());
if let Some(_) = Rfc2047Parser::parse(stream) {
tokens.push(stream.end_write());
token_start = -1;
break;
}
UnstructuredState::Space => {
if *ch == b'=' && stream.skip_byte(&b'?') {
let pos_back = stream.get_pos() - 1;
if let Some(token) = Rfc2047Parser::parse(stream) {
if token_start > 0 {
tokens = add_token(
tokens,
stream,
token_start,
token_end,
is_token_safe,
);
tokens.push(Cow::from(" ".to_string()));
token_start = 0;
is_token_safe = true;
}
tokens.push(Cow::from(token));
state = UnstructuredState::Space;
continue;
} else {
stream.set_pos(pos_back);
}
}*/
}
state = UnstructuredState::Char;
},
UnstructState::Char => todo!(),
if token_start == 0 {
token_start = stream.get_pos();
token_end = stream.get_pos()
}
}
UnstructuredState::Char => token_end = stream.get_pos(),
}
}
}
}
None
match tokens.len() {
1 => tokens.pop(),
0 => None,
_ => Some(Cow::from(tokens.concat())),
}
}
mod tests {
use std::borrow::Cow;
use crate::parsers::{fields::unstructured::parse_unstructured, message_stream::MessageStream};
#[test]
fn test_unstructured() {
let inputs = [
("Saying Hello\n".to_string(), "Saying Hello", true),
("Re: Saying Hello\r\n".to_string(), "Re: Saying Hello", true),
(" Fwd: \n\tSaying \n Hello\r\n".to_string(), "Fwd: Saying Hello", false),
(" FWD: \n Saying Hello \nX-Mailer: 123\r\n".to_string(), "FWD: Saying Hello", false),
(" from x.y.test\n by example.net\n via TCP\n with ESMTP\n id ABC12345\n for <mary@example.net>; 21 Nov 1997 10:05:43 -0600\n".to_string(), "from x.y.test by example.net via TCP with ESMTP id ABC12345 for <mary@example.net>; 21 Nov 1997 10:05:43 -0600", false),
("=?iso-8859-1?q?this is some text?=\n".to_string(), "this is some text", false),
("=?iso-8859-1?q?this=20is=20some=20text?=\r\n".to_string(), "this is some text", false),
(" =?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=\n =?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=\n".to_string(), "If you can read this you understand the example.", false),
(" =?ISO-8859-1?Q?a?=\n".to_string(), "a", false),
("=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=\n".to_string(), "ab", false),
("=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=\n".to_string(), "ab", false),
("=?ISO-8859-1?Q?a?=\r\n =?ISO-8859-1?Q?b?=\nFrom: unknown@domain.com\n".to_string(), "ab", false),
("=?ISO-8859-1?Q?a_b?=\n".to_string(), "a b", false),
("=?ISO-8859-1?Q?a?= =?ISO-8859-2?Q?_b?=\r\n".to_string(), "a b", false),
(" this =?iso-8859-1?q?is?= some =?iso-8859-1?q?t?=\n =?iso-8859-1?q?e?= \n =?iso-8859-1?q?x?=\n =?iso-8859-1?q?t?=\n".to_string(), "this is some text", false),
(" =\n".to_string(), "=", true),
(" =? \n".to_string(), "=?", true),
("=?utf-8 \n".to_string(), "=?utf-8", true),
("=?utf-8? \n".to_string(), "=?utf-8?", true),
(" let's = try =?iso-8859-1? to break\n =? the \n parser\n".to_string(), "let's = try =?iso-8859-1? to break =? the parser", false),
("ハロー・ワールド \n".to_string(), "ハロー・ワールド", true),
];
for input in inputs {
match parse_unstructured(&MessageStream::new(input.0.as_bytes())) {
Some(cow) => {
assert_eq!(cow, input.1);
if let Cow::Borrowed(_) = cow {
assert!(
input.2,
"Expected Owned but received Borrowed string '{}'.",
cow
);
//println!("'{}' -> Borrowed", cow);
} else {
assert!(
!input.2,
"Expected Borrowed but received Owned string '{}'.",
cow
);
//println!("'{}' -> Owned", cow);
}
}
None => panic!("Failed to parse '{}'", input.0),
}
}
}
}
+149 -82
View File
@@ -6,94 +6,162 @@ use crate::parsers::message_stream::MessageStream;
use super::fields::unstructured::parse_unstructured;
pub enum Header<'x> {
Sender(Address<'x>),
From(Address<'x>),
To(AddressList<'x>),
Cc(AddressList<'x>),
Bcc(AddressList<'x>),
/*Sender(Address),
From(Address),
To(AddressList),
Cc(AddressList),
Bcc(AddressList),*/
Subject(Cow<'x, str>),
Other((&'x str, &'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();
pub fn parse(stream: &'x mut MessageStream) -> Option<Header<'x>> {
while let Some(header) = Header::parse_hdr_name(stream) {
match header {
(0, b"cc") => {}
(1, b"bcc") => {}
(7, b"resent-cc") => {}
(8, b"resent-bcc") => {}
(9, b"resent-date") => {}
(10, b"content-type") => {}
(11, b"resent-sender") => {}
(12, b"date") => {}
(13, b"list-owner") => {}
(14, b"resent-from") => {}
(15, b"list-archive") => {}
(16, b"received") => {}
(17, b"list-subscribe") => {}
(18, b"content-id") => {}
(19, b"list-unsubscribe") => {}
(22, b"list-post") => {}
(23, b"message-id") => {}
(24, b"sender") => {}
(25, b"resent-message-id") => {}
(26, b"comments") => {}
(27, b"list-help") => {}
(28, b"references") => {}
(29, b"return-path") => {}
(30, b"mime-version") => {}
(31, b"keywords") => {}
(32, b"content-description") => {}
(33, b"content-transfer-encoding") => {}
(35, b"subject") => return Some(Header::Subject(parse_unstructured(stream)?)),
(36, b"reply-to") => {}
(37, b"resent-to") => {}
(39, b"in-reply-to") => {}
(40, b"to") => {}
(42, b"from") => {}
_ => ()
if !(2..=25).contains(&hash) {
return None;
}
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
};
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'");
}
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,
}
}
None
}
pub fn parse_hdr_name(stream: &'x mut MessageStream) -> Option<(u32, &'x [u8])> {
let mut started = false;
let mut first_ch: u8 = 0;
let mut last_ch: u8 = 0;
pub fn parse_hdr_name(stream: &'x MessageStream) -> Option<&'x [u8]> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
while let Some(ch) = stream.next_mut() {
while let Some(ch) = stream.next() {
match ch {
b':' => {
if started {
return Some((
stream.get_written_bytes() as u32
+ unsafe {
*HDR_HASH.get_unchecked(first_ch as usize) as u32
+ *HDR_HASH.get_unchecked(last_ch as usize) as u32
},
stream.end_write().unwrap(),
));
if token_start != 0 {
return stream.get_bytes(token_start - 1, token_end);
}
}
b' ' | b'\n' | b'\r' => (),
_ => {
if ch.is_ascii_uppercase() {
*ch += 32;
if token_start == 0 {
token_start = stream.get_pos();
}
if !started {
first_ch = *ch;
stream.begin_write();
started = true;
} else {
last_ch = *ch;
}
stream.write_skip();
token_end = stream.get_pos();
}
}
}
@@ -107,22 +175,21 @@ mod tests {
#[test]
fn parse_field_name() {
unsafe {
let inputs = [
("From: ".to_string(), "from"),
("\n\n \nreceived-FROM: ".to_string(), "received-from"),
(" subject : ".to_string(), "subject"),
("X-Custom-Field : ".to_string(), "x-custom-field"),
("mal formed: ".to_string(), "mal forme"), // Not expected to parse this
];
let inputs = [
("From: ".to_string(), "from"),
("\n\n \nreceived-FROM: ".to_string(), "received-from"),
(" subject : ".to_string(), "subject"),
("X-Custom-Field : ".to_string(), "x-custom-field"),
(" T : ".to_string(), "t"),
("mal formed: ".to_string(), "mal formed"),
];
for input in inputs {
match Header::parse_hdr_name(&mut MessageStream::new(
input.0.clone().as_bytes_mut(),
)) {
Some((_, string)) => assert_eq!(input.1, std::str::from_utf8(string).unwrap()),
None => panic!("Failed to parse '{}'", input.0),
}
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),
}
}
}
+32 -87
View File
@@ -1,121 +1,66 @@
use std::{borrow::{Borrow}, cell::Cell};
use std::cell::Cell;
pub struct MessageStream<'x> {
data: &'x [u8],
read_pos: isize,
write_pos: usize,
write_start: usize,
test: Cell<usize>
pos: Cell<usize>
}
impl<'x> MessageStream<'x> {
pub fn new(data: &[u8]) -> MessageStream {
pub fn new(data: &'x [u8]) -> MessageStream<'x> {
MessageStream {
data,
read_pos: -1,
write_pos: 0,
write_start: 0,
test: Cell::new(0)
pos: Cell::new(0)
}
}
#[inline(always)]
pub fn get_bytes(&self, from: usize, to: usize) -> Option<&[u8]> {
self.test.set(1);
self.data.get(from..to)
}
#[inline(always)]
pub fn begin_write(&mut self) {
if self.read_pos > 0 {
self.write_pos = self.read_pos as usize;
self.write_start = self.read_pos as usize;
}
pub fn set_pos(&self, pos: usize) {
self.pos.set(pos)
}
#[inline(always)]
pub fn write(&mut self, ch: u8) {
//self.data[self.write_pos] = ch;
self.write_pos += 1;
pub fn get_pos(&self) -> usize {
self.pos.get()
}
#[inline(always)]
pub fn write_slice(&mut self, chars: &[u8]) {
//self.data[self.write_pos..(self.write_pos+chars.len())].copy_from_slice(chars);
self.write_pos += chars.len();
pub fn next(&self) -> Option<&u8> {
let pos = self.pos.get();
self.pos.set(pos + 1);
self.data.get(pos)
}
#[inline(always)]
pub fn write_skip(&mut self) {
self.write_pos += 1;
}
#[inline(always)]
pub fn end_write(&self) -> Option<&[u8]> {
self.data.get(self.write_start..self.write_pos)
}
#[inline(always)]
pub fn get_written_bytes(&self) -> isize {
self.write_pos as isize - self.write_start as isize
}
#[inline(always)]
pub fn get_read_pos(&self) -> isize {
self.read_pos
}
#[inline(always)]
pub fn get_write_pos(&self) -> usize {
self.write_pos
}
#[inline(always)]
pub fn next(&mut self) -> Option<&u8> {
self.read_pos += 1;
self.data.get(self.read_pos as usize)
}
#[inline(always)]
pub fn next_mut(&mut self) -> Option<&mut u8> {
self.read_pos += 1;
None
//self.data.get_mut(self.read_pos as usize)
}
pub fn skip_byte(&mut self, ch: u8) -> bool {
match self.data.get((self.read_pos as usize) + 1) {
Some(x) if *x == ch => {
self.read_pos += 1;
pub fn skip_byte(&self, ch: &u8) -> bool {
let pos = self.pos.get();
match self.data.get(pos) {
Some(byte) if byte == ch => {
self.pos.set(pos + 1);
true
},
_ => false,
_ => false
}
}
pub fn skip_bytes(&mut self, chs: &[u8]) -> bool {
let next_pos = (self.read_pos as usize) + 1;
match self.data.get(next_pos..next_pos+chs.len()) {
Some(x) if x == chs => {
self.read_pos += chs.len() as isize;
pub fn skip_bytes(&self, chs: &[u8]) -> bool {
let from = self.pos.get();
let to = from + chs.len();
match self.data.get(from..to) {
Some(bytes) if bytes == chs => {
self.pos.set(to);
true
},
_ => false,
}
_ => false
}
}
/*pub fn skip_spaces(&mut self) -> Option<&u8> {
loop {
self.read_pos += 1;
let ch = self.data.get(self.read_pos as usize)?;
if !ch.is_ascii_whitespace() {
return Some(ch);
}
}
}*/
pub fn rewind(&mut self, read_pos: usize) {
self.read_pos = self.read_pos - std::cmp::min(self.read_pos, read_pos as isize);
pub fn rewind(&self, r: usize) {
let pos = self.pos.get() - r;
self.pos.set(pos);
}
}
}
-1
View File
@@ -2,5 +2,4 @@ pub mod fields;
pub mod header;
pub mod message_stream;
pub mod rfc2047;
pub mod token;
+121 -90
View File
@@ -1,9 +1,9 @@
use std::borrow::Cow;
use crate::{
decoders::{
base64::Base64Decoder, charsets::parser::CharsetParser,
quoted_printable::QuotedPrintableDecoder, Decoder, DecoderResult,
base64::Base64Decoder,
charsets::{parser::CharsetParser, utf8::Utf8Decoder, CharsetDecoder},
quoted_printable::QuotedPrintableDecoder,
Decoder, DecoderResult,
},
parsers::message_stream::MessageStream,
};
@@ -12,25 +12,32 @@ pub enum Rfc2047Parser {
Charset,
Language,
Encoding,
Data,
}
impl Rfc2047Parser {
pub fn parse<'x>(stream: &'x mut MessageStream) -> Option<Cow<'x, str>> {
pub fn parse(stream: &MessageStream) -> Option<String> {
let mut ch_parser = CharsetParser::new();
let mut ch_decoder = None;
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 = ch_parser.get_decoder(75);
ch_decoder = Some(
ch_parser
.get_decoder(75)
.unwrap_or_else(|| Box::new(Utf8Decoder::new(75))),
);
state = Rfc2047Parser::Encoding;
}
b'*' => {
ch_decoder = ch_parser.get_decoder(75);
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),
@@ -41,116 +48,140 @@ impl Rfc2047Parser {
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'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'?' {
state = Rfc2047Parser::Data;
if ch_decoder.is_none() {
stream.begin_write();
}
break;
} else {
return None;
}
}
Rfc2047Parser::Data => match ch {
b'?' => {
stream.skip_byte(b'=');
}
}
return if let Some(ref mut ch_decoder) = ch_decoder {
ch_decoder
.to_string()
.map(Cow::from)
} else {
stream
.end_write()
.map(String::from_utf8_lossy)
};
}
b'\n' => return None,
_ => {
match decoder.as_mut().unwrap().ingest(ch) {
DecoderResult::Byte(b) => {
if let Some(ref mut ch_decoder) = ch_decoder {
ch_decoder.ingest(&b);
} else {
stream.write(b);
}
},
DecoderResult::ByteArray(ba) => {
if let Some(ref mut ch_decoder) = ch_decoder {
ch_decoder.ingest_slice(ba);
} else {
stream.write_slice(ba);
}
},
DecoderResult::NeedData => (),
DecoderResult::Error => return None,
}
// Unwrap decoders and proceed to decode data
let mut ch_decoder = ch_decoder?;
let mut decoder = decoder?;
while let Some(ch) = stream.next() {
match ch {
b'?' => {
stream.skip_byte(&b'=');
return ch_decoder.to_string();
}
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,
},
}
}
None
}
}
#[cfg(test)]
mod tests {
use crate::parsers::message_stream::MessageStream;
use super::Rfc2047Parser;
use crate::parsers::message_stream::MessageStream;
#[test]
fn decode_rfc2047() {
unsafe {
let inputs = [
("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(), "this is some text", true),
("US-ASCII?Q?Keith_Moore?=".to_string(), "Keith Moore", false),
("iso_8859-1:1987?Q?Keld_J=F8rn_Simonsen?=".to_string(), "Keld Jørn Simonsen", true),
("ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=".to_string(), "If you can read this yo", true),
("ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=".to_string(), "u understand the example.", true),
("ISO-8859-1?Q?Olle_J=E4rnefors?=".to_string(), "Olle Järnefors", true),
("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),
("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(), "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(), "مرحبا بالعالم", true),
("Iso-8859-6*arabic?b?5dHNyMcgyMfk2cfk5Q==?=".to_string(), "مرحبا بالعالم", true),
#[cfg(feature = "multibytedecode")]
("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(), "ハロー・ワールド", true),
];
let inputs = [
(
"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(),
"this is some text",
true,
),
("US-ASCII?Q?Keith_Moore?=".to_string(), "Keith Moore", false),
(
"iso_8859-1:1987?Q?Keld_J=F8rn_Simonsen?=".to_string(),
"Keld Jørn Simonsen",
true,
),
(
"ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=".to_string(),
"If you can read this yo",
true,
),
(
"ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=".to_string(),
"u understand the example.",
true,
),
(
"ISO-8859-1?Q?Olle_J=E4rnefors?=".to_string(),
"Olle Järnefors",
true,
),
(
"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),
(
"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(),
"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(),
"مرحبا بالعالم",
true,
),
(
"Iso-8859-6*arabic?b?5dHNyMcgyMfk2cfk5Q==?=".to_string(),
"مرحبا بالعالم",
true,
),
#[cfg(feature = "multibytedecode")]
(
"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(),
"ハロー・ワールド",
true,
),
];
for input in inputs {
match Rfc2047Parser::parse(&mut MessageStream::new(input.0.clone().as_bytes_mut())) {
Some(string) => {
match string {
std::borrow::Cow::Borrowed(string) => {
//println!("Decoded '{}' -> Borrowed", string);
assert_eq!(string, input.1);
assert!(!input.2);
},
std::borrow::Cow::Owned(string) => {
//println!("Decoded '{}' -> Owned", string);
assert_eq!(string, input.1);
assert!(input.2);
},
}
},
None => panic!("Failed to parse '{}'", input.0),
for input in inputs {
match Rfc2047Parser::parse(&MessageStream::new(input.0.as_bytes())) {
Some(string) => {
//println!("Decoded '{}'", string);
assert_eq!(string, input.1);
}
None => panic!("Failed to parse '{}'", input.0),
}
}
}
-27
View File
@@ -1,27 +0,0 @@
pub enum TokenPart {
ByteRange((u32, u32)),
String(String)
}
pub struct Token {
items: Vec<TokenPart>
}
impl Token {
pub fn new() -> Token {
Token { items: Vec::new() }
}
pub fn push_string(&mut self, string: String) {
self.items.push(TokenPart::String(string));
}
pub fn push_bytes(&mut self, from: u32, to: u32) {
self.items.push(TokenPart::ByteRange((from, to)));
}
}