Compare commits

...
16 Commits
Author SHA1 Message Date
Mauro D 6f98f52d77 100% safe Rust 2021-11-03 09:08:07 +00:00
Mauro D ee2d08be07 v0.1.1 2021-11-02 11:40:06 +00:00
Mauro D 1717f803db Added comments explaining the use of . 2021-11-02 11:21:42 +00:00
Mauro D 549e8d2428 Formatting. 2021-11-02 10:35:54 +00:00
Mauro D 972b4d6dfc Merge pull request #1 from barafael/main
Add example from readme as cargo example binary
2021-11-02 11:32:27 +01:00
Mauro D 5d4c4a06c7 Added Fuzz testing. 2021-11-02 08:58:54 +00:00
Mauro D 17833a57b4 Added Fuzz testing. 2021-11-02 08:57:01 +00:00
Rafael Bachmann 52a90c3eff Add example from readme as cargo example binary 2021-11-01 19:56:17 +01:00
Mauro D 31bb44cc29 Update rust.yml 2021-11-01 16:28:27 +01:00
Mauro D 24e17cf675 Merge branch 'main' of github.com:stalwartlabs/mail-parser into main 2021-11-01 15:20:07 +00:00
Mauro D 73af8a971e Added Github CI badge 2021-11-01 15:19:54 +00:00
Mauro D 847359ae39 Update rust.yml 2021-11-01 16:10:24 +01:00
Mauro D 419a9a9fad Gitlab CI 2021-11-01 16:05:36 +01:00
Mauro D 80c7b78646 Gitlab CI 2021-11-01 15:03:08 +00:00
Mauro D 4eebde1020 Travis CI 2021-11-01 14:55:24 +00:00
Mauro D 260fd98d7d Added shields to README. 2021-11-01 11:35:29 +00:00
34 changed files with 1975 additions and 1528 deletions
+22
View File
@@ -0,0 +1,22 @@
name: "CI"
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
+18
View File
@@ -0,0 +1,18 @@
stages:
- build
rust-latest:
stage: build
image: rust:latest
script:
- cargo build --verbose
- cargo test --verbose
rust-nightly:
stage: build
image: rustlang/rust:nightly
script:
- cargo build --verbose
- cargo test --verbose
allow_failure: true
+8
View File
@@ -0,0 +1,8 @@
language: rust
rust:
- stable
- beta
- nightly
matrix:
allow_failures:
- rust: nightly
Generated
+1 -1
View File
@@ -59,7 +59,7 @@ checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]]
name = "mail-parser"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"encoding_rs",
"serde",
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "mail-parser"
description = "Fast and robust e-mail parsing library for Rust"
version = "0.1.0"
version = "0.2.0"
edition = "2018"
authors = [ "Stalwart Labs <hello@stalw.art>"]
license = "Apache-2.0 OR MIT"
+26 -20
View File
@@ -1,20 +1,21 @@
# mail-parser
![crates.io](https://img.shields.io/crates/v/mail-parser)
![docs.rs](https://img.shields.io/docsrs/mail-parser)
![crates.io](https://img.shields.io/crates/l/mail-parser)
![Twitter Follow](https://img.shields.io/twitter/follow/stalwartlabs?style=social)
[![crates.io](https://img.shields.io/crates/v/mail-parser)](https://crates.io/crates/mail-parser)
[![build](https://github.com/stalwartlabs/mail-parser/actions/workflows/rust.yml/badge.svg)](https://github.com/stalwartlabs/mail-parser/actions/workflows/rust.yml)
[![docs.rs](https://img.shields.io/docsrs/mail-parser)](https://docs.rs/mail-parser)
[![crates.io](https://img.shields.io/crates/l/mail-parser)](http://www.apache.org/licenses/LICENSE-2.0)
[![Twitter Follow](https://img.shields.io/twitter/follow/stalwartlabs?style=social)](https://twitter.com/stalwartlabs)
_mail-parser_ is an **e-mail parsing library** written in Rust that fully conforms to the Internet Message Format standard (_RFC 5322_), the
Multipurpose Internet Mail Extensions (MIME; _RFC 2045 - 2049_) as well as other [internet messaging RFCs](#conformed-rfcs).
It also supports decoding messages in [41 different character sets](#supported-character-sets) including obsolete formats such as UTF-7.
All Unicode (UTF-*) and single-byte character sets are handled internally by the library while support for legacy multi-byte encodings of Chinese
and Japanse languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
and Japanese languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
In general, this library abides by the Postel's law or [Robustness Principle](https://en.wikipedia.org/wiki/Robustness_principle) which
states that an implementation must be conservative in its sending behavior and liberal in its receiving behavior. This means that
_mail-parser_ will make a best effort to parse non-conformat e-mail messages as long as these do not deviate too much from the standard.
_mail-parser_ will make a best effort to parse non-conformant e-mail messages as long as these do not deviate too much from the standard.
Unlike other e-mail parsing libraries that return nested representations of the different MIME parts in a message, this library
conforms to [RFC 8621, Section 4.1.4](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4) and provides a more human-friendly
@@ -23,18 +24,18 @@ HTML and plain text inline body parts is done automatically when the _alternativ
Performance and memory safety were two important factors while designing _mail-parser_:
- **Zero-copy parsing** is done in most cases (unless when decoding non-UTF8 text or when RFC2047/RFC2231 encoded parts are present).
Practically all strings and u8 slices returned by this library are `Cow<str>` or `Cow<[u8]>` references to the input raw message.
- Memory allocations are always avoided unless they are really necessary. In fact, all Base64 and Quoted-Printable parts are decoded in
place re-using the input buffer.
- [Perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function) is used for fast look-up of message header fields, character
set names and aliases, HTML entities as well as month names while parsing _Date_ fields.
- Fully battle-tested with millions of real-world e-mail messages dating from 1995 until today.
- **Zero-copy parsing**: Practically all strings returned by this library are `Cow<str>` references to the input raw message.
- **High performance Base64 decoding** based on Chromium's decoder ([the fastest non-SIMD decoder](https://github.com/lemire/fastbase64)).
- **Fast** parsing of message header fields, character set names and HTML entities using [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function).
- Written in **100% safe** Rust with no external dependencies.
- Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and
meticulously [tested with MIRI](#testing-fuzzing--benchmarking).
- Thoroughly **battle-tested** with millions of real-world e-mail messages dating from 1995 until today.
## Usage Example
```rust
let mut input = concat!(
let input = concat!(
"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)\n",
"To: \"Colleagues\": \"James Smythe\" <james@vandelay.com>; Friends:\n",
" jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;\n",
@@ -69,10 +70,9 @@ Performance and memory safety were two important factors while designing _mail-p
"--giddyup--\n",
"--festivus--\n",
)
.as_bytes()
.to_vec();
.as_bytes();
let message = Message::parse(&mut input[..]);
let message = Message::parse(input);
// Parses addresses (including comments), lists and groups
assert_eq!(
@@ -183,7 +183,7 @@ Performance and memory safety were two important factors while designing _mail-p
println!("{}", serde_yaml::to_string(&message).unwrap());
```
## Testing & Benchmarking
## Testing, Fuzzing & Benchmarking
To run the testsuite:
@@ -191,13 +191,19 @@ To run the testsuite:
$ cargo test --all-features
```
or, to run the testsuite using MIRI:
or, to run the testsuite with MIRI:
```bash
$ cargo +nightly miri test --all-features
```
and to run the benchmarks:
To fuzz the library with `cargo-fuzz`:
```bash
$ cargo +nightly fuzz run mail_parser
```
and, to run the benchmarks:
```bash
$ cargo +nightly bench --all-features
+17 -20
View File
@@ -17,7 +17,7 @@ use std::{fs, path::PathBuf};
use test::Bencher;
fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&mut [u8], &str)) {
fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&[u8], &str)) {
const SEPARATOR: &[u8] = "\n---- EXPECTED STRUCTURE ----\n".as_bytes();
println!("Benchmarking {}...\n", name);
@@ -63,13 +63,9 @@ fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&mut [u8], &str)) {
b.iter(|| {
for test_msg in &test_data {
let input_str = String::from_utf8_lossy(&test_msg);
let mut input_bytes = test_msg.clone();
fnc(&mut input_bytes[..], &input_str);
fnc(test_msg, String::from_utf8_lossy(&test_msg).as_ref());
}
});
}
#[bench]
@@ -79,23 +75,19 @@ fn bench_stalwart(b: &mut Bencher) {
});
}
/*
// These libraries do not support all RFCs and might be faster
// on the benchmarks as they skip certain encoded parts or fail
// while trying to parse the messages.
// Also no body conversion between HTML/text is done by these.
// on the benchmarks as they do not parse all header fields,
// do not decode encoded parts or fail while trying to parse the messages.
// Also no text body conversion between HTML/plain-text is done by these.
//
// To benchmark against these libraries, add to Cargo.toml dev-dependencies:
//
// email = "0.0.21"
// email-format = "0.8"
// email-parser = "0.5.0"
// email-parser = { version = "0.5.0", features=["headers", "mime"] }
// mailparse = "0.13"
#[bench]
fn bench_mailparse(b: &mut Bencher) {
bench_all_samples(b, "mailparse", |bytes, _str| {
mailparse::parse_mail(bytes).unwrap();
});
}
/*
#[bench]
fn bench_email_parser(b: &mut Bencher) {
@@ -104,6 +96,13 @@ fn bench_email_parser(b: &mut Bencher) {
});
}
#[bench]
fn bench_mailparse(b: &mut Bencher) {
bench_all_samples(b, "mailparse", |bytes, _str| {
mailparse::parse_mail(bytes).unwrap();
});
}
#[bench]
fn benchmark_email(b: &mut Bencher) {
bench_all_samples(b, "email", |_bytes, str| {
@@ -119,6 +118,4 @@ fn bench_email_format(b: &mut Bencher) {
});
}
*/
+150
View File
@@ -0,0 +1,150 @@
use mail_parser::{Addr, Address, BodyPart, Group, Message, MessagePart, MimeFieldGet};
fn main() {
let input = concat!(
"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)\n",
"To: \"Colleagues\": \"James Smythe\" <james@vandelay.com>; Friends:\n",
" jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;\n",
"Date: Sat, 20 Nov 2021 14:22:01 -0800\n",
"Subject: Why not both importing AND exporting? =?utf-8?b?4pi6?=\n",
"Content-Type: multipart/mixed; boundary=\"festivus\";\n\n",
"--festivus\n",
"Content-Type: text/html; charset=\"us-ascii\"\n",
"Content-Transfer-Encoding: base64\n\n",
"PGh0bWw+PHA+SSB3YXMgdGhpbmtpbmcgYWJvdXQgcXVpdHRpbmcgdGhlICZsZHF1bztle\n",
"HBvcnRpbmcmcmRxdW87IHRvIGZvY3VzIGp1c3Qgb24gdGhlICZsZHF1bztpbXBvcnRpbm\n",
"cmcmRxdW87LDwvcD48cD5idXQgdGhlbiBJIHRob3VnaHQsIHdoeSBub3QgZG8gYm90aD8\n",
"gJiN4MjYzQTs8L3A+PC9odG1sPg==\n",
"--festivus\n",
"Content-Type: message/rfc822\n\n",
"From: \"Cosmo Kramer\" <kramer@kramerica.com>\n",
"Subject: Exporting my book about coffee tables\n",
"Content-Type: multipart/mixed; boundary=\"giddyup\";\n\n",
"--giddyup\n",
"Content-Type: text/plain; charset=\"utf-16\"\n",
"Content-Transfer-Encoding: quoted-printable\n\n",
"=FF=FE=0C!5=D8\"=DD5=D8)=DD5=D8-=DD =005=D8*=DD5=D8\"=DD =005=D8\"=\n",
"=DD5=D85=DD5=D8-=DD5=D8,=DD5=D8/=DD5=D81=DD =005=D8*=DD5=D86=DD =\n",
"=005=D8=1F=DD5=D8,=DD5=D8,=DD5=D8(=DD =005=D8-=DD5=D8)=DD5=D8\"=\n",
"=DD5=D8=1E=DD5=D80=DD5=D8\"=DD!=00\n",
"--giddyup\n",
"Content-Type: image/gif; name*1=\"about \"; name*0=\"Book \";\n",
" name*2*=utf-8''%e2%98%95 tables.gif\n",
"Content-Transfer-Encoding: Base64\n",
"Content-Disposition: attachment\n\n",
"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\n",
"--giddyup--\n",
"--festivus--\n",
)
.as_bytes();
let message = Message::parse(input);
// Parses addresses (including comments), lists and groups
assert_eq!(
message.get_from(),
&Address::Address(Addr {
name: Some("Art Vandelay (Vandelay Industries)".into()),
address: Some("art@vandelay.com".into())
})
);
assert_eq!(
message.get_to(),
&Address::GroupList(vec![
Group {
name: Some("Colleagues".into()),
addresses: vec![Addr {
name: Some("James Smythe".into()),
address: Some("james@vandelay.com".into())
}]
},
Group {
name: Some("Friends".into()),
addresses: vec![
Addr {
name: None,
address: Some("jane@example.com".into())
},
Addr {
name: Some("John Smîth".into()),
address: Some("john@example.com".into())
}
]
}
])
);
assert_eq!(
message.get_date().unwrap().to_iso8601(),
"2021-11-20T14:22:01-08:00"
);
// RFC2047 support for encoded text in message readers
assert_eq!(
message.get_subject().unwrap(),
"Why not both importing AND exporting? ☺"
);
// HTML and text body parts are returned conforming to RFC8621, Section 4.1.4
assert_eq!(
message.get_html_body(0).unwrap().to_string(),
concat!(
"<html><p>I was thinking about quitting the &ldquo;exporting&rdquo; to ",
"focus just on the &ldquo;importing&rdquo;,</p><p>but then I thought,",
" why not do both? &#x263A;</p></html>"
)
);
// HTML parts are converted to plain text (and viceversa) when missing
assert_eq!(
message.get_text_body(0).unwrap().to_string(),
concat!(
"I was thinking about quitting the “exporting” to focus just on the",
" “importing”,\nbut then I thought, why not do both? ☺\n"
)
);
// Supports nested messages as well as multipart/digest
let nested_message = match message.get_attachment(0).unwrap() {
MessagePart::Message(v) => v,
_ => unreachable!(),
};
assert_eq!(
nested_message.get_subject().unwrap(),
"Exporting my book about coffee tables"
);
// Handles UTF-* as well as many legacy encodings
assert_eq!(
nested_message.get_text_body(0).unwrap().to_string(),
"ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
);
assert_eq!(
nested_message.get_html_body(0).unwrap().to_string(),
"<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
);
let nested_attachment = match nested_message.get_attachment(0).unwrap() {
MessagePart::Binary(v) => v,
_ => unreachable!(),
};
assert_eq!(nested_attachment.len(), 42);
// Full RFC2231 support for continuations and character sets
assert_eq!(
nested_attachment
.get_header()
.unwrap()
.get_content_type()
.unwrap()
.get_attribute("name")
.unwrap(),
"Book about ☕ tables.gif"
);
// Integrates with Serde
println!("{}", serde_json::to_string_pretty(&message).unwrap());
println!("{}", serde_yaml::to_string(&message).unwrap());
}
+3
View File
@@ -0,0 +1,3 @@
target
corpus
artifacts
+128
View File
@@ -0,0 +1,128 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "arbitrary"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "577b08a4acd7b99869f863c50011b01eb73424ccc798ecd996f2e24817adfca7"
[[package]]
name = "cc"
version = "1.0.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79c2681d6594606957bbb8631c4b90a7fcaaa72cdb714743a437b156d6a7eedd"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "encoding_rs"
version = "0.8.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a74ea89a0a1b98f6332de42c95baff457ada66d1cb4030f9ff151b2041a1c746"
dependencies = [
"cfg-if",
]
[[package]]
name = "libfuzzer-sys"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36a9a84a6e8b55dfefb04235e55edb2b9a2a18488fcae777a6bdaa6f06f1deb3"
dependencies = [
"arbitrary",
"cc",
"once_cell",
]
[[package]]
name = "mail-parser"
version = "0.1.1"
dependencies = [
"encoding_rs",
"serde",
"serde_bytes",
]
[[package]]
name = "mail-parser-fuzz"
version = "0.0.0"
dependencies = [
"libfuzzer-sys",
"mail-parser",
]
[[package]]
name = "once_cell"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
[[package]]
name = "proc-macro2"
version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba508cc11742c0dc5c1659771673afbab7a0efab23aa17e854cbab0837ed0b43"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_bytes"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16ae07dd2f88a366f15bd0632ba725227018c69a1c8550a927324f8eb8368bb9"
dependencies = [
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "1.0.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2afee18b8beb5a596ecb4a2dce128c719b4ba399d34126b9e4396e3f9860966"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "unicode-xid"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "mail-parser-fuzz"
version = "0.0.0"
authors = ["Automatically generated"]
publish = false
edition = "2018"
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
[dependencies.mail-parser]
path = ".."
# Prevent this from interfering with workspaces
[workspace]
members = ["."]
[[bin]]
name = "mail_parser"
path = "fuzz_targets/mail_parser.rs"
test = false
doc = false
+140
View File
@@ -0,0 +1,140 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser::{
decoders::{
base64::Base64Decoder,
charsets::{
map::get_charset_decoder,
single_byte::decoder_iso_8859_1,
utf::{decoder_utf16, decoder_utf16_be, decoder_utf16_le, decoder_utf7},
},
encoded_word::parse_encoded_word,
hex::decode_hex,
html::{add_html_token, html_to_text, text_to_html},
quoted_printable::QuotedPrintableDecoder,
},
parsers::{
fields::{
address::parse_address,
content_type::parse_content_type,
date::parse_date,
id::parse_id,
list::parse_comma_separared,
raw::{parse_and_ignore, parse_raw},
unstructured::parse_unstructured,
},
header::parse_header_name,
message_stream::MessageStream,
},
Message,
};
fuzz_target!(|data: &[u8]| {
// Fuzz every parsing function
for n_fuzz in 1..=24 {
let stream = MessageStream::new(&data);
match n_fuzz {
1 => {
parse_date(&stream, false);
}
2 => {
parse_address(&stream);
}
3 => {
parse_id(&stream);
}
4 => {
parse_comma_separared(&stream);
}
5 => {
parse_and_ignore(&stream);
}
6 => {
parse_raw(&stream);
}
7 => {
parse_unstructured(&stream);
}
8 => {
parse_content_type(&stream);
}
9 => {
parse_header_name(&stream);
}
10 => {
parse_encoded_word(&stream);
}
11 => {
stream.seek_next_part(b"\n");
}
12 => {
stream.get_bytes_to_boundary(b"\n");
}
13 => {
stream.get_bytes_to_boundary(&[]);
}
14 => {
stream.skip_crlf();
}
15 => {
stream.is_boundary_end(0);
}
16 => {
stream.skip_multipart_end();
}
17 => {
stream.decode_base64(b"\n", true);
}
18 => {
stream.decode_base64(b"\n", false);
}
19 => {
stream.decode_base64(&[], true);
}
20 => {
stream.decode_base64(&[], false);
}
21 => {
stream.decode_quoted_printable(b"\n\n", true); // QP Boundaries have to be at least 2 bytes long
}
22 => {
stream.decode_quoted_printable(b"\n\n", false); // QP Boundaries have to be at least 2 bytes long
}
23 => {
stream.decode_quoted_printable(&[], true);
}
24 => {
stream.decode_quoted_printable(&[], false);
}
0 | 25..=u32::MAX => unreachable!(),
}
}
// Fuzz HTML functions
let mut html_str = String::with_capacity(data.len());
let str_data = String::from_utf8_lossy(data);
add_html_token(&mut html_str, str_data.as_ref().as_bytes(), false);
html_to_text(&str_data);
text_to_html(&str_data);
// Fuzz decoding functions
decode_hex(data);
get_charset_decoder(data);
let decoders: &[for<'x> fn(&'x [u8]) -> String] = &[
decoder_utf7,
decoder_utf16_le,
decoder_utf16_be,
decoder_utf16,
decoder_iso_8859_1,
];
for decoder in decoders {
decoder(data);
}
// Fuzz the entire library
Message::parse(&data[..]);
});
+79 -133
View File
@@ -9,154 +9,100 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::parsers::message_stream::MessageStream;
#[repr(C)]
pub union Base64Chunk {
pub val: u32,
pub bytes: [u8; std::mem::size_of::<u32>()],
}
pub trait Base64Decoder<'x> {
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, bool, Option<&'x [u8]>);
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, Option<Cow<'x, [u8]>>);
}
// Miri does not play well with UnsafeCells, see https://github.com/rust-lang/miri/issues/1665
//
// When testing under Miri,
// (*data)[i] = val;
// is used instead of
// *(*data).get_unchecked_mut(i) = val;
//
impl<'x> Base64Decoder<'x> for MessageStream<'x> {
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, bool, Option<&'x [u8]>) {
unsafe {
let mut success = boundary.is_empty();
fn decode_base64(&self, boundary: &[u8], is_word: bool) -> (bool, Option<Cow<'x, [u8]>>) {
let mut success = boundary.is_empty();
let mut chunk = Base64Chunk { val: 0 };
let mut byte_count: u8 = 0;
let mut match_count: usize = 0;
let mut chunk: u32 = 0;
let mut byte_count: u8 = 0;
let mut match_count: usize = 0;
let data = &mut *self.data.get();
let data_len = (*data).len();
let start_pos = self.pos.get();
let mut read_pos = start_pos;
let stream_pos = &mut *self.pos.get();
let start_pos = *stream_pos;
let mut read_pos = *stream_pos;
let mut write_pos = *stream_pos;
let mut buf = Vec::with_capacity(self.data.len() - read_pos);
while read_pos < data_len {
let ch = (*data).get_unchecked(read_pos);
read_pos += 1;
if !success {
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
success = true;
break;
} else {
continue;
}
} else if match_count > 0 {
if ch == boundary.get_unchecked(0) {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
for ch in self.data[read_pos..].iter() {
read_pos += 1;
let val = BASE64_MAP
.get_unchecked(byte_count as usize)
.get_unchecked(*ch as usize);
if *val >= 0x01ffffff {
if *ch == b'=' {
match byte_count {
1 | 2 => {
#[cfg(miri)]
{
(*data)[write_pos] = *chunk.bytes.get_unchecked(0);
}
#[cfg(not(miri))]
{
*((*data).get_unchecked_mut(write_pos)) =
*chunk.bytes.get_unchecked(0);
}
write_pos += 1;
byte_count = 0;
}
3 => {
#[cfg(miri)]
{
(*data)[write_pos] = *chunk.bytes.get_unchecked(0);
(*data)[write_pos + 1] = *chunk.bytes.get_unchecked(1);
}
#[cfg(not(miri))]
{
(*data)
.get_unchecked_mut(write_pos..write_pos + 2)
.copy_from_slice(chunk.bytes.get_unchecked(0..2));
}
write_pos += 2;
byte_count = 0;
}
0 => (),
_ => {
success = false;
break;
}
}
} else if !(*ch).is_ascii_whitespace() || is_word {
success = false;
if !success {
if *ch == boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
success = true;
break;
} else {
continue;
}
continue;
}
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
chunk.val = *val;
} else {
chunk.val |= *val;
if byte_count == 0 {
#[cfg(miri)]
{
(*data)[write_pos] = *chunk.bytes.get_unchecked(0);
(*data)[write_pos + 1] = *chunk.bytes.get_unchecked(1);
(*data)[write_pos + 2] = *chunk.bytes.get_unchecked(2);
}
#[cfg(not(miri))]
{
(*data)
.get_unchecked_mut(write_pos..write_pos + 3)
.copy_from_slice(chunk.bytes.get_unchecked(0..3));
}
write_pos += 3;
} else if match_count > 0 {
if *ch == boundary[0] {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
*stream_pos = read_pos;
let val = BASE64_MAP[byte_count as usize][*ch as usize];
(
success,
false,
if write_pos > start_pos {
Some((*data).get_unchecked(start_pos..write_pos))
} else {
None
},
)
if val >= 0x01ffffff {
if *ch == b'=' {
match byte_count {
1 | 2 => {
buf.push(chunk.to_le_bytes()[0]);
byte_count = 0;
}
3 => {
buf.extend_from_slice(&chunk.to_le_bytes()[0..2]);
byte_count = 0;
}
0 => (),
_ => {
success = false;
break;
}
}
} else if !ch.is_ascii_whitespace() || is_word {
success = false;
break;
}
continue;
}
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
chunk = val;
} else {
chunk |= val;
if byte_count == 0 {
buf.extend_from_slice(&chunk.to_le_bytes()[0..3]);
}
}
}
self.pos.set(read_pos);
(
success,
if !buf.is_empty() {
buf.shrink_to_fit();
Some(buf.into())
} else {
None
},
)
}
}
@@ -220,14 +166,14 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let stream = MessageStream::new(unsafe { str.as_bytes_mut() });
let str = input.0.to_string();
let stream = MessageStream::new(str.as_bytes());
let (success, _, result) = stream.decode_base64(input.2.as_bytes(), input.3);
let (success, result) = stream.decode_base64(input.2.as_bytes(), input.3);
assert_eq!(success, !input.1.is_empty(), "Failed for '{:?}'", input.0);
if !input.1.is_empty() {
let result_str = std::str::from_utf8(result.unwrap()).unwrap();
let result_str = std::str::from_utf8(result.as_ref().unwrap().as_ref()).unwrap();
//println!("'{}' -> '{}'", input.0.escape_debug(), result_str.escape_debug());
assert_eq!(
result_str,
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -9,14 +9,12 @@
* except according to those terms.
*/
use std::borrow::Cow;
pub mod map;
pub mod multi_byte;
pub mod single_byte;
pub mod utf;
pub type DecoderFnc<'x> = fn(&'x [u8]) -> Cow<'x, str>;
pub type DecoderFnc<'x> = fn(&'x [u8]) -> String;
#[cfg(test)]
mod tests {
+11 -13
View File
@@ -9,8 +9,6 @@
* except according to those terms.
*/
use std::borrow::Cow;
#[cfg(feature = "full_encoding")]
use encoding_rs::*;
@@ -18,7 +16,7 @@ use encoding_rs::*;
use super::map::decoder_default;
#[cfg(feature = "full_encoding")]
fn multi_byte_decoder(mut decoder: Decoder, bytes: &[u8]) -> Cow<str> {
fn multi_byte_decoder(mut decoder: Decoder, bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len() * 3);
if let (CoderResult::OutputFull, _, _) = decoder.decode_to_string(bytes, &mut result, true) {
@@ -26,10 +24,10 @@ fn multi_byte_decoder(mut decoder: Decoder, bytes: &[u8]) -> Cow<str> {
}
result.shrink_to_fit();
result.into()
result
}
pub fn decoder_shift_jis(bytes: &[u8]) -> Cow<str> {
pub fn decoder_shift_jis(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(SHIFT_JIS.new_decoder(), bytes)
@@ -41,7 +39,7 @@ pub fn decoder_shift_jis(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_big5(bytes: &[u8]) -> Cow<str> {
pub fn decoder_big5(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(BIG5.new_decoder(), bytes)
@@ -53,7 +51,7 @@ pub fn decoder_big5(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_euc_jp(bytes: &[u8]) -> Cow<str> {
pub fn decoder_euc_jp(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(EUC_JP.new_decoder(), bytes)
@@ -65,7 +63,7 @@ pub fn decoder_euc_jp(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_euc_kr(bytes: &[u8]) -> Cow<str> {
pub fn decoder_euc_kr(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(EUC_KR.new_decoder(), bytes)
@@ -77,7 +75,7 @@ pub fn decoder_euc_kr(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_gb18030(bytes: &[u8]) -> Cow<str> {
pub fn decoder_gb18030(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(GB18030.new_decoder(), bytes)
@@ -89,7 +87,7 @@ pub fn decoder_gb18030(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_gbk(bytes: &[u8]) -> Cow<str> {
pub fn decoder_gbk(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(GBK.new_decoder(), bytes)
@@ -101,7 +99,7 @@ pub fn decoder_gbk(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_iso2022_jp(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso2022_jp(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(ISO_2022_JP.new_decoder(), bytes)
@@ -113,7 +111,7 @@ pub fn decoder_iso2022_jp(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_windows874(bytes: &[u8]) -> Cow<str> {
pub fn decoder_windows874(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(WINDOWS_874.new_decoder(), bytes)
@@ -125,7 +123,7 @@ pub fn decoder_windows874(bytes: &[u8]) -> Cow<str> {
}
}
pub fn decoder_ibm866(bytes: &[u8]) -> Cow<str> {
pub fn decoder_ibm866(bytes: &[u8]) -> String {
#[cfg(feature = "full_encoding")]
{
multi_byte_decoder(IBM866.new_decoder(), bytes)
+31 -33
View File
@@ -9,128 +9,126 @@
* except according to those terms.
*/
use std::borrow::Cow;
fn single_byte_decoder<'x>(table: &[char], bytes: &'x [u8]) -> Cow<'x, str> {
fn single_byte_decoder(table: &[char], bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len() * 2);
for byte in bytes {
result.push(unsafe { *table.get_unchecked(*byte as usize) });
result.push(table[*byte as usize]);
}
result.shrink_to_fit();
result.into()
result
}
pub fn decoder_iso_8859_1(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_1(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_1, bytes)
}
pub fn decoder_iso_8859_2(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_2(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_2, bytes)
}
pub fn decoder_iso_8859_3(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_3(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_3, bytes)
}
pub fn decoder_iso_8859_4(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_4(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_4, bytes)
}
pub fn decoder_iso_8859_5(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_5(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_5, bytes)
}
pub fn decoder_iso_8859_6(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_6(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_6, bytes)
}
pub fn decoder_iso_8859_7(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_7(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_7, bytes)
}
pub fn decoder_iso_8859_8(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_8(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_8, bytes)
}
pub fn decoder_iso_8859_9(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_9(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_9, bytes)
}
pub fn decoder_iso_8859_10(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_10(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_10, bytes)
}
pub fn decoder_iso_8859_13(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_13(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_13, bytes)
}
pub fn decoder_iso_8859_14(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_14(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_14, bytes)
}
pub fn decoder_iso_8859_15(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_15(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_15, bytes)
}
pub fn decoder_iso_8859_16(bytes: &[u8]) -> Cow<str> {
pub fn decoder_iso_8859_16(bytes: &[u8]) -> String {
single_byte_decoder(ISO_8859_16, bytes)
}
pub fn decoder_cp1250(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1250(bytes: &[u8]) -> String {
single_byte_decoder(CP1250, bytes)
}
pub fn decoder_cp1251(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1251(bytes: &[u8]) -> String {
single_byte_decoder(CP1251, bytes)
}
pub fn decoder_cp1252(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1252(bytes: &[u8]) -> String {
single_byte_decoder(CP1252, bytes)
}
pub fn decoder_cp1253(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1253(bytes: &[u8]) -> String {
single_byte_decoder(CP1253, bytes)
}
pub fn decoder_cp1254(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1254(bytes: &[u8]) -> String {
single_byte_decoder(CP1254, bytes)
}
pub fn decoder_cp1255(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1255(bytes: &[u8]) -> String {
single_byte_decoder(CP1255, bytes)
}
pub fn decoder_cp1256(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1256(bytes: &[u8]) -> String {
single_byte_decoder(CP1256, bytes)
}
pub fn decoder_cp1257(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1257(bytes: &[u8]) -> String {
single_byte_decoder(CP1257, bytes)
}
pub fn decoder_cp1258(bytes: &[u8]) -> Cow<str> {
pub fn decoder_cp1258(bytes: &[u8]) -> String {
single_byte_decoder(CP1258, bytes)
}
pub fn decoder_koi8_r(bytes: &[u8]) -> Cow<str> {
pub fn decoder_koi8_r(bytes: &[u8]) -> String {
single_byte_decoder(KOI8_R, bytes)
}
pub fn decoder_koi8_u(bytes: &[u8]) -> Cow<str> {
pub fn decoder_koi8_u(bytes: &[u8]) -> String {
single_byte_decoder(KOI8_U, bytes)
}
pub fn decoder_macintosh(bytes: &[u8]) -> Cow<str> {
pub fn decoder_macintosh(bytes: &[u8]) -> String {
single_byte_decoder(MACINTOSH, bytes)
}
pub fn decoder_ibm_850(bytes: &[u8]) -> Cow<str> {
pub fn decoder_ibm_850(bytes: &[u8]) -> String {
single_byte_decoder(IBM850, bytes)
}
pub fn decoder_tis_620(bytes: &[u8]) -> Cow<str> {
pub fn decoder_tis_620(bytes: &[u8]) -> String {
single_byte_decoder(TIS_620, bytes)
}
+26 -40
View File
@@ -9,38 +9,32 @@
* except according to those terms.
*/
use std::{
borrow::Cow,
char::{decode_utf16, REPLACEMENT_CHARACTER},
};
use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
use crate::decoders::base64::{Base64Chunk, BASE64_MAP};
use crate::decoders::base64::BASE64_MAP;
struct Utf7DecoderState {
utf16_bytes: Vec<u16>,
pending_byte: Option<u8>,
b64_bytes: Base64Chunk,
b64_bytes: u32,
}
fn add_utf16_bytes(state: &mut Utf7DecoderState, n_bytes: usize) {
debug_assert!(n_bytes < std::mem::size_of::<u32>());
// Safe because n_bytes is always lower than size_of::<u32>
unsafe {
for byte in state.b64_bytes.bytes.get_unchecked(0..n_bytes) {
if let Some(pending_byte) = state.pending_byte {
state
.utf16_bytes
.push(u16::from_be_bytes([pending_byte, *byte]));
state.pending_byte = None;
} else {
state.pending_byte = Some(*byte);
}
for byte in state.b64_bytes.to_le_bytes()[0..n_bytes].iter() {
if let Some(pending_byte) = state.pending_byte {
state
.utf16_bytes
.push(u16::from_be_bytes([pending_byte, *byte]));
state.pending_byte = None;
} else {
state.pending_byte = Some(*byte);
}
}
}
pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
pub fn decoder_utf7(bytes: &[u8]) -> String {
let mut result = String::with_capacity(bytes.len());
let mut byte_count: u8 = 0;
let mut in_b64 = false;
@@ -48,28 +42,20 @@ pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
let mut state = Utf7DecoderState {
utf16_bytes: Vec::with_capacity(10),
pending_byte: None,
b64_bytes: Base64Chunk { val: 0 },
b64_bytes: 0,
};
for byte in bytes {
if in_b64 {
// Safe because BASEMAP size is [4][u8::MAX]
let val = unsafe {
BASE64_MAP
.get_unchecked(byte_count as usize)
.get_unchecked(*byte as usize)
};
let val = BASE64_MAP[byte_count as usize][*byte as usize];
if *val < 0x01ffffff {
if val < 0x01ffffff {
byte_count = (byte_count + 1) & 3;
if byte_count == 1 {
state.b64_bytes.val = *val;
state.b64_bytes = val;
} else {
// Safe union read/write
unsafe {
state.b64_bytes.val |= *val;
}
state.b64_bytes |= val;
if byte_count == 0 {
add_utf16_bytes(&mut state, 3);
@@ -112,30 +98,29 @@ pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
}
result.shrink_to_fit();
result.into()
result
}
fn decoder_utf16_(bytes: &[u8], fnc: fn([u8; 2]) -> u16) -> Cow<str> {
fn decoder_utf16_(bytes: &[u8], fnc: fn([u8; 2]) -> u16) -> String {
if bytes.len() >= 2 {
decode_utf16(bytes.chunks_exact(2).map(|c| fnc([c[0], c[1]])))
.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
.collect::<String>()
.into()
} else {
"".into()
"".to_string()
}
}
pub fn decoder_utf16_le(bytes: &[u8]) -> Cow<str> {
pub fn decoder_utf16_le(bytes: &[u8]) -> String {
decoder_utf16_(bytes, u16::from_le_bytes)
}
pub fn decoder_utf16_be(bytes: &[u8]) -> Cow<str> {
pub fn decoder_utf16_be(bytes: &[u8]) -> String {
decoder_utf16_(bytes, u16::from_be_bytes)
}
#[allow(clippy::type_complexity)]
pub fn decoder_utf16(bytes: &[u8]) -> Cow<str> {
pub fn decoder_utf16(bytes: &[u8]) -> String {
// Read BOM
let (bytes, fnc): (&[u8], fn([u8; 2]) -> u16) = match bytes.get(0..2) {
Some([0xfe, 0xff]) => (bytes.get(2..).unwrap_or(&[]), u16::from_be_bytes),
@@ -146,8 +131,9 @@ pub fn decoder_utf16(bytes: &[u8]) -> Cow<str> {
decoder_utf16_(bytes, fnc)
}
pub fn decoder_utf8(bytes: &[u8]) -> Cow<str> {
String::from_utf8_lossy(bytes)
// Not currently used at the moment
pub fn decoder_utf8(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
#[cfg(test)]
+9 -13
View File
@@ -9,8 +9,6 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::{
decoders::{
base64::Base64Decoder, charsets::map::get_charset_decoder,
@@ -19,9 +17,7 @@ use crate::{
parsers::message_stream::MessageStream,
};
use super::charsets::map::decoder_default;
pub fn parse_encoded_word<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
pub fn parse_encoded_word(stream: &MessageStream) -> Option<String> {
if !stream.skip_byte(&b'?') {
return None;
}
@@ -55,12 +51,12 @@ pub fn parse_encoded_word<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
return None;
}
let (success, is_utf8_safe, bytes) = match stream.next() {
let (success, bytes) = match stream.next() {
Some(b'q') | Some(b'Q') if stream.skip_byte(&b'?') => {
stream.decode_quoted_printable(b"?=", true)
}
Some(b'b') | Some(b'B') if stream.skip_byte(&b'?') => stream.decode_base64(b"?=", true),
_ => (false, false, None),
_ => (false, None),
};
if !success {
@@ -71,11 +67,11 @@ pub fn parse_encoded_word<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
if let Some(decoder) =
get_charset_decoder(stream.get_bytes(charset_start, charset_end).unwrap())
{
decoder(bytes?).into()
} else if is_utf8_safe {
unsafe { Cow::from(std::str::from_utf8_unchecked(bytes?)).into() }
decoder(bytes?.as_ref()).into()
} else {
decoder_default(bytes?).into()
String::from_utf8(bytes?.into_owned())
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
}
@@ -165,9 +161,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
match parse_encoded_word(&MessageStream::new(unsafe { str.as_bytes_mut() })) {
match parse_encoded_word(&MessageStream::new(str.as_bytes())) {
Some(string) => {
//println!("Decoded '{}'", string);
assert_eq!(string, input.1);
+2 -2
View File
@@ -39,7 +39,7 @@ pub fn decode_hex(src: &[u8]) -> (bool, Vec<u8>) {
result.push(*ch);
}
HexState::Percent => {
hex1 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
hex1 = HEX_MAP[*ch as usize];
if hex1 != -1 {
state = HexState::Hex1;
} else {
@@ -48,7 +48,7 @@ pub fn decode_hex(src: &[u8]) -> (bool, Vec<u8>) {
}
}
HexState::Hex1 => {
let hex2 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
let hex2 = HEX_MAP[*ch as usize];
state = HexState::None;
if hex2 != -1 {
+21 -27
View File
@@ -30,36 +30,32 @@ pub fn add_html_token(result: &mut String, token: &[u8], add_space: bool) {
} else if (2..=31).contains(&entity.len()) {
let mut hash = entity.len() as u32;
/* Safe because ENTITY_HASH's size is 260 (u8::MAX + 5)
and ENTITY_MAP's size is 18016 (18079 - 64 + 1) */
debug_assert_eq!(ENTITY_HASH.len(), u8::MAX as usize + 5);
debug_assert_eq!(ENTITY_MAP.len(), 18079 - 64 + 1);
unsafe {
for (pos, ch) in entity.iter().enumerate() {
match pos {
0 | 5 | 6 | 9 | 11 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize);
}
1 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize + 4);
}
2 | 4 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize + 1);
}
3 => {
hash += *ENTITY_HASH.get_unchecked(*ch as usize + 3);
}
_ => (),
for (pos, ch) in entity.iter().enumerate() {
match pos {
0 | 5 | 6 | 9 | 11 => {
hash += ENTITY_HASH[*ch as usize];
}
if pos == entity.len() - 1 {
hash += *ENTITY_HASH.get_unchecked(*ch as usize);
1 => {
hash += ENTITY_HASH[*ch as usize + 4];
}
2 | 4 => {
hash += ENTITY_HASH[*ch as usize + 1];
}
3 => {
hash += ENTITY_HASH[*ch as usize + 3];
}
_ => (),
}
if pos == entity.len() - 1 {
hash += ENTITY_HASH[*ch as usize];
}
}
if (64..=18079).contains(&hash) {
entity_code = *ENTITY_MAP.get_unchecked((hash - 64) as usize);
}
if (64..=18079).contains(&hash) {
entity_code = ENTITY_MAP[(hash - 64) as usize];
}
}
@@ -69,9 +65,7 @@ pub fn add_html_token(result: &mut String, token: &[u8], add_space: bool) {
}
}
// Safe because the input string is tokenized by ASCII chars, therefore the resulting
// u8 array is UTF-8 safe.
result.push_str(unsafe { std::str::from_utf8_unchecked(token) });
result.push_str(std::str::from_utf8(token).unwrap());
}
pub fn html_to_text(input: &str) -> String {
@@ -237,7 +231,7 @@ pub fn text_to_html(input: &str) -> String {
}
result.extend_from_slice(b"</body></html>");
unsafe { String::from_utf8_unchecked(result) }
String::from_utf8(result).unwrap()
}
#[cfg(test)]
+129 -161
View File
@@ -9,6 +9,8 @@
* except according to those terms.
*/
use std::borrow::Cow;
use crate::parsers::message_stream::MessageStream;
#[derive(PartialEq, Debug)]
@@ -23,192 +25,146 @@ pub trait QuotedPrintableDecoder<'x> {
&self,
boundary: &[u8],
is_word: bool,
) -> (bool, bool, Option<&'x [u8]>);
) -> (bool, Option<Cow<'x, [u8]>>);
}
// Miri does not play well with UnsafeCells, see https://github.com/rust-lang/miri/issues/1665
//
// When testing under Miri,
// (*data)[i] = val;
// is used instead of
// *(*data).get_unchecked_mut(i) = val;
//
impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
fn decode_quoted_printable(
&self,
boundary: &[u8],
is_word: bool,
) -> (bool, bool, Option<&'x [u8]>) {
unsafe {
let mut success = boundary.is_empty();
let mut is_utf8_safe = true;
) -> (bool, Option<Cow<'x, [u8]>>) {
let mut success = boundary.is_empty();
let mut data = &mut *self.data.get();
let data_len = (*data).len();
let start_pos = self.pos.get();
let mut read_pos = start_pos;
let stream_pos = &mut *self.pos.get();
let start_pos = *stream_pos;
let mut read_pos = *stream_pos;
let mut write_pos = *stream_pos;
let mut buf = Vec::with_capacity(self.data.len() - read_pos);
let mut state = QuotedPrintableState::None;
let mut match_count = 0;
let mut hex1 = 0;
let mut state = QuotedPrintableState::None;
let mut match_count = 0;
let mut hex1 = 0;
while read_pos < data_len {
let ch = *(*data).get_unchecked(read_pos);
read_pos += 1;
debug_assert!(boundary.is_empty() || boundary.len() >= 2);
if !success {
if ch == *boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
let done = is_word || self.is_boundary_end(read_pos);
data = &mut *self.data.get(); // Avoid violating the Stacked Borrows rules
for ch in self.data[read_pos..].iter() {
read_pos += 1;
if done {
success = true;
break;
}
// if success is false, a boundary was provided
if !success {
let mut is_boundary_end = true;
if *ch == boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
let done = if is_word {
true
} else {
continue;
is_boundary_end = self.is_boundary_end(read_pos);
is_boundary_end
};
if done {
success = true;
break;
}
} else {
continue;
}
}
if match_count > 0 {
for ch in boundary[..match_count].iter() {
if *ch != b'\n' || QuotedPrintableState::Eq != state {
buf.push(*ch);
}
}
state = QuotedPrintableState::None;
if match_count > 0 {
for ch in boundary[..match_count].iter() {
if *ch != b'\n' || QuotedPrintableState::Eq != state {
#[cfg(miri)]
{
(*data)[write_pos] = *ch;
}
#[cfg(not(miri))]
{
*((*data).get_unchecked_mut(write_pos)) = *ch;
}
write_pos += 1;
if is_utf8_safe && *ch > 0x7f {
is_utf8_safe = false;
}
}
}
state = QuotedPrintableState::None;
if ch == *boundary.get_unchecked(0) {
// is_boundary_end is always true except in the rare event
// that a boundary was found without a proper MIME ending (-- or \r\n)
if is_boundary_end {
if *ch == boundary[0] {
// Char matched beginning of boundary, get next char.
match_count = 1;
continue;
} else {
// Reset match count and decode character
match_count = 0;
}
} else {
// There was a full boundary match but without a proper MIME
// ending, reset match count and continue.
match_count = 0;
continue;
}
}
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
} else {
success = false;
break;
}
}
b'\n' => {
if is_word {
success = false;
break;
} else if QuotedPrintableState::Eq == state {
state = QuotedPrintableState::None;
} else {
#[cfg(miri)]
{
(*data)[write_pos] = b'\n';
}
#[cfg(not(miri))]
{
*((*data).get_unchecked_mut(write_pos)) = b'\n';
}
write_pos += 1;
}
}
b'_' if is_word => {
#[cfg(miri)]
{
(*data)[write_pos] = b' ';
}
#[cfg(not(miri))]
{
*((*data).get_unchecked_mut(write_pos)) = b' ';
}
write_pos += 1;
}
b'\r' => (),
_ => match state {
QuotedPrintableState::None => {
#[cfg(miri)]
{
(*data)[write_pos] = ch;
}
#[cfg(not(miri))]
{
*((*data).get_unchecked_mut(write_pos)) = ch;
}
write_pos += 1;
if is_utf8_safe && ch > 0x7f {
is_utf8_safe = false;
}
}
QuotedPrintableState::Eq => {
hex1 = *HEX_MAP.get_unchecked(ch as usize);
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
success = false;
break;
}
}
QuotedPrintableState::Hex1 => {
let hex2 = *HEX_MAP.get_unchecked(ch as usize);
state = QuotedPrintableState::None;
if hex2 != -1 {
let ch = ((hex1 as u8) << 4) | hex2 as u8;
#[cfg(miri)]
{
(*data)[write_pos] = ch;
}
#[cfg(not(miri))]
{
*((*data).get_unchecked_mut(write_pos)) = ch;
}
write_pos += 1;
if is_utf8_safe && ch > 0x7f {
is_utf8_safe = false;
}
} else {
success = false;
break;
}
}
},
}
}
*stream_pos = read_pos;
match ch {
b'=' => {
if let QuotedPrintableState::None = state {
state = QuotedPrintableState::Eq
} else {
success = false;
break;
}
}
b'\n' => {
if is_word {
success = false;
break;
} else if QuotedPrintableState::Eq == state {
state = QuotedPrintableState::None;
} else {
buf.push(b'\n');
}
}
b'_' if is_word => {
buf.push(b' ');
}
b'\r' => (),
_ => match state {
QuotedPrintableState::None => {
buf.push(*ch);
}
QuotedPrintableState::Eq => {
hex1 = HEX_MAP[*ch as usize];
if hex1 != -1 {
state = QuotedPrintableState::Hex1;
} else {
success = false;
break;
}
}
QuotedPrintableState::Hex1 => {
let hex2 = HEX_MAP[*ch as usize];
(
success,
is_utf8_safe,
if write_pos > start_pos {
Some((*data).get_unchecked(start_pos..write_pos))
} else {
None
state = QuotedPrintableState::None;
if hex2 != -1 {
let ch = ((hex1 as u8) << 4) | hex2 as u8;
buf.push(ch);
} else {
success = false;
break;
}
}
},
)
}
}
self.pos.set(read_pos);
(
success,
if !buf.is_empty() {
buf.shrink_to_fit();
Some(buf.into())
} else {
None
},
)
}
}
@@ -289,15 +245,15 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let stream = MessageStream::new(unsafe { str.as_bytes_mut() });
let str = input.0.to_string();
let stream = MessageStream::new(str.as_bytes());
let (success, _, result) = stream.decode_quoted_printable(input.2.as_bytes(), input.3);
let (success, result) = stream.decode_quoted_printable(input.2.as_bytes(), input.3);
assert_eq!(success, !input.1.is_empty(), "Failed for '{:?}'", input.0);
if !input.1.is_empty() {
let result_str = std::str::from_utf8(result.unwrap()).unwrap();
let result_str = std::str::from_utf8(result.as_ref().unwrap()).unwrap();
/*println!(
"Decoded '{}'\n -> to ->\n'{}'\n{}",
@@ -314,6 +270,18 @@ mod tests {
);
}
}
// MIRI overflow tests
for input in [b"\x0a\x0a\x00\x0b".to_vec(), b":B\x0a%".to_vec()] {
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(b"\n\n", true);
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(b"\n\n", false);
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(&[], true);
let stream = MessageStream::new(&input[..]);
stream.decode_quoted_printable(&[], false);
}
}
}
+330 -112
View File
@@ -10,37 +10,37 @@
*/
//! # mail-parser
//!
//!
//! _mail-parser_ is an **e-mail parsing library** written in Rust that fully conforms to the Internet Message Format standard (_RFC 5322_), the
//! Multipurpose Internet Mail Extensions (MIME; _RFC 2045 - 2049_) as well as other [internet messaging RFCs](#conformed-rfcs).
//!
//!
//! It also supports decoding messages in [41 different character sets](#supported-character-sets) including obsolete formats such as UTF-7.
//! All Unicode (UTF-*) and single-byte character sets are handled internally by the library while support for legacy multi-byte encodings of Chinese
//! and Japanse languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
//!
//! In general, this library abides by the Postel's law or [Robustness Principle](https://en.wikipedia.org/wiki/Robustness_principle) which
//! and Japanese languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
//!
//! In general, this library abides by the Postel's law or [Robustness Principle](https://en.wikipedia.org/wiki/Robustness_principle) which
//! states that an implementation must be conservative in its sending behavior and liberal in its receiving behavior. This means that
//! _mail-parser_ will make a best effort to parse non-conformat e-mail messages as long as these do not deviate too much from the standard.
//!
//! Unlike other e-mail parsing libraries that return nested representations of the different MIME parts in a message, this library
//! _mail-parser_ will make a best effort to parse non-conformant e-mail messages as long as these do not deviate too much from the standard.
//!
//! Unlike other e-mail parsing libraries that return nested representations of the different MIME parts in a message, this library
//! conforms to [RFC 8621, Section 4.1.4](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4) and provides a more human-friendly
//! representation of the message contents consisting of just text body parts, html body parts and attachments. Additionally, conversion to/from
//! HTML and plain text inline body parts is done automatically when the _alternative_ version is missing.
//!
//!
//! Performance and memory safety were two important factors while designing _mail-parser_:
//!
//! - **Zero-copy parsing** is done in most cases (unless when decoding non-UTF8 text or when RFC2047/RFC2231 encoded parts are present).
//! Practically all strings and u8 slices returned by this library are `Cow<str>` or `Cow<[u8]>` references to the input raw message.
//! - Memory allocations are always avoided unless they are really necessary. In fact, all Base64 and Quoted-Printable parts are decoded in
//! place re-using the input buffer.
//! - [Perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function) is used for fast look-up of message header fields, character
//! set names and aliases, HTML entities as well as month names while parsing _Date_ fields.
//! - Fully battle-tested with millions of real-world e-mail messages dating from 1995 until today.
//!
//!
//! - **Zero-copy parsing**: Practically all strings returned by this library are `Cow<str>` references to the input raw message.
//! - **High performance Base64 decoding** based on Chromium's decoder ([the fastest non-SIMD decoder](https://github.com/lemire/fastbase64)).
//! - **Fast** parsing of message header fields, character set names and HTML entities using [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function).
//! - Written in **100% safe** Rust with no external dependencies.
//! - Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and
//! meticulously [tested with MIRI](#testing-fuzzing--benchmarking).
//! - Thoroughly **battle-tested** with millions of real-world e-mail messages dating from 1995 until today.
//!
//! Jump to the [example](#usage-example).
//!
//!
//! ## Conformed RFCs
//!
//!
//! - [RFC 822 - Standard for ARPA Internet Text Messages](https://datatracker.ietf.org/doc/html/rfc822)
//! - [RFC 5322 - Internet Message Format](https://datatracker.ietf.org/doc/html/rfc5322)
//! - [RFC 2045 - Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies](https://datatracker.ietf.org/doc/html/rfc2045)
@@ -55,60 +55,60 @@
//! - [RFC 2369 - The Use of URLs as Meta-Syntax for Core Mail List Commands and their Transport through Message Header Fields](https://datatracker.ietf.org/doc/html/rfc2369)
//! - [RFC 2919 - List-Id: A Structured Field and Namespace for the Identification of Mailing Lists](https://datatracker.ietf.org/doc/html/rfc2919)
//! - [RFC 8621 - The JSON Meta Application Protocol (JMAP) for Mail (Section 4.1.4)](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4)
//!
//!
//! ## Supported Character Sets
//!
//!
//! - UTF-8
//! - UTF-16, UTF-16BE, UTF-16LE
//! - UTF-7
//! - US-ASCII
//! - ISO-8859-1
//! - ISO-8859-2
//! - ISO-8859-3
//! - ISO-8859-4
//! - ISO-8859-5
//! - ISO-8859-6
//! - ISO-8859-7
//! - ISO-8859-8
//! - ISO-8859-9
//! - ISO-8859-10
//! - ISO-8859-13
//! - ISO-8859-14
//! - ISO-8859-15
//! - ISO-8859-1
//! - ISO-8859-2
//! - ISO-8859-3
//! - ISO-8859-4
//! - ISO-8859-5
//! - ISO-8859-6
//! - ISO-8859-7
//! - ISO-8859-8
//! - ISO-8859-9
//! - ISO-8859-10
//! - ISO-8859-13
//! - ISO-8859-14
//! - ISO-8859-15
//! - ISO-8859-16
//! - CP1250
//! - CP1251
//! - CP1252
//! - CP1253
//! - CP1254
//! - CP1255
//! - CP1256
//! - CP1257
//! - CP1250
//! - CP1251
//! - CP1252
//! - CP1253
//! - CP1254
//! - CP1255
//! - CP1256
//! - CP1257
//! - CP1258
//! - KOI8-R
//! - KOI8_U
//! - MACINTOSH
//! - IBM850
//! - TIS-620
//!
//!
//! Supported character sets via the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs):
//!
//! - SHIFT_JIS
//! - BIG5
//! - EUC-JP
//! - EUC-KR
//! - EUC-JP
//! - EUC-KR
//! - GB18030
//! - GBK
//! - ISO-2022-JP
//! - ISO-2022-JP
//! - WINDOWS-874
//! - IBM-866
//!
//!
//! ## Usage Example
//!
//!
//! ```
//! use mail_parser::*;
//!
//! let mut input = concat!(
//!
//! let input = concat!(
//! "From: Art Vandelay <art@vandelay.com> (Vandelay Industries)\n",
//! "To: \"Colleagues\": \"James Smythe\" <james@vandelay.com>; Friends:\n",
//! " jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;\n",
@@ -143,10 +143,9 @@
//! "--giddyup--\n",
//! "--festivus--\n",
//! )
//! .as_bytes()
//! .to_vec();
//! .as_bytes();
//!
//! let message = Message::parse(&mut input[..]);
//! let message = Message::parse(input);
//!
//! // Parses addresses (including comments), lists and groups
//! assert_eq!(
@@ -193,7 +192,7 @@
//! "Why not both importing AND exporting? ☺"
//! );
//!
//! // HTML and text body parts are returned conforming to RFC8621, Section 4.1.4
//! // HTML and text body parts are returned conforming to RFC8621, Section 4.1.4
//! assert_eq!(
//! message.get_html_body(0).unwrap().to_string(),
//! concat!(
@@ -257,9 +256,8 @@
//! println!("{}", serde_yaml::to_string(&message).unwrap());
//!```
mod decoders;
mod parsers;
pub mod decoders;
pub mod parsers;
use std::{borrow::Cow, collections::HashMap, fmt, slice::Iter};
@@ -272,13 +270,22 @@ use serde::{Deserialize, Serialize};
pub struct Message<'x> {
#[cfg_attr(feature = "serde_support", serde(borrow))]
header: Box<MessageHeader<'x>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Vec::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Vec::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
html_body: Vec<InlinePart<'x>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Vec::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Vec::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
text_body: Vec<InlinePart<'x>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Vec::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Vec::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
attachments: Vec<MessagePart<'x>>,
}
@@ -287,7 +294,10 @@ pub struct Message<'x> {
#[derive(Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct TextPart<'x> {
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
header: Option<MimeHeader<'x>>,
contents: Cow<'x, str>,
@@ -297,7 +307,10 @@ pub struct TextPart<'x> {
#[derive(Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct BinaryPart<'x> {
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
header: Option<MimeHeader<'x>>,
#[cfg_attr(feature = "serde_support", serde(with = "serde_bytes"))]
@@ -315,12 +328,12 @@ pub enum InlinePart<'x> {
}
/// A text, binary or nested e-mail MIME message part.
///
///
/// - Text: Any text/* part
/// - Binary: Any other part type that is not text, usually attachments.
/// - InlineBinary: Same as the Binary variant but an inline part according to RFC 8621, Section 4.1.4
/// - Message: A nested RFC5322 message.
///
///
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub enum MessagePart<'x> {
@@ -343,113 +356,221 @@ pub enum MessagePart<'x> {
#[derive(PartialEq, Debug, Default)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct MessageHeader<'x> {
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub bcc: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub cc: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub comments: Option<Vec<Cow<'x, str>>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub date: Option<DateTime>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub from: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub in_reply_to: Option<Vec<Cow<'x, str>>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub keywords: Option<Vec<Cow<'x, str>>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub list_archive: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub list_help: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub list_id: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub list_owner: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub list_post: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub list_subscribe: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub list_unsubscribe: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub message_id: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub mime_version: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub received: Option<Vec<Cow<'x, str>>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub references: Option<Vec<Cow<'x, str>>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub reply_to: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub resent_bcc: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub resent_cc: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub resent_date: Option<Vec<DateTime>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub resent_from: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub resent_message_id: Option<Vec<Cow<'x, str>>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub resent_sender: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub resent_to: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub return_path: Option<Vec<Cow<'x, str>>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub sender: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub subject: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Address::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Address::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub to: Address<'x>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_description: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_disposition: Option<ContentType<'x>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_id: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_transfer_encoding: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_type: Option<ContentType<'x>>,
#[cfg_attr(feature = "serde_support", serde(borrow))]
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "HashMap::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "HashMap::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub others: HashMap<&'x str, Vec<Cow<'x, str>>>,
}
@@ -458,19 +579,34 @@ pub struct MessageHeader<'x> {
#[derive(PartialEq, Debug, Default)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct MimeHeader<'x> {
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_description: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_disposition: Option<ContentType<'x>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_id: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_transfer_encoding: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub content_type: Option<ContentType<'x>>,
}
@@ -480,12 +616,18 @@ pub struct MimeHeader<'x> {
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Addr<'x> {
/// The address name including comments
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub name: Option<Cow<'x, str>>,
/// An e-mail address (RFC5322/RFC2369) or URL (RFC2369)
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub address: Option<Cow<'x, str>>,
}
@@ -495,12 +637,18 @@ pub struct Addr<'x> {
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct Group<'x> {
/// Group name
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub name: Option<Cow<'x, str>>,
/// Addressess member of the group
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Vec::is_empty"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Vec::is_empty")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
pub addresses: Vec<Addr<'x>>,
}
@@ -533,10 +681,16 @@ pub enum Address<'x> {
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct ContentType<'x> {
c_type: Cow<'x, str>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
c_subtype: Option<Cow<'x, str>>,
#[cfg_attr(feature = "serde_support", serde(skip_serializing_if = "Option::is_none"))]
#[cfg_attr(
feature = "serde_support",
serde(skip_serializing_if = "Option::is_none")
)]
#[cfg_attr(feature = "serde_support", serde(default))]
attributes: Option<HashMap<Cow<'x, str>, Cow<'x, str>>>,
}
@@ -784,6 +938,70 @@ impl<'x> Message<'x> {
}
}
impl<'x> MessageHeader<'x> {
pub fn is_empty(&self) -> bool {
for addr in [
&self.from,
&self.to,
&self.cc,
&self.bcc,
&self.reply_to,
&self.sender,
&self.resent_to,
&self.resent_from,
&self.resent_bcc,
&self.resent_cc,
&self.resent_sender,
&self.list_archive,
&self.list_help,
&self.list_id,
&self.list_owner,
&self.list_post,
&self.list_subscribe,
&self.list_unsubscribe,
] {
if !addr.is_empty() {
return false;
}
}
for str in [
&self.subject,
&self.message_id,
&self.mime_version,
&self.content_description,
&self.content_id,
&self.content_transfer_encoding,
] {
if str.is_some() {
return false;
}
}
if self.date.is_some() || !self.others.is_empty() {
return false;
}
for vec in [
&self.comments,
&self.in_reply_to,
&self.keywords,
&self.received,
&self.references,
&self.resent_message_id,
&self.return_path,
] {
if vec.is_some() {
return false;
}
}
self.content_disposition.is_none()
&& self.resent_date.is_none()
&& self.content_type.is_none()
}
}
impl<'x> MimeFieldGet<'x> for Message<'x> {
fn get_content_description(&self) -> Option<&Cow<'x, str>> {
self.header.content_description.as_ref()
+6 -17
View File
@@ -40,7 +40,6 @@ pub struct AddressParser<'x> {
token_start: usize,
token_end: usize,
is_token_safe: bool,
is_token_email: bool,
is_token_start: bool,
is_escaped: bool,
@@ -65,11 +64,7 @@ pub fn add_token<'x>(
) {
if parser.token_start > 0 {
let token = stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap();
let mut add_space = false;
let list = match parser.state {
@@ -100,7 +95,6 @@ pub fn add_token<'x>(
}
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_email = false;
parser.is_token_start = true;
parser.is_escaped = false;
@@ -238,7 +232,6 @@ pub fn parse_address<'x>(stream: &MessageStream<'x>) -> Address<'x> {
token_start: 0,
token_end: 0,
is_token_safe: true,
is_token_email: false,
is_token_start: true,
is_escaped: false,
@@ -323,7 +316,7 @@ pub fn parse_address<'x>(stream: &MessageStream<'x>) -> Address<'x> {
} else {
&mut parser.comment_tokens
})
.push(token);
.push(token.into());
continue;
}
}
@@ -373,12 +366,7 @@ pub fn parse_address<'x>(stream: &MessageStream<'x>) -> Address<'x> {
add_group(&mut parser);
continue;
}
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_escaped {
@@ -941,8 +929,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let result = parse_address(&MessageStream::new(unsafe { str.as_bytes_mut() }));
println!("Testiong {}", input.0);
let str = input.0.to_string();
let result = parse_address(&MessageStream::new(str.as_bytes()));
let expected: Address = serde_yaml::from_str(input.1).unwrap_or(Address::Empty);
/*if input.0.len() >= 70 {
+20 -46
View File
@@ -16,9 +16,7 @@ use std::{
use crate::{
decoders::{
charsets::map::{decoder_default, get_charset_decoder},
encoded_word::parse_encoded_word,
hex::decode_hex,
charsets::map::get_charset_decoder, encoded_word::parse_encoded_word, hex::decode_hex,
},
parsers::message_stream::MessageStream,
ContentType,
@@ -58,24 +56,18 @@ struct ContentTypeParser<'x> {
is_encoded_attribute: bool,
is_escaped: bool,
is_lower_case: bool,
is_token_safe: bool,
is_token_start: bool,
}
#[inline(always)]
fn reset_parser(parser: &mut ContentTypeParser) {
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_start = true;
}
fn add_attribute<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>) -> bool {
if parser.token_start > 0 {
let mut attr = stream.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
);
let mut attr = stream.get_string(parser.token_start - 1, parser.token_end);
if !parser.is_lower_case {
attr.as_mut().unwrap().to_mut().make_ascii_lowercase();
@@ -99,11 +91,7 @@ fn add_attribute<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<
fn add_attribute_parameter<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>) {
if parser.token_start > 0 {
let attr_part = stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap();
if parser.attr_charset.is_none() {
@@ -143,7 +131,6 @@ fn add_partial_value<'x>(
} else {
parser.token_end
},
parser.is_token_safe,
)
.unwrap(),
);
@@ -162,11 +149,7 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>)
let has_values = !parser.values.is_empty();
let value = if parser.token_start > 0 {
stream.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
stream.get_string(parser.token_start - 1, parser.token_end)
} else {
if !has_values {
return;
@@ -200,16 +183,17 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>)
if parser.is_encoded_attribute {
if let (true, decoded_bytes) = decode_hex(value.as_bytes()) {
value = get_charset_decoder(
parser
.attr_charset
.as_ref()
.unwrap_or(&"utf-8".into())
.as_bytes(),
)
.unwrap_or(decoder_default)(&decoded_bytes)
.into_owned()
.into();
value = if let Some(decoder) = parser
.attr_charset
.as_ref()
.and_then(|c| get_charset_decoder(c.as_bytes()))
{
decoder(&decoded_bytes).into()
} else {
String::from_utf8(decoded_bytes)
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
}
parser.is_encoded_attribute = false;
}
@@ -240,11 +224,7 @@ fn add_value<'x>(parser: &mut ContentTypeParser<'x>, stream: &MessageStream<'x>)
fn add_attr_position(parser: &mut ContentTypeParser, stream: &MessageStream) -> bool {
if parser.token_start > 0 {
parser.attr_position = stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap()
.parse()
.unwrap_or(0);
@@ -288,7 +268,6 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
is_continuation: false,
is_encoded_attribute: false,
is_lower_case: true,
is_token_safe: true,
is_token_start: true,
is_escaped: false,
@@ -418,7 +397,7 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
{
if let Some(token) = parse_encoded_word(stream) {
add_partial_value(&mut parser, stream, false);
parser.values.push(token);
parser.values.push(token.into());
continue;
}
}
@@ -496,12 +475,7 @@ pub fn parse_content_type<'x>(stream: &MessageStream<'x>) -> Option<ContentType<
continue;
}
b'\r' => continue,
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_escaped {
@@ -1353,9 +1327,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
let result = parse_content_type(&MessageStream::new(unsafe { str.as_bytes_mut() }));
let result = parse_content_type(&MessageStream::new(str.as_bytes()));
let expected: Option<ContentType> = serde_yaml::from_str(input.1).unwrap_or(None);
/*
+7 -8
View File
@@ -115,10 +115,9 @@ pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<Date
b'a'..=b'z' | b'A'..=b'Z' => {
if pos == 1 {
if (1..=2).contains(&month_pos) {
month_hash += unsafe {
*MONTH_HASH
.get_unchecked((if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize)
} as usize;
month_hash += MONTH_HASH
[(if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize]
as usize;
}
month_pos += 1;
}
@@ -157,7 +156,7 @@ pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<Date
parts[2]
},
month: if month_pos == 3 && month_hash <= 30 {
(unsafe { *MONTH_MAP.get_unchecked(month_hash) }) as u32
MONTH_MAP[month_hash] as u32
} else {
parts[1]
},
@@ -188,7 +187,7 @@ static MONTH_HASH: &[u8] = &[
31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31,
];
pub static MONTH_MAP: &[u8] = &[
pub static MONTH_MAP: &[u8; 31] = &[
5, 0, 0, 0, 10, 3, 0, 0, 0, 7, 1, 0, 0, 0, 12, 6, 0, 0, 0, 8, 4, 0, 0, 0, 2, 9, 0, 0, 0, 0, 11,
];
@@ -259,8 +258,8 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
match parse_date(&MessageStream::new(unsafe { str.as_bytes_mut() }), false) {
let str = input.0.to_string();
match parse_date(&MessageStream::new(str.as_bytes()), false) {
Some(date) => {
//println!("{} -> {}", input.0.escape_debug(), date.to_iso8601());
assert_eq!(input.1, date.to_iso8601());
+4 -15
View File
@@ -16,7 +16,6 @@ use crate::parsers::message_stream::MessageStream;
pub fn parse_id<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'x, str>>> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut is_token_safe = true;
let mut is_id_part = false;
let mut ids = Vec::new();
@@ -36,24 +35,14 @@ pub fn parse_id<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'x, str>>> {
b'>' => {
is_id_part = false;
if token_start > 0 {
ids.push(
stream
.get_string(token_start - 1, token_end, is_token_safe)
.unwrap(),
);
is_token_safe = true;
ids.push(stream.get_string(token_start - 1, token_end).unwrap());
token_start = 0;
} else {
continue;
}
}
b' ' | b'\t' | b'\r' => continue,
0..=0x7f => (),
_ => {
if is_token_safe {
is_token_safe = false;
}
}
_ => (),
}
if is_id_part {
if token_start == 0 {
@@ -103,10 +92,10 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
input.1,
parse_id(&MessageStream::new(unsafe { str.as_bytes_mut() })).unwrap(),
parse_id(&MessageStream::new(str.as_bytes())).unwrap(),
"Failed to parse '{:?}'",
input.0
);
+5 -17
View File
@@ -16,7 +16,6 @@ use crate::{decoders::encoded_word::parse_encoded_word, parsers::message_stream:
struct ListParser<'x> {
token_start: usize,
token_end: usize,
is_token_safe: bool,
is_token_start: bool,
tokens: Vec<Cow<'x, str>>,
list: Vec<Cow<'x, str>>,
@@ -29,11 +28,7 @@ fn add_token<'x>(parser: &mut ListParser<'x>, stream: &MessageStream<'x>, add_sp
}
parser.tokens.push(
stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap(),
);
@@ -42,7 +37,6 @@ fn add_token<'x>(parser: &mut ListParser<'x>, stream: &MessageStream<'x>, add_sp
}
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_start = true;
}
}
@@ -63,7 +57,6 @@ pub fn parse_comma_separared<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'
let mut parser = ListParser {
token_start: 0,
token_end: 0,
is_token_safe: true,
is_token_start: true,
tokens: Vec::new(),
list: Vec::new(),
@@ -101,7 +94,7 @@ pub fn parse_comma_separared<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'
b'=' if parser.is_token_start => {
if let Some(token) = parse_encoded_word(stream) {
add_token(&mut parser, stream, true);
parser.tokens.push(token);
parser.tokens.push(token.into());
continue;
}
}
@@ -111,12 +104,7 @@ pub fn parse_comma_separared<'x>(stream: &MessageStream<'x>) -> Option<Vec<Cow<'
continue;
}
b'\r' => continue,
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_token_start {
@@ -177,9 +165,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
parse_comma_separared(&MessageStream::new(unsafe { str.as_bytes_mut() }),).unwrap(),
parse_comma_separared(&MessageStream::new(str.as_bytes()),).unwrap(),
input.1
);
}
+4 -10
View File
@@ -16,7 +16,6 @@ use crate::parsers::message_stream::MessageStream;
pub fn parse_raw<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut is_token_safe = true;
while let Some(ch) = stream.next() {
match ch {
@@ -28,7 +27,7 @@ pub fn parse_raw<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
_ => {
return if token_start > 0 {
stream
.get_string(token_start - 1, token_end, is_token_safe)
.get_string(token_start - 1, token_end)
.unwrap()
.into()
} else {
@@ -37,12 +36,7 @@ pub fn parse_raw<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>> {
}
},
b' ' | b'\t' | b'\r' => continue,
0..=0x7f => (),
_ => {
if is_token_safe {
is_token_safe = false;
}
}
_ => (),
}
if token_start == 0 {
@@ -93,9 +87,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
parse_raw(&MessageStream::new(unsafe { str.as_bytes_mut() })).unwrap(),
parse_raw(&MessageStream::new(str.as_bytes())).unwrap(),
input.1,
"Failed for '{:?}'",
input.0
+5 -17
View File
@@ -15,7 +15,6 @@ use crate::{decoders::encoded_word::parse_encoded_word, parsers::message_stream:
struct UnstructuredParser<'x> {
token_start: usize,
token_end: usize,
is_token_safe: bool,
is_token_start: bool,
tokens: Vec<Cow<'x, str>>,
}
@@ -27,11 +26,7 @@ fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &MessageStream<'x>
}
parser.tokens.push(
stream
.get_string(
parser.token_start - 1,
parser.token_end,
parser.is_token_safe,
)
.get_string(parser.token_start - 1, parser.token_end)
.unwrap(),
);
@@ -40,7 +35,6 @@ fn add_token<'x>(parser: &mut UnstructuredParser<'x>, stream: &MessageStream<'x>
}
parser.token_start = 0;
parser.is_token_safe = true;
parser.is_token_start = true;
}
}
@@ -49,7 +43,6 @@ pub fn parse_unstructured<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
let mut parser = UnstructuredParser {
token_start: 0,
token_end: 0,
is_token_safe: true,
is_token_start: true,
tokens: Vec::new(),
};
@@ -85,17 +78,12 @@ pub fn parse_unstructured<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
b'=' if parser.is_token_start => {
if let Some(token) = parse_encoded_word(stream) {
add_token(&mut parser, stream, true);
parser.tokens.push(token);
parser.tokens.push(token.into());
continue;
}
}
b'\r' => continue,
0..=0x7f => (),
_ => {
if parser.is_token_safe {
parser.is_token_safe = false;
}
}
_ => (),
}
if parser.is_token_start {
@@ -191,9 +179,9 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
let str = input.0.to_string();
assert_eq!(
parse_unstructured(&MessageStream::new(unsafe { str.as_bytes_mut() }),).unwrap(),
parse_unstructured(&MessageStream::new(str.as_bytes()),).unwrap(),
input.1,
"Failed to parse '{:?}'",
input.0
+11 -19
View File
@@ -45,7 +45,7 @@ impl<'x> MimeHeader<'x> {
}
}
enum HeaderParserResult<'x> {
pub enum HeaderParserResult<'x> {
Supported(fn(&mut dyn MessageField<'x>, &MessageStream<'x>)),
Unsupported(&'x [u8]),
Lf,
@@ -63,7 +63,7 @@ pub fn parse_headers<'x>(header: &mut dyn MessageField<'x>, stream: &MessageStre
}
}
fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'x> {
pub fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'x> {
let mut token_start: usize = 0;
let mut token_end: usize = 0;
let mut token_len: usize = 0;
@@ -77,20 +77,14 @@ fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'x> {
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;
token_hash +=
token_len + HDR_HASH[last_ch.to_ascii_lowercase() as usize] as usize;
if (4..=61).contains(&token_hash) {
let token_hash = token_hash - 4;
if field.eq_ignore_ascii_case(unsafe {
HDR_NAMES.get_unchecked(token_hash)
}) {
return HeaderParserResult::Supported(unsafe {
*HDR_FNCS.get_unchecked(token_hash)
});
if field.eq_ignore_ascii_case(HDR_NAMES[token_hash]) {
return HeaderParserResult::Supported(HDR_FNCS[token_hash]);
}
}
}
@@ -112,9 +106,7 @@ fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'x> {
}
if let 0 | 9 = token_len {
token_hash +=
unsafe { *HDR_HASH.get_unchecked((*ch).to_ascii_lowercase() as usize) }
as usize;
token_hash += HDR_HASH[(*ch).to_ascii_lowercase() as usize] as usize;
}
token_len += 1;
}
@@ -159,8 +151,8 @@ mod tests {
];
for input in inputs {
let mut str = input.0.to_string();
match parse_header_name(&MessageStream::new(unsafe { str.as_bytes_mut() })) {
let str = input.0.to_string();
match parse_header_name(&MessageStream::new(str.as_bytes())) {
HeaderParserResult::Supported(f) => {
if let HeaderParserResult::Supported(val) = input.1 {
if f as usize == val as usize {
@@ -196,7 +188,7 @@ static HDR_HASH: &[u8] = &[
62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62, 62,
];
static HDR_FNCS: &[for<'x, 'y> fn(&mut dyn MessageField<'x>, &MessageStream<'x>)] = &[
static HDR_FNCS: &[for<'x, 'y> fn(&mut dyn MessageField<'x>, &MessageStream<'x>); 58] = &[
super::fields::parse_date,
super::fields::parse_no_op,
super::fields::parse_sender,
@@ -257,7 +249,7 @@ static HDR_FNCS: &[for<'x, 'y> fn(&mut dyn MessageField<'x>, &MessageStream<'x>)
super::fields::parse_resent_from,
];
static HDR_NAMES: &[&[u8]] = &[
static HDR_NAMES: &[&[u8]; 58] = &[
b"date",
b"",
b"sender",
+26 -38
View File
@@ -14,12 +14,11 @@ use std::borrow::Cow;
use crate::{
decoders::{
base64::Base64Decoder,
charsets::map::{decoder_default, get_charset_decoder},
charsets::map::get_charset_decoder,
html::{html_to_text, text_to_html},
quoted_printable::QuotedPrintableDecoder,
},
MessagePart, BinaryPart, InlinePart, ContentType, Message, MessageHeader, MimeHeader,
TextPart,
BinaryPart, ContentType, InlinePart, Message, MessageHeader, MessagePart, MimeHeader, TextPart,
};
use super::{fields::MessageField, header::parse_headers, message_stream::MessageStream};
@@ -39,24 +38,18 @@ enum MimeType {
}
#[inline(always)]
fn bytes_to_string<'x>(
bytes: &'x [u8],
content_type: Option<&ContentType>,
is_utf8_safe: bool,
) -> Cow<'x, str> {
fn bytes_to_string<'x>(bytes: Cow<'x, [u8]>, content_type: Option<&ContentType>) -> Cow<'x, str> {
if let Some(content_type) = content_type {
if let Some(charset) = content_type.get_attribute("charset") {
if let Some(decoder_fnc) = get_charset_decoder(charset.as_bytes()) {
return decoder_fnc(bytes);
return decoder_fnc(bytes.as_ref()).into();
}
}
}
if !is_utf8_safe {
decoder_default(bytes)
} else {
(unsafe { std::str::from_utf8_unchecked(bytes) }).into()
}
String::from_utf8(bytes.into_owned())
.unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
.into()
}
#[inline(always)]
@@ -130,16 +123,19 @@ impl<'x> Message<'x> {
}
}
/// Parses a byte slice containing the RFC5322 raw message and returns a
/// Returns `false` if at least one header field was successfully parsed.
pub fn is_empty(&self) -> bool {
self.header.is_empty()
}
/// Parses a byte slice containing the RFC5322 raw message and returns a
/// `Message` struct.
///
///
/// This function never panics, a best-effort is made to parse the message and
/// if no headers are found and empty `Message` struct is returned.
///
/// Note: The `parse()` function requires a mutable `[u8]` as input in order
/// to perform BASE64/Quoted-Printable decoding in-place.
///
pub fn parse(bytes: &'x mut [u8]) -> Message<'x> {
/// To make sure parsing was successfull use `is_empty()`.
///
pub fn parse(bytes: &'x [u8]) -> Message<'x> {
let stream = MessageStream::new(bytes);
let mut message = Message::new();
@@ -219,9 +215,7 @@ impl<'x> Message<'x> {
stream.skip_crlf();
let (success, mut is_utf8_safe, mut bytes) = match header
.get_content_transfer_encoding()
{
let (success, mut bytes) = match header.get_content_transfer_encoding() {
Some(encoding) if encoding.eq_ignore_ascii_case("base64") => stream.decode_base64(
state
.mime_boundary
@@ -249,7 +243,7 @@ impl<'x> Message<'x> {
if !success {
if !stream.is_eof() {
// Get raw MIME part
let (success, r_is_utf8_safe, r_bytes) = stream.get_bytes_to_boundary(
let (success, r_bytes) = stream.get_bytes_to_boundary(
state
.mime_boundary
.as_ref()
@@ -258,10 +252,8 @@ impl<'x> Message<'x> {
if !success {
// 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(&[][..]);
let (_, r_bytes) = stream.get_bytes_to_boundary(&[][..]);
if r_bytes.is_some() {
is_utf8_safe = r_is_utf8_safe;
bytes = r_bytes;
} else {
break;
@@ -270,7 +262,6 @@ impl<'x> Message<'x> {
break;
}
} else {
is_utf8_safe = r_is_utf8_safe;
bytes = r_bytes;
}
mime_type = MimeType::TextOther;
@@ -319,9 +310,8 @@ impl<'x> Message<'x> {
if is_text {
let text_part = TextPart {
contents: bytes_to_string(
bytes.map_or_else(|| "\n".as_bytes(), |v| v),
bytes.unwrap_or_else(|| vec![b'\n'].into()),
header.get_content_type(),
is_utf8_safe,
),
header: if !mime_part_header.is_empty() {
Some(std::mem::take(&mut mime_part_header))
@@ -358,7 +348,7 @@ impl<'x> Message<'x> {
} else {
None
},
contents: bytes.map_or_else(|| "?".as_bytes(), |v| v).into(),
contents: bytes.unwrap_or_else(|| Cow::from(vec![b'?'])),
};
if add_to_html {
@@ -388,9 +378,7 @@ impl<'x> Message<'x> {
if let (Some(mut prev_message), Some(mut prev_state)) =
(message_stack.pop(), state_stack.pop())
{
prev_message
.attachments
.push(MessagePart::Message(message));
prev_message.attachments.push(MessagePart::Message(message));
message = prev_message;
prev_state.mime_boundary = state.mime_boundary;
state = prev_state;
@@ -466,9 +454,7 @@ impl<'x> Message<'x> {
}
while let Some(mut prev_message) = message_stack.pop() {
prev_message
.attachments
.push(MessagePart::Message(message));
prev_message.attachments.push(MessagePart::Message(message));
message = prev_message;
}
@@ -516,6 +502,8 @@ mod tests {
let input = input.split_at_mut(pos);
let message = Message::parse(input.0);
assert!(!message.is_empty());
assert_eq!(
message,
serde_json::from_slice::<Message>(&input.1[SEPARATOR.len()..]).unwrap(),
+98 -146
View File
@@ -9,110 +9,86 @@
* except according to those terms.
*/
use std::{borrow::Cow, cell::UnsafeCell};
use std::{borrow::Cow, cell::Cell};
pub struct MessageStream<'x> {
pub data: UnsafeCell<&'x mut [u8]>,
pub pos: UnsafeCell<usize>,
pub data: &'x [u8],
pub pos: Cell<usize>,
}
impl<'x> MessageStream<'x> {
pub fn new(data: &'x mut [u8]) -> MessageStream<'x> {
pub fn new(data: &'x [u8]) -> MessageStream<'x> {
MessageStream {
data: data.into(),
data,
pos: 0.into(),
}
}
#[inline(always)]
pub fn get_bytes(&self, from: usize, to: usize) -> Option<&'x [u8]> {
unsafe { (*self.data.get()).get(from..to) }
self.data.get(from..to)
}
pub fn get_string(&self, from: usize, to: usize, utf8_valid: bool) -> Option<Cow<'x, str>> {
unsafe {
if utf8_valid {
Cow::from(std::str::from_utf8_unchecked(
(*self.data.get()).get(from..to)?,
))
.into()
} else {
String::from_utf8_lossy((*self.data.get()).get(from..to)?).into()
}
}
pub fn get_string(&self, from: usize, to: usize) -> Option<Cow<'x, str>> {
String::from_utf8_lossy(self.data.get(from..to)?).into()
}
#[inline(always)]
pub fn is_eof(&self) -> bool {
unsafe { *self.pos.get() >= (*self.data.get()).len() }
self.pos.get() >= self.data.len()
}
#[inline(always)]
pub fn set_pos(&self, pos: usize) {
unsafe {
*self.pos.get() = pos;
}
self.pos.set(pos);
}
#[inline(always)]
pub fn get_pos(&self) -> usize {
unsafe { *self.pos.get() }
self.pos.get()
}
#[inline(always)]
pub fn next(&self) -> Option<&'x u8> {
unsafe {
let pos = &mut *self.pos.get();
let data = &mut *self.data.get();
if *pos < data.len() {
let result = data.get_unchecked(*pos);
*pos += 1;
Some(result)
} else {
None
}
}
let pos = self.pos.get();
let result = self.data.get(pos);
self.pos.set(pos + 1);
result
}
#[inline(always)]
pub fn peek(&self) -> Option<&'x u8> {
unsafe { (*self.data.get()).get(*self.pos.get()) }
self.data.get(self.pos.get())
}
#[inline(always)]
pub fn advance(&self, pos: usize) {
unsafe {
*self.pos.get() += pos;
}
self.pos.set(self.pos.get() + pos)
}
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();
let mut pos = *cur_pos;
let mut match_count = 0;
let mut pos = self.pos.get();
for ch in (*data)[*cur_pos..].iter() {
pos += 1;
let mut match_count = 0;
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
*cur_pos = pos;
return true;
} else {
continue;
}
} else if match_count > 0 {
if ch == boundary.get_unchecked(0) {
match_count = 1;
continue;
} else {
match_count = 0;
}
for ch in self.data[pos..].iter() {
pos += 1;
if ch == &boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
self.pos.set(pos);
return true;
} else {
continue;
}
} else if match_count > 0 {
if ch == &boundary[0] {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
@@ -121,134 +97,110 @@ impl<'x> MessageStream<'x> {
false
}
pub fn get_bytes_to_boundary(&self, boundary: &[u8]) -> (bool, bool, Option<&'x [u8]>) {
unsafe {
let mut data = &mut *self.data.get();
pub fn get_bytes_to_boundary(&self, boundary: &[u8]) -> (bool, Option<Cow<'x, [u8]>>) {
let mut pos = self.pos.get();
let stream_pos = &mut *self.pos.get();
let start_pos = *stream_pos;
let start_pos = pos;
return if !boundary.is_empty() {
let mut pos = *stream_pos;
let mut match_count = 0;
let mut is_utf8_safe = true;
return if !boundary.is_empty() {
let mut match_count = 0;
for ch in (*data)[pos..].iter() {
pos += 1;
for ch in self.data[pos..].iter() {
pos += 1;
if is_utf8_safe && *ch > 0x7f {
is_utf8_safe = false;
}
if ch == &boundary[match_count] {
match_count += 1;
if match_count == boundary.len() {
if self.is_boundary_end(pos) {
let match_pos = pos - match_count;
self.pos.set(pos);
if ch == boundary.get_unchecked(match_count) {
match_count += 1;
if match_count == boundary.len() {
let is_boundary_end = self.is_boundary_end(pos);
data = &mut *self.data.get(); // Avoid violating the Stacked Borrows rules
if is_boundary_end {
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 {
match_count = 0;
}
}
continue;
} else if match_count > 0 {
if ch == boundary.get_unchecked(0) {
match_count = 1;
continue;
return (
true,
if start_pos < match_pos {
Cow::from(&self.data[start_pos..match_pos]).into()
} else {
None
},
);
} else {
match_count = 0;
}
}
continue;
} else if match_count > 0 {
if ch == &boundary[0] {
match_count = 1;
continue;
} else {
match_count = 0;
}
}
}
(false, false, None)
} else if *stream_pos < (*data).len() {
*stream_pos = (*data).len();
(true, false, (*data).get(start_pos..))
} else {
(false, false, None)
};
}
(false, None)
} else if pos < self.data.len() {
self.pos.set(self.data.len());
(true, Cow::from(&self.data[start_pos..]).into())
} else {
(false, None)
};
}
#[inline(always)]
pub fn skip_crlf(&self) {
unsafe {
let cur_pos = &mut *self.pos.get();
let data = &mut *self.data.get();
let mut pos = *cur_pos;
let mut pos = self.pos.get();
for ch in (*data)[*cur_pos..].iter() {
match ch {
b'\r' | b' ' | b'\t' => pos += 1,
b'\n' => {
*cur_pos = pos + 1;
break;
}
_ => break,
for ch in self.data[pos..].iter() {
match ch {
b'\r' | b' ' | b'\t' => pos += 1,
b'\n' => {
self.pos.set(pos + 1);
break;
}
_ => break,
}
}
}
#[inline(always)]
pub fn skip_byte(&self, ch: &u8) -> bool {
unsafe {
let pos = &mut *self.pos.get();
let data = &mut *self.data.get();
let pos = self.pos.get();
if (*data).get(*pos) == Some(ch) {
*pos += 1;
true
} else {
false
}
if self.data.get(pos) == Some(ch) {
self.pos.set(pos + 1);
true
} else {
false
}
}
#[inline(always)]
pub fn is_boundary_end(&self, pos: usize) -> bool {
matches!(
unsafe { (*self.data.get()).get(pos..) },
self.data.get(pos..),
Some([b'\n' | b'\r' | b' ' | b'\t', ..]) | Some([b'-', b'-', ..]) | Some([]) | None
)
}
pub fn skip_multipart_end(&self) -> bool {
unsafe {
let pos = &mut *self.pos.get();
let pos = self.pos.get();
match (*self.data.get()).get(*pos..*pos + 2) {
Some(b"--") => {
if let Some(byte) = (*self.data.get()).get(*pos + 2) {
if !(*byte).is_ascii_whitespace() {
return false;
}
match self.data.get(pos..pos + 2) {
Some(b"--") => {
if let Some(byte) = self.data.get(pos + 2) {
if !(*byte).is_ascii_whitespace() {
return false;
}
*pos += 2;
true
}
_ => false,
self.pos.set(pos + 2);
true
}
_ => false,
}
}
pub fn rewind(&self, r: usize) {
unsafe {
*self.pos.get() -= r;
}
self.pos.set(self.pos.get() - r);
}
}
-1
View File
@@ -143,5 +143,4 @@ fn test_api() {
//println!("{}", serde_json::to_string_pretty(&message).unwrap());
//println!("{}", serde_yaml::to_string(&message).unwrap());
}