Test suite using Serde.

This commit is contained in:
Mauro D
2021-10-25 16:19:54 +00:00
parent 0018821b84
commit 2d8dbed00a
92 changed files with 95113 additions and 918 deletions
+1 -3
View File
@@ -116,9 +116,7 @@ impl<'x> Base64Decoder<'x> for MessageStream<'x> {
#[cfg(test)]
mod tests {
use crate::{
parsers::message_stream::MessageStream,
};
use crate::parsers::message_stream::MessageStream;
use super::Base64Decoder;
+8 -7
View File
@@ -45,12 +45,16 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
if ch == *boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
success = true;
break;
if is_word || self.is_boundary_end(read_pos) {
success = true;
break;
}
} else {
continue;
}
} else if match_count > 0 {
}
if match_count > 0 {
for ch in boundary[..match_count].iter() {
if *ch != b'\n' || QuotedPrintableState::Eq != state {
*((*data).get_unchecked_mut(write_pos)) = *ch;
@@ -151,10 +155,7 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
#[cfg(test)]
mod tests {
use crate::{
decoders::{
quoted_printable::QuotedPrintableDecoder,
},
parsers::message_stream::MessageStream,
decoders::quoted_printable::QuotedPrintableDecoder, parsers::message_stream::MessageStream,
};
#[test]
File diff suppressed because it is too large Load Diff
+653 -106
View File
@@ -417,6 +417,8 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
b')' if parser.state == ContentState::Comment => {
if !parser.is_escaped {
parser.state = parser.state_stack.pop().unwrap();
parser.token_start = 0;
parser.is_token_safe = true;
} else {
parser.is_escaped = false;
}
@@ -453,74 +455,179 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
mod tests {
#[test]
fn parse_content_fields() {
use std::{borrow::Cow, collections::HashMap};
use crate::parsers::{fields::content_type::ContentType, message_stream::MessageStream};
use super::parse_content_type;
let inputs = [
("audio/basic\n", "audio||basic"),
("application/postscript \n", "application||postscript"),
("image/ jpeg\n", "image||jpeg"),
(" message / rfc822\n", "message||rfc822"),
("inline\n", "inline"),
(
"audio/basic\n",
concat!("---\n", "c_type: audio\n", "c_subtype: basic\n"),
),
(
"application/postscript \n",
concat!("---\n", "c_type: application\n", "c_subtype: postscript\n"),
),
(
"image/ jpeg\n",
concat!("---\n", "c_type: image\n", "c_subtype: jpeg\n"),
),
(
" message / rfc822\n",
concat!("---\n", "c_type: message\n", "c_subtype: rfc822\n"),
),
("inline\n", concat!("---\n", "c_type: inline\n")),
(
" text/plain; charset =us-ascii (Plain text)\n",
"text||plain||charset~~us-ascii",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"text/plain; charset= \"us-ascii\"\n",
"text||plain||charset~~us-ascii",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"text/plain; charset =ISO-8859-1\n",
"text||plain||charset~~ISO-8859-1",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: ISO-8859-1\n"
),
),
(
"text/foo; charset= bar\n",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: foo\n",
"attributes:\n",
" charset: bar\n"
),
),
("text/foo; charset= bar\n", "text||foo||charset~~bar"),
(
" text /plain; charset=\"iso-8859-1\"; format=flowed\n",
"text||plain||charset~~iso-8859-1||format~~flowed",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: iso-8859-1\n",
" format: flowed\n"
),
),
(
"application/pgp-signature; x-mac-type=70674453;\n name=PGP.sig\n",
"application||pgp-signature||x-mac-type~~70674453||name~~PGP.sig",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: pgp-signature\n",
"attributes:\n",
" name: PGP.sig\n",
" x-mac-type: \"70674453\"\n"
),
),
(
"multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p\n",
"multipart||mixed||boundary~~gc0p4Jq0M2Yt08j34c0p",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: mixed\n",
"attributes:\n",
" boundary: gc0p4Jq0M2Yt08j34c0p\n"
),
),
(
"multipart/mixed; boundary=gc0pJq0M:08jU534c0p\n",
"multipart||mixed||boundary~~gc0pJq0M:08jU534c0p",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: mixed\n",
"attributes:\n",
" boundary: \"gc0pJq0M:08jU534c0p\"\n"
),
),
(
"multipart/mixed; boundary=\"gc0pJq0M:08jU534c0p\"\n",
"multipart||mixed||boundary~~gc0pJq0M:08jU534c0p",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: mixed\n",
"attributes:\n",
" boundary: \"gc0pJq0M:08jU534c0p\"\n"
),
),
(
"multipart/mixed; boundary=\"simple boundary\"\n",
"multipart||mixed||boundary~~simple boundary",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: mixed\n",
"attributes:\n",
" boundary: simple boundary\n"
),
),
(
"multipart/alternative; boundary=boundary42\n",
"multipart||alternative||boundary~~boundary42",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: alternative\n",
"attributes:\n",
" boundary: boundary42\n"
),
),
(
" multipart/mixed;\n boundary=\"---- main boundary ----\"\n",
"multipart||mixed||boundary~~---- main boundary ----",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: mixed\n",
"attributes:\n",
" boundary: \"---- main boundary ----\"\n"
),
),
(
"multipart/alternative; boundary=42\n",
"multipart||alternative||boundary~~42",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: alternative\n",
"attributes:\n",
" boundary: \"42\"\n"
),
),
(
"message/partial; id=\"ABC@host.com\";\n",
"message||partial||id~~ABC@host.com",
concat!(
"---\n",
"c_type: message\n",
"c_subtype: partial\n",
"attributes:\n",
" id: ABC@host.com\n"
),
),
(
"multipart/parallel;boundary=unique-boundary-2\n",
"multipart||parallel||boundary~~unique-boundary-2",
concat!(
"---\n",
"c_type: multipart\n",
"c_subtype: parallel\n",
"attributes:\n",
" boundary: unique-boundary-2\n"
),
),
(
concat!(
@@ -529,9 +636,16 @@ mod tests {
"ation=\"Fri, 14 Jun 1991 19:13:14 -0400 (EDT)\"\n"
),
concat!(
"message||external-body||name~~BodyFormats.ps||site~~thumper.bellcore.c",
"om||mode~~image||access-type~~ANON-FTP||directory~~pub||expiration~~Fr",
"i, 14 Jun 1991 19:13:14 -0400 (EDT)"
"---\n",
"c_type: message\n",
"c_subtype: external-body\n",
"attributes:\n",
" expiration: \"Fri, 14 Jun 1991 19:13:14 -0400 (EDT)\"\n",
" site: thumper.bellcore.com\n",
" directory: pub\n",
" name: BodyFormats.ps\n",
" mode: image\n",
" access-type: ANON-FTP\n"
),
),
(
@@ -541,9 +655,14 @@ mod tests {
", 14 Jun 1991 19:13:14 -0400 (EDT)\"\n"
),
concat!(
"message||external-body||access-type~~local-file||expiration~~Fri, 14 J",
"un 1991 19:13:14 -0400 (EDT)||name~~/u/nsb/writing/rfcs/RFC-MIME.ps||s",
"ite~~thumper.bellcore.com"
"---\n",
"c_type: message\n",
"c_subtype: external-body\n",
"attributes:\n",
" expiration: \"Fri, 14 Jun 1991 19:13:14 -0400 (EDT)\"\n",
" access-type: local-file\n",
" name: /u/nsb/writing/rfcs/RFC-MIME.ps\n",
" site: thumper.bellcore.com\n"
),
),
(
@@ -553,8 +672,13 @@ mod tests {
"T)\"\n"
),
concat!(
"message||external-body||access-type~~mail-server||server~~listserv@bog",
"us.bitnet||expiration~~Fri, 14 Jun 1991 19:13:14 -0400 (EDT)"
"---\n",
"c_type: message\n",
"c_subtype: external-body\n",
"attributes:\n",
" access-type: mail-server\n",
" server: listserv@bogus.bitnet\n",
" expiration: \"Fri, 14 Jun 1991 19:13:14 -0400 (EDT)\"\n"
),
),
(
@@ -563,8 +687,13 @@ mod tests {
"llcore.com\"\n"
),
concat!(
"message||partial||number~~2||total~~3||id~~oc=jpbe0M2Yt4s@thumper.bell",
"core.com"
"---\n",
"c_type: message\n",
"c_subtype: partial\n",
"attributes:\n",
" total: \"3\"\n",
" number: \"2\"\n",
" id: oc=jpbe0M2Yt4s@thumper.bellcore.com\n"
),
),
(
@@ -573,8 +702,13 @@ mod tests {
"\";\n boundary=\"=-J1qXPoyGtE2XNN5N6Z6j\"\n"
),
concat!(
"multipart||signed||protocol~~application/pgp-signature||boundary~~=-J1",
"qXPoyGtE2XNN5N6Z6j||micalg~~pgp-sha1"
"---\n",
"c_type: multipart\n",
"c_subtype: signed\n",
"attributes:\n",
" boundary: \"=-J1qXPoyGtE2XNN5N6Z6j\"\n",
" micalg: pgp-sha1\n",
" protocol: application/pgp-signature\n"
),
),
(
@@ -582,7 +716,14 @@ mod tests {
"message/external-body;\n access-type=local-file;\n name=\"/u/nsb/M",
"e.jpeg\"\n"
),
concat!("message||external-body||access-type~~local-file||name~~/u/nsb/Me.jpeg"),
concat!(
"---\n",
"c_type: message\n",
"c_subtype: external-body\n",
"attributes:\n",
" name: /u/nsb/Me.jpeg\n",
" access-type: local-file\n"
),
),
(
concat!(
@@ -590,8 +731,12 @@ mod tests {
"\"cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar\"\n"
),
concat!(
"message||external-body||url~~ftp://cs.utk.edu/pub/moore/bulk-mailer/bu",
"lk-mailer.tar||access-type~~URL"
"---\n",
"c_type: message\n",
"c_subtype: external-body\n",
"attributes:\n",
" url: \"ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar\"\n",
" access-type: URL\n"
),
),
(
@@ -600,8 +745,12 @@ mod tests {
"/moore/bulk-mailer/bulk-mailer.tar\"\n"
),
concat!(
"message||external-body||access-type~~URL||url~~ftp://cs.utk.edu/pub/mo",
"ore/bulk-mailer/bulk-mailer.tar"
"---\n",
"c_type: message\n",
"c_subtype: external-body\n",
"attributes:\n",
" url: \"ftp://cs.utk.edu/pub/moore/bulk-mailer/bulk-mailer.tar\"\n",
" access-type: URL\n"
),
),
(
@@ -610,8 +759,13 @@ mod tests {
"un%2A%2A%2A\n"
),
concat!(
"application||x-stuff||title-language~~en-us||title~~This is ***fun***|",
"|title-charset~~us-ascii"
"---\n",
"c_type: application\n",
"c_subtype: x-stuff\n",
"attributes:\n",
" title: This is ***fun***\n",
" title-charset: us-ascii\n",
" title-language: en-us\n"
),
),
(
@@ -620,8 +774,13 @@ mod tests {
"\n title*1*=%2A%2A%2Afun%2A%2A%2A%20\n title*2=\"isn't it!\"\n"
),
concat!(
"application||x-stuff||title~~This is even more ***fun*** isn't it!||ti",
"tle-charset~~us-ascii||title-language~~en"
"---\n",
"c_type: application\n",
"c_subtype: x-stuff\n",
"attributes:\n",
" title-language: en\n",
" title-charset: us-ascii\n",
" title: \"This is even more ***fun*** isn't it!\"\n"
),
),
(
@@ -630,8 +789,13 @@ mod tests {
"%20r%E1pido\n filename*2=\" (versi%F3n \\'99 \\\"oficial\\\").pdf\"\n"
),
concat!(
"application||pdf||filename~~Ñandú rápido (versión '99 \"oficial\").pdf||",
"filename-charset~~iso-8859-1||filename-language~~es"
"---\n",
"c_type: application\n",
"c_subtype: pdf\n",
"attributes:\n",
" filename: \"Ñandú rápido (versión '99 \\\"oficial\\\").pdf\"\n",
" filename-language: es\n",
" filename-charset: iso-8859-1\n"
),
),
(
@@ -639,104 +803,487 @@ mod tests {
" image/png;\n name=\"=?utf-8?q?=E3=83=8F=E3=83=AD=E3=83=BC=E3=83=BB=E3",
"=83=AF=E3=83=BC=E3=83=AB=E3=83=89?=.png\"\n"
),
concat!("image||png||name~~ハロー・ワールド.png"),
concat!(
"---\n",
"c_type: image\n",
"c_subtype: png\n",
"attributes:\n",
" name: ハロー・ワールド.png\n"
),
),
(
" image/gif;\n name==?iso-8859-6?b?5dHNyMcgyMfk2cfk5Q==?=.gif\n",
"image||gif||name~~مرحبا بالعالم.gif",
concat!(
"---\n",
"c_type: image\n",
"c_subtype: gif\n",
"attributes:\n",
" name: مرحبا بالعالم.gif\n"
),
),
(
concat!(
"image/jpeg;\n name=\"=?iso-8859-1?B?4Q==?= =?utf-8?B?w6k=?= =?iso-8859",
"-1?q?=ED?=.jpeg\"\n"
),
concat!("image||jpeg||name~~á é í.jpeg"),
concat!(
"---\n",
"c_type: image\n",
"c_subtype: jpeg\n",
"attributes:\n",
" name: á é í.jpeg\n"
),
),
(
concat!(
"image/jpeg;\n name==?iso-8859-1?B?4Q==?= =?utf-8?B?w6k=?= =?iso-8859-",
"1?q?=ED?=.jpeg\n"
),
concat!("image||jpeg||name~~áéí.jpeg"),
concat!(
"---\n",
"c_type: image\n",
"c_subtype: jpeg\n",
"attributes:\n",
" name: áéí.jpeg\n"
),
),
(
"image/gif;\n name==?iso-8859-6?b?5dHNyMcgyMfk2cfk5S5naWY=?=\n",
"image||gif||name~~مرحبا بالعالم.gif",
concat!(
"---\n",
"c_type: image\n",
"c_subtype: gif\n",
"attributes:\n",
" name: مرحبا بالعالم.gif\n"
),
),
(
" image/gif;\n name=\"=?iso-8859-6?b?5dHNyMcgyMfk2cfk5S5naWY=?=\"\n",
"image||gif||name~~مرحبا بالعالم.gif",
concat!(
"---\n",
"c_type: image\n",
"c_subtype: gif\n",
"attributes:\n",
" name: مرحبا بالعالم.gif\n"
),
),
(
" inline; filename=\" best \\\"file\\\" ever with \\\\ escaped ' stuff. \"\n",
"inline||||filename~~ best \"file\" ever with \\ escaped ' stuff. ",
concat!(
"---\n",
"c_type: inline\n",
"attributes:\n",
" filename: \" best \\\"file\\\" ever with \\\\ escaped ' stuff. \"\n"
),
),
("test/\n", concat!("---\n", "c_type: test\n")),
("/invalid\n", concat!("---\n", "~\n")),
("/\n", concat!("---\n", "~\n")),
(";\n", concat!("---\n", "~\n")),
("/ ; name=value\n", concat!("---\n", "~\n")),
(
"text/plain;\n",
concat!("---\n", "c_type: text\n", "c_subtype: plain\n"),
),
(
"text/plain;;\n",
concat!("---\n", "c_type: text\n", "c_subtype: plain\n"),
),
("test/\n", "test"),
("/invalid\n", ""),
("/\n", ""),
(";\n", ""),
("/ ; name=value\n", ""),
("text/plain;\n", "text||plain"),
("text/plain;;\n", "text||plain"),
(
"text/plain ;;;;; = ;; name=\"value\"\n",
"text||plain||name~~value",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" name: value\n"
),
),
("=\n", concat!("---\n", "c_type: \"=\"\n")),
("name=value\n", concat!("---\n", "c_type: name=value\n")),
(
"text/plain; name= \n",
concat!("---\n", "c_type: text\n", "c_subtype: plain\n"),
),
(
"a/b; = \n",
concat!("---\n", "c_type: a\n", "c_subtype: b\n"),
),
(
"a/b; = \n \n",
concat!("---\n", "c_type: a\n", "c_subtype: b\n"),
),
(
"a/b; =value\n",
concat!("---\n", "c_type: a\n", "c_subtype: b\n"),
),
(
"test/test; =\"value\"\n",
concat!("---\n", "c_type: test\n", "c_subtype: test\n"),
),
(
"á/é; á=é\n",
concat!(
"---\n",
"c_type: á\n",
"c_subtype: é\n",
"attributes:\n",
" á: é\n"
),
),
(
"inva/lid; name=\" \n",
concat!(
"---\n",
"c_type: inva\n",
"c_subtype: lid\n",
"attributes:\n",
" name: \" \"\n"
),
),
(
"inva/lid; name=\" \n \n",
concat!(
"---\n",
"c_type: inva\n",
"c_subtype: lid\n",
"attributes:\n",
" name: \" \"\n"
),
),
("=\n", "="),
("name=value\n", "name=value"),
("text/plain; name= \n", "text||plain"),
("a/b; = \n", "a||b"),
("a/b; = \n \n", "a||b"),
("a/b; =value\n", "a||b"),
("test/test; =\"value\"\n", "test||test"),
("á/é; á=é\n", "á||é||á~~é"),
("inva/lid; name=\" \n", "inva||lid||name~~ "),
("inva/lid; name=\" \n \n", "inva||lid||name~~ "),
(
"inva/lid; name=\" \n \"; test=test\n",
"inva||lid||name~~ ||test~~test",
concat!(
"---\n",
"c_type: inva\n",
"c_subtype: lid\n",
"attributes:\n",
" test: test\n",
" name: \" \"\n"
),
),
("name=value\n", concat!("---\n", "c_type: name=value\n")),
(
concat!(
"test/encoded; key4*=us-ascii''foo; key*2=ba%; key2*0=a; key3*0*=us-asc",
"ii'en'xyz; key*0=\"f\u{0}oo\"; key2*1*=b%25; key3*1=plop%; key*1=baz\n"
), //TODO insert in right order
concat!(
"---\n",
"c_type: test\n",
"c_subtype: encoded\n",
"attributes:\n",
" key3-language: en\n",
" key3-charset: us-ascii\n",
" key3: xyzplop\n",
" key: \"ba%f\\u0000oobaz\"\n",
" key4: foo\n",
" key2: ab%25\n",
" key4-charset: us-ascii\n"
),
),
(";charset=us-ascii\n", concat!("---\n", "~\n")),
(" ;charset=us-ascii\n", concat!("---\n", "~\n")),
("/\n", concat!("---\n", "~\n")),
("/;charset=us-ascii\n", concat!("---\n", "~\n")),
("/ ;charset=us-ascii\n", concat!("---\n", "~\n")),
("text/\n", concat!("---\n", "c_type: text\n")),
(
"text/;charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"text/ ;charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
("/plain\n", concat!("---\n", "~\n")),
("/plain;charset=us-ascii\n", concat!("---\n", "~\n")),
("/plain ;charset=us-ascii\n", concat!("---\n", "~\n")),
(
"text/plain\n",
concat!("---\n", "c_type: text\n", "c_subtype: plain\n"),
),
(
"text/plain;charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"text/plain ;charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"text/plain/format\n",
concat!("---\n", "c_type: text\n", "c_subtype: plain/format\n"),
),
(
"text/plain/format;charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain/format\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"text/plain/format ;charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain/format\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/ld+json\n",
concat!("---\n", "c_type: application\n", "c_subtype: ld+json\n"),
),
(
"application/ld+json;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: ld+json\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/ld+json ;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: ld+json\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/x-magic-cap-package-1.0\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: x-magic-cap-package-1.0\n"
),
),
(
"application/x-magic-cap-package-1.0;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: x-magic-cap-package-1.0\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/x-magic-cap-package-1.0 ;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: x-magic-cap-package-1.0\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/pro_eng\n",
concat!("---\n", "c_type: application\n", "c_subtype: pro_eng\n"),
),
(
"application/pro_eng;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: pro_eng\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/pro_eng ;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: pro_eng\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/wordperfect6.1\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: wordperfect6.1\n"
),
),
(
"application/wordperfect6.1;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: wordperfect6.1\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"application/wordperfect6.1 ;charset=us-ascii\n",
concat!(
"---\n",
"c_type: application\n",
"c_subtype: wordperfect6.1\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
concat!(
"application/vnd.openxmlformats-officedocument.wordprocessingml.templat",
"e\n"
),
concat!(
"---\n",
"c_type: application\n",
"c_subtype: vnd.openxmlformats-officedocument.wordprocessingml.template\n"
),
),
(
concat!(
"application/vnd.openxmlformats-officedocument.wordprocessingml.templat",
"e;charset=us-ascii\n"
),
concat!(
"---\n",
"c_type: application\n",
"c_subtype: vnd.openxmlformats-officedocument.wordprocessingml.template\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
concat!(
"application/vnd.openxmlformats-officedocument.wordprocessingml.templat",
"e ;charset=us-asii\n"
),
concat!(
"---\n",
"c_type: application\n",
"c_subtype: vnd.openxmlformats-officedocument.wordprocessingml.template\n",
"attributes:\n",
" charset: us-asii\n"
),
),
(
"(hello) text (plain) / (world) plain (eod)\n",
concat!("---\n", "c_type: text\n", "c_subtype: plain\n"),
),
(
"(hello) text (plain) / (world) plain (eod);charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"(hello) text (plain) / (world) plain (eod); charset=us-ascii\n",
concat!(
"---\n",
"c_type: text\n",
"c_subtype: plain\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
"message/rfc822\r\n\n",
concat!("---\n", "c_type: message\n", "c_subtype: rfc822\n"),
),
(
" \t\r message/rfc822 \t\r\n\n",
concat!("---\n", "c_type: message\n", "c_subtype: rfc822\n"),
),
(
" \t\r message/rfc822 \t ;charset=us-ascii\r\n\n",
concat!(
"---\n",
"c_type: message\n",
"c_subtype: rfc822\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
(
" \t\r message/rfc822 \t ; charset=us-ascii\r\n",
concat!(
"---\n",
"c_type: message\n",
"c_subtype: rfc822\n",
"attributes:\n",
" charset: us-ascii\n"
),
),
("name=value\n", "name=value"),
];
for input in inputs {
let mut str = input.0.to_string();
let result = parse_content_type(&MessageStream::new(unsafe { str.as_bytes_mut() }));
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();
let expected: Option<ContentType> = serde_yaml::from_str(input.1).unwrap_or(None);
for (count, part) in input.1.split("||").enumerate() {
match count {
0 => c_type = Some(part.into()),
1 => {
c_subtype = if part.is_empty() {
None
} else {
Some(part.into())
}
}
_ => {
let attr: Vec<&str> = part.split("~~").collect();
attributes.insert(attr[0].into(), attr[1].into());
}
}
}
c_type.map(|content_type| ContentType {
c_type: content_type,
c_subtype: c_subtype.take(),
attributes: if !attributes.is_empty() {
Some(attributes)
} else {
None
},
})
/*
if input.0.len() >= 70 {
println!(
"(concat!({:?}), concat!({:?})),",
input
.0
.chars()
.collect::<Vec<char>>()
.chunks(70)
.map(|c| c.iter().collect::<String>())
.collect::<Vec<String>>(),
serde_yaml::to_string(&result)
.unwrap_or("".to_string())
.split_inclusive("\n")
.collect::<Vec<&str>>()
);
} else {
None
};
println!(
"({:?}, concat!({:?})),",
input.0,
serde_yaml::to_string(&result)
.unwrap_or("".to_string())
.split_inclusive("\n")
.collect::<Vec<&str>>()
);
}*/
assert_eq!(result, expected, "Failed for '{:?}'", input.0);
}
+4 -14
View File
@@ -1,9 +1,6 @@
use std::borrow::Cow;
use crate::{
decoders::{encoded_word::parse_encoded_word},
parsers::message_stream::MessageStream,
};
use crate::{decoders::encoded_word::parse_encoded_word, parsers::message_stream::MessageStream};
struct ListParser<'x> {
token_start: usize,
@@ -51,9 +48,7 @@ fn add_tokens_to_list<'x>(parser: &mut ListParser<'x>) {
}
}
pub fn parse_comma_separared<'x>(
stream: &MessageStream<'x>,
) -> Option<Vec<Cow<'x, str>>> {
pub fn parse_comma_separared<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'x, str>>> {
let mut parser = ListParser {
token_start: 0,
token_end: 0,
@@ -128,9 +123,7 @@ pub fn parse_comma_separared<'x>(
}
mod tests {
use crate::{
parsers::{fields::list::parse_comma_separared, message_stream::MessageStream},
};
use crate::parsers::{fields::list::parse_comma_separared, message_stream::MessageStream};
#[test]
fn parse_comma_separated_text() {
@@ -183,10 +176,7 @@ mod tests {
for input in inputs {
let mut str = input.0.to_string();
assert_eq!(
parse_comma_separared(
&MessageStream::new(unsafe { str.as_bytes_mut() }),
)
.unwrap(),
parse_comma_separared(&MessageStream::new(unsafe { str.as_bytes_mut() }),).unwrap(),
input.1
);
}
+41 -41
View File
@@ -96,10 +96,6 @@ impl<'x> MessageField<'x> for MessageHeader<'x> {
append_address_line(&mut self.resent_cc, parse_address(stream));
}
fn set_content_id(&mut self, stream: &MessageStream<'x>) {
self.mime.set_content_id(stream);
}
fn set_resent_message_id(&mut self, stream: &MessageStream<'x>) {
append_line_many(&mut self.resent_message_id, parse_id(stream));
}
@@ -152,10 +148,6 @@ impl<'x> MessageField<'x> for MessageHeader<'x> {
self.from = parse_address(stream);
}
fn set_content_transfer_encoding(&mut self, stream: &MessageStream<'x>) {
self.mime.set_content_transfer_encoding(stream);
}
fn set_return_path(&mut self, stream: &MessageStream<'x>) {
append_line_many(&mut self.return_path, parse_id(stream));
}
@@ -176,10 +168,6 @@ impl<'x> MessageField<'x> for MessageHeader<'x> {
self.message_id = parse_id(stream).map(|mut v| v.pop().unwrap());
}
fn set_content_type(&mut self, stream: &MessageStream<'x>) {
self.mime.set_content_type(stream);
}
fn set_list_post(&mut self, stream: &MessageStream<'x>) {
self.list_post = parse_address(stream);
}
@@ -188,18 +176,10 @@ impl<'x> MessageField<'x> for MessageHeader<'x> {
self.reply_to = parse_address(stream);
}
fn set_content_description(&mut self, stream: &MessageStream<'x>) {
self.mime.set_content_description(stream);
}
fn set_resent_from(&mut self, stream: &MessageStream<'x>) {
append_address_line(&mut self.resent_from, parse_address(stream));
}
fn set_content_disposition(&mut self, stream: &MessageStream<'x>) {
self.mime.set_content_disposition(stream);
}
fn set_list_unsubscribe(&mut self, stream: &MessageStream<'x>) {
self.list_unsubscribe = parse_address(stream);
}
@@ -220,24 +200,44 @@ impl<'x> MessageField<'x> for MessageHeader<'x> {
}
}
fn set_content_id(&mut self, stream: &MessageStream<'x>) {
self.content_id = parse_id(stream).map(|mut v| v.pop().unwrap());
}
fn set_content_transfer_encoding(&mut self, stream: &MessageStream<'x>) {
self.content_transfer_encoding = parse_unstructured(stream);
}
fn set_content_type(&mut self, stream: &MessageStream<'x>) {
self.content_type = self::content_type::parse_content_type(stream);
}
fn set_content_description(&mut self, stream: &MessageStream<'x>) {
self.content_description = parse_unstructured(stream);
}
fn set_content_disposition(&mut self, stream: &MessageStream<'x>) {
self.content_disposition = self::content_type::parse_content_type(stream);
}
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.mime.content_description.as_ref()
self.content_description.as_ref()
}
fn get_content_disposition(&self) -> Option<&ContentType<'x>> {
self.mime.content_disposition.as_ref()
self.content_disposition.as_ref()
}
fn get_content_id(&self) -> Option<&Cow<'x, str>> {
self.mime.content_id.as_ref()
self.content_id.as_ref()
}
fn get_content_transfer_encoding(&self) -> Option<&Cow<'x, str>> {
self.mime.content_transfer_encoding.as_ref()
self.content_transfer_encoding.as_ref()
}
fn get_content_type(&self) -> Option<&ContentType<'x>> {
self.mime.content_type.as_ref()
self.content_type.as_ref()
}
}
@@ -270,10 +270,6 @@ impl<'x> MessageField<'x> for MimeHeader<'x> {
parse_and_ignore(stream);
}
fn set_content_id(&mut self, stream: &MessageStream<'x>) {
self.content_id = parse_id(stream).map(|mut v| v.pop().unwrap());
}
fn set_resent_message_id(&mut self, stream: &MessageStream<'x>) {
parse_and_ignore(stream);
}
@@ -326,10 +322,6 @@ impl<'x> MessageField<'x> for MimeHeader<'x> {
parse_and_ignore(stream);
}
fn set_content_transfer_encoding(&mut self, stream: &MessageStream<'x>) {
self.content_transfer_encoding = parse_unstructured(stream);
}
fn set_return_path(&mut self, stream: &MessageStream<'x>) {
parse_and_ignore(stream);
}
@@ -350,10 +342,6 @@ impl<'x> MessageField<'x> for MimeHeader<'x> {
parse_and_ignore(stream);
}
fn set_content_type(&mut self, stream: &MessageStream<'x>) {
self.content_type = self::content_type::parse_content_type(stream);
}
fn set_list_post(&mut self, stream: &MessageStream<'x>) {
parse_and_ignore(stream);
}
@@ -362,10 +350,6 @@ impl<'x> MessageField<'x> for MimeHeader<'x> {
parse_and_ignore(stream);
}
fn set_content_description(&mut self, stream: &MessageStream<'x>) {
self.content_description = parse_unstructured(stream);
}
fn set_resent_from(&mut self, stream: &MessageStream<'x>) {
parse_and_ignore(stream);
}
@@ -382,6 +366,22 @@ impl<'x> MessageField<'x> for MimeHeader<'x> {
parse_and_ignore(stream);
}
fn set_content_id(&mut self, stream: &MessageStream<'x>) {
self.content_id = parse_id(stream).map(|mut v| v.pop().unwrap());
}
fn set_content_transfer_encoding(&mut self, stream: &MessageStream<'x>) {
self.content_transfer_encoding = parse_unstructured(stream);
}
fn set_content_type(&mut self, stream: &MessageStream<'x>) {
self.content_type = self::content_type::parse_content_type(stream);
}
fn set_content_description(&mut self, stream: &MessageStream<'x>) {
self.content_description = parse_unstructured(stream);
}
fn set_content_disposition(&mut self, stream: &MessageStream<'x>) {
self.content_disposition = self::content_type::parse_content_type(stream);
}
+17 -1
View File
@@ -9,7 +9,6 @@ use super::fields::{
#[derive(PartialEq, Debug, Default, Serialize, Deserialize)]
pub struct MessageHeader<'x> {
pub mime: MimeHeader<'x>,
#[serde(skip_serializing_if = "Address::is_empty")]
#[serde(default)]
pub bcc: Address<'x>,
@@ -22,6 +21,8 @@ pub struct MessageHeader<'x> {
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub date: Option<DateTime>,
#[serde(skip_serializing_if = "Address::is_empty")]
#[serde(default)]
pub from: Address<'x>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
@@ -98,6 +99,21 @@ pub struct MessageHeader<'x> {
#[serde(skip_serializing_if = "Address::is_empty")]
#[serde(default)]
pub to: Address<'x>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub content_description: Option<Cow<'x, str>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub content_disposition: Option<ContentType<'x>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub content_id: Option<Cow<'x, str>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub content_transfer_encoding: Option<Cow<'x, str>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
pub content_type: Option<ContentType<'x>>,
#[serde(borrow)]
#[serde(skip_serializing_if = "HashMap::is_empty")]
#[serde(default)]
+135 -121
View File
@@ -13,7 +13,7 @@ use super::{
message_stream::MessageStream,
};
#[derive(Debug, Default, Serialize, Deserialize)]
#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Message<'x> {
#[serde(borrow)]
header: MessageHeader<'x>,
@@ -27,7 +27,7 @@ pub struct Message<'x> {
#[serde(default)]
attachments: Vec<MessageAttachment<'x>>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct TextPart<'x> {
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
@@ -35,15 +35,17 @@ pub struct TextPart<'x> {
contents: Cow<'x, str>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct BinaryPart<'x> {
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
header: Option<MimeHeader<'x>>,
contents: &'x [u8],
#[serde(with = "serde_bytes")]
#[serde(borrow)]
contents: Cow<'x, [u8]>,
}
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub enum MessageAttachment<'x> {
Text(Box<TextPart<'x>>),
#[serde(borrow)]
@@ -180,40 +182,32 @@ impl<'x> Message<'x> {
// Parse headers
if !parse_headers(header, &stream) {
// EOF found while parsing headers, abort.
debug_assert!(false, "EOF found while parsing header. Aborting.");
break;
}
state.parts += 1;
let (is_multipart, is_inline, is_text, mime_type) =
let (is_multipart, mut is_inline, mut is_text, mut mime_type) =
get_mime_type(header.get_content_type(), &state.mime_type);
/*println!(
println!(
"--- New part {:?} parent {:?} at '{:?}'",
mime_type,
state.mime_type,
stream
.get_string(stream.get_pos(), stream.get_pos() + 50, true)
.get_string(stream.get_pos(), stream.get_pos() + 20, true)
.unwrap_or_else(|| "NOTHING".into())
);*/
);
if is_multipart {
if let Some(mime_boundary) = header
.get_content_type()
.map_or_else(|| None, |f| f.get_attribute("boundary"))
{
//println!("Found boundary '{}'", mime_boundary,);
println!("Found boundary '{}'", mime_boundary,);
let mime_boundary = ("\n--".to_string() + mime_boundary).into_bytes();
if stream.seek_bytes(mime_boundary.as_ref()) {
/*println!(
"Seek to '{:?}'",
stream
.get_string(stream.get_pos(), stream.get_pos() + 50, true)
.unwrap_or_else(|| "NOTHING".into())
);*/
if stream.seek_next_part(mime_boundary.as_ref()) {
let new_state = MessageParserState {
in_alternative: state.in_alternative
|| mime_type == MimeType::MultipartAlernative,
@@ -231,8 +225,8 @@ impl<'x> Message<'x> {
stream.skip_crlf();
continue;
} else {
debug_assert!(false, "MIME boundary seek failed. Aborting.");
break;
mime_type = MimeType::TextOther;
is_text = true;
}
}
} else if mime_type == MimeType::Message {
@@ -275,7 +269,7 @@ impl<'x> Message<'x> {
.map_or_else(|| &[][..], |b| &b[..]),
false,
),
_ => stream.get_bytes_bounded(
_ => stream.get_bytes_to_boundary(
state
.mime_boundary
.as_ref()
@@ -283,22 +277,39 @@ impl<'x> Message<'x> {
),
};
// Attempt to recover contents of an invalid message
if !success {
//println!("Failed to parse part, reattempting.");
if !stream.is_eof() {
let (success, r_is_utf8_safe, r_bytes) = stream.get_bytes_bounded(
// Get raw MIME part
let (success, r_is_utf8_safe, r_bytes) = stream.get_bytes_to_boundary(
state
.mime_boundary
.as_ref()
.map_or_else(|| &[][..], |b| &b[..]),
);
if !success {
debug_assert!(false, "Failed to parse encoded part. Aborting.");
break;
// If there is MIME boundary, ignore it and get raw message
if !stream.is_eof() && state.mime_boundary.is_some() {
let (_, r_is_utf8_safe, r_bytes) =
stream.get_bytes_to_boundary(&[][..]);
if r_bytes.is_some() {
is_utf8_safe = r_is_utf8_safe;
bytes = r_bytes;
} else {
break;
}
} else {
break;
}
} else {
is_utf8_safe = r_is_utf8_safe;
bytes = r_bytes;
}
is_utf8_safe = r_is_utf8_safe;
bytes = r_bytes;
} else {
debug_assert!(false, "Failed to parse encoded part. Aborting.");
mime_type = MimeType::TextOther;
is_inline = false;
is_text = true;
} else if bytes.is_none() {
break;
}
}
@@ -335,7 +346,7 @@ impl<'x> Message<'x> {
};
let contents = bytes_to_string(
bytes.map_or_else(|| "?".as_bytes(), |v| v),
bytes.map_or_else(|| "\n".as_bytes(), |v| v),
header.get_content_type(),
is_utf8_safe,
);
@@ -372,7 +383,7 @@ impl<'x> Message<'x> {
} else {
None
},
contents: bytes.map_or_else(|| "?".as_bytes(), |v| v),
contents: bytes.map_or_else(|| "?".as_bytes(), |v| v).into(),
})));
};
@@ -397,16 +408,8 @@ impl<'x> Message<'x> {
}
}
if stream.skip_bytes("--".as_bytes()) {
if stream.skip_multipart_end() {
// End of MIME part reached
/*println!(
"Mime part end '{:?}--' next '{:?}'",
std::str::from_utf8(state.mime_boundary.as_ref().unwrap().as_ref())
.unwrap(),
stream
.get_string(stream.get_pos(), stream.get_pos() + 10, true)
.unwrap_or_else(|| "NOTHING".into())
);*/
if MimeType::MultipartAlernative == state.mime_type
&& state.need_html_body
@@ -419,7 +422,7 @@ impl<'x> Message<'x> {
for part in message.html_body[state.html_parts..].iter() {
message.text_body.push(TextPart {
header: None,
contents: part.contents.clone(), //Todo make plain text
contents: part.contents.clone(), //TODO make plain text
});
}
}
@@ -443,32 +446,32 @@ impl<'x> Message<'x> {
if let Some(ref mime_boundary) = state.mime_boundary {
// Ancestor has a MIME boundary, seek it.
if stream.seek_bytes(mime_boundary) {
// Boundary not found, probably a corrupted message, abort.
/*println!(
if stream.seek_next_part(mime_boundary) {
println!(
"Found ancestor MIME boundary '{:?}'",
std::str::from_utf8(mime_boundary).unwrap()
);*/
);
continue 'inner;
} /*else {
println!(
"Boundary '{:?} not found.",
std::str::from_utf8(mime_boundary).unwrap()
);
}*/
} /*else {
// Ancestor does not have a MIME boundary, end parsing.
println!("Ancestor has no MIME boundary, parent found?");
} */
} /*else {
// No more ancestors found, finish parsing.
println!("Finish parsing, no ancestors found.");
} */
} else {
println!(
"Boundary '{:?} not found.",
std::str::from_utf8(mime_boundary).unwrap()
);
}
} else {
// Ancestor does not have a MIME boundary, end parsing.
println!("Ancestor has no MIME boundary, parent found?");
}
} else {
// No more ancestors found, finish parsing.
println!("Finish parsing, no ancestors found.");
}
break 'outer;
} else {
stream.skip_crlf();
// Headers of next part expected next, break inner look.
//println!("Expecting headers of next part.");
break 'inner;
}
}
@@ -486,72 +489,83 @@ mod tests {
use crate::parsers::message::Message;
/*#[test]
fn body_parse() {
let mut samples_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
samples_dir.push("test/dovecot");
let mut got_sign = false;
let mut count = 0;
for path in fs::read_dir(samples_dir.to_str().unwrap()).unwrap() {
let mut path = path.unwrap().path();
if path.as_path().to_str().unwrap().contains(".yaml") {
continue;
}
//if !path.as_path().to_str().unwrap().contains("m576") {
// continue;
//}
println!("Parsing {}", path.to_str().unwrap());
let mut input = fs::read(path.as_path()).unwrap();
if String::from_utf8_lossy(&input).contains("application/pgp-signature") {
if !got_sign {
got_sign = true;
} else {
continue;
}
}
let input2 = input.clone();
let message = Message::parse(&mut input);
if message.text_body.len() + message.html_body.len() + message.attachments.len() > 1 {
fs::write(
format!("/vagrant/Code/stalwart/test/final/list_{:03}.eml", count),
&input2,
)
.unwrap();
//assert!(path.set_extension("yaml"));
fs::write(
format!("/vagrant/Code/stalwart/test/final/list_{:03}.yaml", count),
serde_yaml::to_string(&message).unwrap(),
)
.unwrap();
//fs::write(path, serde_yaml::to_string(&message).unwrap()).unwrap();
count += 1;
}
}
}*/
#[test]
fn body_parse() {
let mut samples_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
samples_dir.push("test/messages");
const SEPARATOR: &[u8] = "\n---- EXPECTED STRUCTURE ----\n".as_bytes();
for path in fs::read_dir(samples_dir.to_str().unwrap()).unwrap() {
let mut path = path.unwrap().path();
if path.as_path().to_str().unwrap().contains(".yaml") {
continue;
for test_suite in ["rfc", "legacy", "malformed"] {
let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
test_dir.push("tests");
test_dir.push(test_suite);
for file_name in fs::read_dir(test_dir).unwrap() {
let mut input = fs::read(file_name.as_ref().unwrap().path()).unwrap();
let mut pos = 0;
for sep_pos in 0..input.len() {
if input[sep_pos..sep_pos + SEPARATOR.len()].eq(SEPARATOR) {
pos = sep_pos;
break;
}
}
assert!(pos > 0, "Failed to find separator.");
let input = input.split_at_mut(pos);
assert_eq!(
Message::parse(input.0),
serde_json::from_slice::<Message>(&input.1[SEPARATOR.len()..]).unwrap(),
"Test failed for {}",
file_name.unwrap().path().display()
);
}
//if !path.as_path().to_str().unwrap().contains("m576") {
// continue;
//}
println!("Parsing {}", path.to_str().unwrap());
let mut input = fs::read(path.as_path()).unwrap();
let message = Message::parse(&mut input);
}
}
assert!(path.set_extension("yaml"));
fs::write(path, serde_yaml::to_string(&message).unwrap()).unwrap();
#[test]
fn generate_test_samples() {
const SEPARATOR: &[u8] = "\n---- EXPECTED STRUCTURE ----\n".as_bytes();
for test_suite in ["rfc" /*"legacy","malformed"*/] {
let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
test_dir.push("tests");
test_dir.push(test_suite);
for file_name in fs::read_dir(test_dir).unwrap() {
if !file_name
.as_ref()
.unwrap()
.path()
.to_str()
.unwrap()
.contains("007")
{
continue;
}
let mut input = fs::read(file_name.as_ref().unwrap().path()).unwrap();
let mut pos = 0;
for sep_pos in 0..input.len() {
if input[sep_pos..sep_pos + SEPARATOR.len()].eq(SEPARATOR) {
pos = sep_pos;
break;
}
}
assert!(pos > 0, "Failed to find separator.");
let input = input.split_at_mut(pos);
println!(
"{}",
serde_yaml::to_string(&Message::parse(input.0)).unwrap()
);
/*let mut output = Vec::new();
output.extend_from_slice(input.0);
output.extend_from_slice(SEPARATOR);
output.extend_from_slice(
serde_json::to_string_pretty(&Message::parse(input.0))
.unwrap_or_else(|_| "".to_string())
.as_bytes(),
);
fs::write(file_name.as_ref().unwrap().path(), &output).unwrap();*/
}
}
}
}
+59 -29
View File
@@ -85,8 +85,8 @@ impl<'x> MessageStream<'x> {
}
}
pub fn seek_bytes(&self, bytes: &[u8]) -> bool {
if !bytes.is_empty() {
pub fn seek_next_part(&self, boundary: &[u8]) -> bool {
if !boundary.is_empty() {
unsafe {
let cur_pos = &mut *self.pos.get();
let data = &mut *self.data.get();
@@ -96,16 +96,16 @@ impl<'x> MessageStream<'x> {
for ch in (*data)[*cur_pos..].iter() {
pos += 1;
if ch == bytes.get_unchecked(match_count) {
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == bytes.len() {
if match_count == boundary.len() {
*cur_pos = pos;
return true;
} else {
continue;
}
} else if match_count > 0 {
if ch == bytes.get_unchecked(0) {
if ch == boundary.get_unchecked(0) {
match_count = 1;
continue;
} else {
@@ -119,7 +119,7 @@ impl<'x> MessageStream<'x> {
false
}
pub fn get_bytes_bounded(&self, boundary: &[u8]) -> (bool, bool, Option<&'x [u8]>) {
pub fn get_bytes_to_boundary(&self, boundary: &[u8]) -> (bool, bool, Option<&'x [u8]>) {
unsafe {
let data = &mut *self.data.get();
@@ -141,20 +141,24 @@ impl<'x> MessageStream<'x> {
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
let match_pos = pos - match_count;
*stream_pos = pos;
return (
true,
is_utf8_safe,
if start_pos < match_pos {
(*data).get(start_pos..match_pos)
} else {
None
},
);
} else {
continue;
if self.is_boundary_end(pos) {
let match_pos = pos - match_count;
*stream_pos = pos;
println!("Got '{:?}'", std::str::from_utf8((*data).get(start_pos..match_pos).unwrap()).unwrap());
return (
true,
is_utf8_safe,
if start_pos < match_pos {
(*data).get(start_pos..match_pos)
} else {
None
},
);
} else {
match_count = 0;
}
}
continue;
} else if match_count > 0 {
if ch == boundary.get_unchecked(0) {
match_count = 1;
@@ -175,6 +179,7 @@ impl<'x> MessageStream<'x> {
}
}
#[inline(always)]
pub fn skip_crlf(&self) {
unsafe {
let cur_pos = &mut *self.pos.get();
@@ -183,7 +188,7 @@ impl<'x> MessageStream<'x> {
for ch in (*data)[*cur_pos..].iter() {
match ch {
b'\r' => pos += 1,
b'\r' | b' ' | b'\t' => pos += 1,
b'\n' => {
*cur_pos = pos + 1;
break;
@@ -194,12 +199,13 @@ impl<'x> MessageStream<'x> {
}
}
#[inline(always)]
pub fn skip_byte(&self, ch: &u8) -> bool {
unsafe {
let pos = &mut *self.pos.get();
let data = &mut *self.data.get();
if *pos < (*data).len() && (*data).get_unchecked(*pos) == ch {
if (*data).get(*pos) == Some(ch) {
*pos += 1;
true
} else {
@@ -208,17 +214,41 @@ impl<'x> MessageStream<'x> {
}
}
pub fn skip_bytes(&self, chs: &[u8]) -> bool {
#[inline(always)]
pub fn is_boundary_end(&self, pos: usize) -> bool {
unsafe {
let data = &mut *self.data.get();
match (*data).get(pos) {
Some(b'\n') => true,
Some(b'-') if (*data).get(pos + 1) == Some(&b'-') => true,
Some(b'\r') if (*data).get(pos + 1) == Some(&b'\n') => true,
Some(b' ') | Some(b'\t') => true,
None => true,
_ => false,
}
}
}
pub fn skip_multipart_end(&self) -> bool {
unsafe {
let pos = &mut *self.pos.get();
let data = &mut *self.data.get();
let to = *pos + chs.len();
match (*data).get(*pos..to) {
Some(bytes) if bytes == chs => {
*pos = to;
true
}
match (*self.data.get()).get(*pos..*pos + 2) {
Some(b"--") => match (*self.data.get()).get(*pos + 2) {
Some(b'\n') => {
*pos += 3;
true
}
Some(b'\r') if (*self.data.get()).get(*pos + 3) == Some(&b'\n') => {
*pos += 4;
true
}
None | Some(b' ') | Some(b'\t') => {
*pos += 2;
true
}
_ => false,
},
_ => false,
}
}
-90
View File
@@ -1,90 +0,0 @@
function isInlineMediaType(type) {
return type.startsWith('image/') ||
type.startsWith('audio/') ||
type.startsWith('video/');
}
function parseStructure(parts, multipartType, inAlternative,
htmlBody, textBody, attachments) {
// For multipartType == alternative
let textLength = textBody ? textBody.length : -1;
let htmlLength = htmlBody ? htmlBody.length : -1;
for (let i = 0; i < parts.length; i += 1) {
let part = parts[i];
let isMultipart = part.type.startsWith('multipart/');
// Is this a body part rather than an attachment
let isInline = part.disposition != "attachment" &&
// Must be one of the allowed body types
(part.type == "text/plain" ||
part.type == "text/html" ||
isInlineMediaType(part.type)) &&
// If multipart/related, only the first part can be inline
// If a text part with a filename, and not the first item
// in the multipart, assume it is an attachment
(i === 0 ||
(multipartType != "related" &&
(isInlineMediaType(part.type) || !part.name)));
if (isMultipart) {
let subMultiType = part.type.split('/')[1];
parseStructure(part.subParts, subMultiType,
inAlternative || (subMultiType == 'alternative'),
htmlBody, textBody, attachments);
} else if (isInline) {
if (multipartType == 'alternative') {
switch (part.type) {
case 'text/plain':
textBody.push(part);
break;
case 'text/html':
htmlBody.push(part);
break;
default:
attachments.push(part);
break;
}
continue;
} else if (inAlternative) {
if (part.type == 'text/plain') {
htmlBody = null;
}
if (part.type == 'text/html') {
textBody = null;
}
}
if (textBody) {
textBody.push(part);
}
if (htmlBody) {
htmlBody.push(part);
}
if ((!textBody || !htmlBody) &&
isInlineMediaType(part.type)) {
attachments.push(part);
}
} else {
attachments.push(part);
}
}
if (multipartType == 'alternative' && textBody && htmlBody) {
// Found HTML part only
if (textLength == textBody.length &&
htmlLength != htmlBody.length) {
for (let i = htmlLength; i < htmlBody.length; i += 1) {
textBody.push(htmlBody[i]);
}
}
// Found plaintext part only
if (htmlLength == htmlBody.length &&
textLength != textBody.length) {
for (let i = textLength; i < textBody.length; i += 1) {
htmlBody.push(textBody[i]);
}
}
}
}