mirror of
https://github.com/stalwartlabs/mail-parser.git
synced 2026-11-29 00:01:49 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee2d08be07 | ||
|
|
1717f803db | ||
|
|
549e8d2428 | ||
|
|
972b4d6dfc | ||
|
|
5d4c4a06c7 | ||
|
|
17833a57b4 | ||
|
|
52a90c3eff | ||
|
|
31bb44cc29 | ||
|
|
24e17cf675 | ||
|
|
73af8a971e | ||
|
|
847359ae39 | ||
|
|
419a9a9fad | ||
|
|
80c7b78646 | ||
|
|
4eebde1020 | ||
|
|
260fd98d7d |
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
language: rust
|
||||
rust:
|
||||
- stable
|
||||
- beta
|
||||
- nightly
|
||||
matrix:
|
||||
allow_failures:
|
||||
- rust: nightly
|
||||
Generated
+1
-1
@@ -59,7 +59,7 @@ checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
|
||||
|
||||
[[package]]
|
||||
name = "mail-parser"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"serde",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "mail-parser"
|
||||
description = "Fast and robust e-mail parsing library for Rust"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
edition = "2018"
|
||||
authors = [ "Stalwart Labs <hello@stalw.art>"]
|
||||
license = "Apache-2.0 OR MIT"
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
# mail-parser
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
[](https://crates.io/crates/mail-parser)
|
||||
[](https://github.com/stalwartlabs/mail-parser/actions/workflows/rust.yml)
|
||||
[](https://docs.rs/mail-parser)
|
||||
[](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
[](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
|
||||
@@ -29,6 +30,8 @@ Performance and memory safety were two important factors while designing _mail-p
|
||||
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.
|
||||
- Although some `unsafe` code was used to obtain performance gains of about 10%, every function in the library has been
|
||||
[fuzzed](#testing-fuzzing--benchmarking) and also heavily [tested with MIRI](#testing-fuzzing--benchmarking).
|
||||
- Fully battle-tested with millions of real-world e-mail messages dating from 1995 until today.
|
||||
|
||||
## Usage Example
|
||||
@@ -183,7 +186,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 +194,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
|
||||
|
||||
+15
-15
@@ -69,7 +69,6 @@ fn bench_all_samples(b: &mut Bencher, name: &str, fnc: fn(&mut [u8], &str)) {
|
||||
fnc(&mut input_bytes[..], &input_str);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
#[bench]
|
||||
@@ -79,23 +78,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 +99,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 +121,4 @@ fn bench_email_format(b: &mut Bencher) {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
use mail_parser::{Addr, Address, BodyPart, Group, Message, MessagePart, MimeFieldGet};
|
||||
|
||||
fn main() {
|
||||
let mut 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()
|
||||
.to_vec();
|
||||
|
||||
let message = Message::parse(&mut 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 “exporting” to ",
|
||||
"focus just on the “importing”,</p><p>but then I thought,",
|
||||
" why not do both? ☺</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());
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
target
|
||||
corpus
|
||||
artifacts
|
||||
Generated
+128
@@ -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.0"
|
||||
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"
|
||||
@@ -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
|
||||
@@ -0,0 +1,143 @@
|
||||
#![no_main]
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use std::borrow::Cow;
|
||||
|
||||
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 mut data = Vec::from(data);
|
||||
let stream = MessageStream::new(&mut 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());
|
||||
add_html_token(&mut html_str, data, false);
|
||||
let html_str = String::from_utf8_lossy(data);
|
||||
html_to_text(&html_str);
|
||||
text_to_html(&html_str);
|
||||
|
||||
// Fuzz decoding functions
|
||||
decode_hex(data);
|
||||
get_charset_decoder(data);
|
||||
|
||||
let decoders: &[for<'x> fn(&'x [u8]) -> Cow<'x, str>] = &[
|
||||
decoder_utf7,
|
||||
decoder_utf16_le,
|
||||
decoder_utf16_be,
|
||||
decoder_utf16,
|
||||
decoder_iso_8859_1,
|
||||
];
|
||||
|
||||
for decoder in decoders {
|
||||
decoder(data);
|
||||
}
|
||||
|
||||
// Fuzz the entire library
|
||||
let mut data = Vec::from(data);
|
||||
Message::parse(&mut data[..]);
|
||||
});
|
||||
@@ -49,7 +49,7 @@ impl<'x> Base64Decoder<'x> for MessageStream<'x> {
|
||||
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;
|
||||
|
||||
@@ -29,22 +29,27 @@ pub fn get_charset_decoder<'x>(charset: &[u8]) -> Option<DecoderFnc<'x>> {
|
||||
} else {
|
||||
*ch
|
||||
};
|
||||
// SAFE: `pos` is always lower than 45
|
||||
unsafe {
|
||||
*l_charset.get_unchecked_mut(pos) = ch;
|
||||
}
|
||||
if let 0 | 3 | 6 | 7 | 8 | 9 = pos {
|
||||
// SAFE: CH_HASH's size is u8::MAX
|
||||
hash += unsafe { *CH_HASH.get_unchecked(ch as usize) };
|
||||
}
|
||||
if pos == charset.len() - 1 {
|
||||
// SAFE: CH_HASH's size is u8::MAX
|
||||
hash += unsafe { *CH_HASH.get_unchecked(ch as usize) };
|
||||
}
|
||||
}
|
||||
|
||||
if (7..=764).contains(&hash) {
|
||||
let hash = (hash - 7) as usize;
|
||||
// SAFE: CH_MAP's size is 758
|
||||
let &ch_map = unsafe { CH_MAP.get_unchecked(hash) };
|
||||
|
||||
if l_charset[..charset.len()].eq(ch_map) {
|
||||
// SAFE: FNC_MAP's size is 758
|
||||
return Some(unsafe { *FNC_MAP.get_unchecked(hash) });
|
||||
}
|
||||
}
|
||||
@@ -101,7 +106,7 @@ static CH_HASH: &[u32] = &[
|
||||
765,
|
||||
];
|
||||
|
||||
static CH_MAP: &[&[u8]] = &[
|
||||
static CH_MAP: &[&[u8]; 758] = &[
|
||||
b"l8",
|
||||
b"",
|
||||
b"",
|
||||
@@ -863,7 +868,7 @@ static CH_MAP: &[&[u8]] = &[
|
||||
];
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
static FNC_MAP: &[for<'x> fn(&'x [u8]) -> Cow<'x, str>] = &[
|
||||
static FNC_MAP: &[for<'x> fn(&'x [u8]) -> Cow<'x, str>; 758] = &[
|
||||
decoder_iso_8859_14,
|
||||
decoder_default,
|
||||
decoder_default,
|
||||
|
||||
@@ -15,6 +15,7 @@ fn single_byte_decoder<'x>(table: &[char], bytes: &'x [u8]) -> Cow<'x, str> {
|
||||
let mut result = String::with_capacity(bytes.len() * 2);
|
||||
|
||||
for byte in bytes {
|
||||
// SAFE: table's size is always u8::MAX
|
||||
result.push(unsafe { *table.get_unchecked(*byte as usize) });
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,8 @@ struct Utf7DecoderState {
|
||||
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 {
|
||||
// SAFE: union access of `n_bytes`, which is always lower than size_of::<u32>
|
||||
for byte in state.b64_bytes.bytes.get_unchecked(0..n_bytes) {
|
||||
if let Some(pending_byte) = state.pending_byte {
|
||||
state
|
||||
@@ -53,7 +53,7 @@ pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
|
||||
|
||||
for byte in bytes {
|
||||
if in_b64 {
|
||||
// Safe because BASEMAP size is [4][u8::MAX]
|
||||
// SAFE: BASEMAP's size is [4][u8::MAX]
|
||||
let val = unsafe {
|
||||
BASE64_MAP
|
||||
.get_unchecked(byte_count as usize)
|
||||
@@ -66,7 +66,7 @@ pub fn decoder_utf7(bytes: &[u8]) -> Cow<str> {
|
||||
if byte_count == 1 {
|
||||
state.b64_bytes.val = *val;
|
||||
} else {
|
||||
// Safe union read/write
|
||||
// SAFE: union read/write
|
||||
unsafe {
|
||||
state.b64_bytes.val |= *val;
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ pub fn parse_encoded_word<'x>(stream: &MessageStream<'x>) -> Option<Cow<'x, str>
|
||||
{
|
||||
decoder(bytes?).into()
|
||||
} else if is_utf8_safe {
|
||||
// SAFE: slice checked previously
|
||||
unsafe { Cow::from(std::str::from_utf8_unchecked(bytes?)).into() }
|
||||
} else {
|
||||
decoder_default(bytes?).into()
|
||||
|
||||
@@ -39,6 +39,7 @@ pub fn decode_hex(src: &[u8]) -> (bool, Vec<u8>) {
|
||||
result.push(*ch);
|
||||
}
|
||||
HexState::Percent => {
|
||||
// SAFE: HEX_MAP's size is u8::MAX
|
||||
hex1 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
if hex1 != -1 {
|
||||
state = HexState::Hex1;
|
||||
@@ -48,6 +49,7 @@ pub fn decode_hex(src: &[u8]) -> (bool, Vec<u8>) {
|
||||
}
|
||||
}
|
||||
HexState::Hex1 => {
|
||||
// SAFE: HEX_MAP's size is u8::MAX
|
||||
let hex2 = unsafe { *HEX_MAP.get_unchecked(*ch as usize) };
|
||||
|
||||
state = HexState::None;
|
||||
|
||||
@@ -30,11 +30,11 @@ 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);
|
||||
|
||||
/* SAFE: ENTITY_HASH's size is 260 (u8::MAX + 5)
|
||||
and ENTITY_MAP's size is 18016 (18079 - 64 + 1) */
|
||||
unsafe {
|
||||
for (pos, ch) in entity.iter().enumerate() {
|
||||
match pos {
|
||||
@@ -69,7 +69,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
|
||||
// SAFE: 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) });
|
||||
}
|
||||
@@ -237,6 +237,7 @@ pub fn text_to_html(input: &str) -> String {
|
||||
}
|
||||
result.extend_from_slice(b"</body></html>");
|
||||
|
||||
// SAFE: `result` contains a sequence of a valid `input` string tokens and UTF-8 safe slices
|
||||
unsafe { String::from_utf8_unchecked(result) }
|
||||
}
|
||||
|
||||
|
||||
@@ -44,9 +44,11 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
let mut success = boundary.is_empty();
|
||||
let mut is_utf8_safe = true;
|
||||
|
||||
// SAFE: exclusive access to `self.data`
|
||||
let mut data = &mut *self.data.get();
|
||||
let data_len = (*data).len();
|
||||
|
||||
// SAFE: exclusive access to `self.pos`
|
||||
let stream_pos = &mut *self.pos.get();
|
||||
let start_pos = *stream_pos;
|
||||
let mut read_pos = *stream_pos;
|
||||
@@ -56,15 +58,29 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
let mut match_count = 0;
|
||||
let mut hex1 = 0;
|
||||
|
||||
debug_assert!(boundary.is_empty() || boundary.len() >= 2);
|
||||
|
||||
while read_pos < data_len {
|
||||
// SAFE: slice bounds checked in while loop
|
||||
let ch = *(*data).get_unchecked(read_pos);
|
||||
read_pos += 1;
|
||||
|
||||
// if success is false, a boundary was provided
|
||||
if !success {
|
||||
let mut is_boundary_end = true;
|
||||
|
||||
// SAFE: bounds are checked after the first match occurs
|
||||
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);
|
||||
let done = if is_word {
|
||||
true
|
||||
} else {
|
||||
// SAFE: exclusive access to `self.data` is re-obtained after
|
||||
// is_boundary_end finishes.
|
||||
is_boundary_end = self.is_boundary_end(read_pos);
|
||||
is_boundary_end
|
||||
};
|
||||
data = &mut *self.data.get(); // Avoid violating the Stacked Borrows rules
|
||||
|
||||
if done {
|
||||
@@ -85,6 +101,8 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
#[cfg(not(miri))]
|
||||
{
|
||||
// SAFE: `write_pos` increments in parallel to `read_pos`
|
||||
// which is bound checked in the while loop
|
||||
*((*data).get_unchecked_mut(write_pos)) = *ch;
|
||||
}
|
||||
write_pos += 1;
|
||||
@@ -95,11 +113,24 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
state = QuotedPrintableState::None;
|
||||
|
||||
if ch == *boundary.get_unchecked(0) {
|
||||
match_count = 1;
|
||||
continue;
|
||||
// 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 {
|
||||
|
||||
// SAFE: `boundary` is never empty at this point
|
||||
if ch == *boundary.get_unchecked(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,6 +157,8 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
#[cfg(not(miri))]
|
||||
{
|
||||
// SAFE: `write_pos` increments in parallel to `read_pos`
|
||||
// which is bound checked in the while loop
|
||||
*((*data).get_unchecked_mut(write_pos)) = b'\n';
|
||||
}
|
||||
|
||||
@@ -139,6 +172,8 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
#[cfg(not(miri))]
|
||||
{
|
||||
// SAFE: `write_pos` increments in parallel to `read_pos`
|
||||
// which is bound checked in the while loop
|
||||
*((*data).get_unchecked_mut(write_pos)) = b' ';
|
||||
}
|
||||
write_pos += 1;
|
||||
@@ -152,6 +187,8 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
#[cfg(not(miri))]
|
||||
{
|
||||
// SAFE: `write_pos` increments in parallel to `read_pos`
|
||||
// which is bound checked in the while loop
|
||||
*((*data).get_unchecked_mut(write_pos)) = ch;
|
||||
}
|
||||
write_pos += 1;
|
||||
@@ -160,6 +197,7 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
}
|
||||
QuotedPrintableState::Eq => {
|
||||
// SAFE: HEX_MAP's size is u8::MAX
|
||||
hex1 = *HEX_MAP.get_unchecked(ch as usize);
|
||||
if hex1 != -1 {
|
||||
state = QuotedPrintableState::Hex1;
|
||||
@@ -169,6 +207,7 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
}
|
||||
QuotedPrintableState::Hex1 => {
|
||||
// SAFE: HEX_MAP's size is u8::MAX
|
||||
let hex2 = *HEX_MAP.get_unchecked(ch as usize);
|
||||
|
||||
state = QuotedPrintableState::None;
|
||||
@@ -181,6 +220,8 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
}
|
||||
#[cfg(not(miri))]
|
||||
{
|
||||
// SAFE: `write_pos` increments in parallel to `read_pos`
|
||||
// which is bound checked in the while loop
|
||||
*((*data).get_unchecked_mut(write_pos)) = ch;
|
||||
}
|
||||
|
||||
@@ -203,6 +244,7 @@ impl<'x> QuotedPrintableDecoder<'x> for MessageStream<'x> {
|
||||
success,
|
||||
is_utf8_safe,
|
||||
if write_pos > start_pos {
|
||||
// SAFE: bounds are checked
|
||||
Some((*data).get_unchecked(start_pos..write_pos))
|
||||
} else {
|
||||
None
|
||||
@@ -314,6 +356,18 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// MIRI overflow tests
|
||||
for mut input in [b"\x0a\x0a\x00\x0b".to_vec(), b":B\x0a%".to_vec()] {
|
||||
let stream = MessageStream::new(&mut input[..]);
|
||||
stream.decode_quoted_printable(b"\n\n", true);
|
||||
let stream = MessageStream::new(&mut input[..]);
|
||||
stream.decode_quoted_printable(b"\n\n", false);
|
||||
let stream = MessageStream::new(&mut input[..]);
|
||||
stream.decode_quoted_printable(&[], true);
|
||||
let stream = MessageStream::new(&mut input[..]);
|
||||
stream.decode_quoted_printable(&[], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+262
-105
@@ -10,37 +10,39 @@
|
||||
*/
|
||||
|
||||
//! # 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).
|
||||
//!
|
||||
//! - **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
|
||||
//! - 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.
|
||||
//! - Although some `unsafe` code was used to obtain performance gains of about 10%, every function in the library has been
|
||||
//! [fuzzed](#testing-fuzzing--benchmarking) and also heavily [tested with MIRI](#testing-fuzzing--benchmarking).
|
||||
//! - Fully 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,59 +57,59 @@
|
||||
//! - [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!(
|
||||
//! "From: Art Vandelay <art@vandelay.com> (Vandelay Industries)\n",
|
||||
//! "To: \"Colleagues\": \"James Smythe\" <james@vandelay.com>; Friends:\n",
|
||||
@@ -193,7 +195,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 +259,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 +273,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 +297,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 +310,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 +331,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 +359,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 +582,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 +619,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 +640,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 +684,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>>>,
|
||||
}
|
||||
|
||||
@@ -115,6 +115,7 @@ 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) {
|
||||
// SAFE: MONTH_HASH's size is u8::MAX
|
||||
month_hash += unsafe {
|
||||
*MONTH_HASH
|
||||
.get_unchecked((if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize)
|
||||
@@ -157,6 +158,7 @@ pub fn parse_date(stream: &MessageStream, abort_on_invalid: bool) -> Option<Date
|
||||
parts[2]
|
||||
},
|
||||
month: if month_pos == 3 && month_hash <= 30 {
|
||||
// SAFE: MONTH_MAP's size is 31
|
||||
(unsafe { *MONTH_MAP.get_unchecked(month_hash) }) as u32
|
||||
} else {
|
||||
parts[1]
|
||||
@@ -188,7 +190,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,
|
||||
];
|
||||
|
||||
|
||||
@@ -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,6 +77,7 @@ 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) {
|
||||
// SAFE: HDR_HASH's size is u8::MAX
|
||||
token_hash += token_len
|
||||
+ unsafe {
|
||||
*HDR_HASH.get_unchecked(last_ch.to_ascii_lowercase() as usize)
|
||||
@@ -85,9 +86,11 @@ fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'x> {
|
||||
if (4..=61).contains(&token_hash) {
|
||||
let token_hash = token_hash - 4;
|
||||
|
||||
if field.eq_ignore_ascii_case(unsafe {
|
||||
// SAFE: HDR_NAME's size is 58
|
||||
if field.eq_ignore_ascii_case(unsafe {
|
||||
HDR_NAMES.get_unchecked(token_hash)
|
||||
}) {
|
||||
// SAFE: HDR_FNCS's size is 58
|
||||
return HeaderParserResult::Supported(unsafe {
|
||||
*HDR_FNCS.get_unchecked(token_hash)
|
||||
});
|
||||
@@ -112,6 +115,7 @@ fn parse_header_name<'x>(stream: &MessageStream<'x>) -> HeaderParserResult<'x> {
|
||||
}
|
||||
|
||||
if let 0 | 9 = token_len {
|
||||
// SAFE: HDR_HASH's size is u8::MAX
|
||||
token_hash +=
|
||||
unsafe { *HDR_HASH.get_unchecked((*ch).to_ascii_lowercase() as usize) }
|
||||
as usize;
|
||||
@@ -196,7 +200,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 +261,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",
|
||||
|
||||
+9
-13
@@ -18,8 +18,7 @@ use crate::{
|
||||
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};
|
||||
@@ -55,6 +54,7 @@ fn bytes_to_string<'x>(
|
||||
if !is_utf8_safe {
|
||||
decoder_default(bytes)
|
||||
} else {
|
||||
// SAFE: `bytes` slice is ASCII and UTF-8 safe
|
||||
(unsafe { std::str::from_utf8_unchecked(bytes) }).into()
|
||||
}
|
||||
}
|
||||
@@ -130,15 +130,15 @@ impl<'x> Message<'x> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a byte slice containing the RFC5322 raw message and returns a
|
||||
/// 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
|
||||
///
|
||||
/// 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> {
|
||||
let stream = MessageStream::new(bytes);
|
||||
|
||||
@@ -388,9 +388,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 +464,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
use std::{borrow::Cow, cell::UnsafeCell};
|
||||
|
||||
pub struct MessageStream<'x> {
|
||||
// SAFE: MessageStream is always executed on a single thread and this struct
|
||||
// is never shared outside the library.
|
||||
pub data: UnsafeCell<&'x mut [u8]>,
|
||||
pub pos: UnsafeCell<usize>,
|
||||
}
|
||||
@@ -26,12 +28,15 @@ impl<'x> MessageStream<'x> {
|
||||
|
||||
#[inline(always)]
|
||||
pub fn get_bytes(&self, from: usize, to: usize) -> Option<&'x [u8]> {
|
||||
// SAFE: exclusive access to `data`
|
||||
unsafe { (*self.data.get()).get(from..to) }
|
||||
}
|
||||
|
||||
pub fn get_string(&self, from: usize, to: usize, utf8_valid: bool) -> Option<Cow<'x, str>> {
|
||||
// SAFE: exclusive access to `data`
|
||||
unsafe {
|
||||
if utf8_valid {
|
||||
// SAFE: slice region is US-ASCII and UTF-8 safe
|
||||
Cow::from(std::str::from_utf8_unchecked(
|
||||
(*self.data.get()).get(from..to)?,
|
||||
))
|
||||
@@ -44,11 +49,13 @@ impl<'x> MessageStream<'x> {
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_eof(&self) -> bool {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
unsafe { *self.pos.get() >= (*self.data.get()).len() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn set_pos(&self, pos: usize) {
|
||||
// SAFE: exclusive access to `pos`
|
||||
unsafe {
|
||||
*self.pos.get() = pos;
|
||||
}
|
||||
@@ -56,16 +63,19 @@ impl<'x> MessageStream<'x> {
|
||||
|
||||
#[inline(always)]
|
||||
pub fn get_pos(&self) -> usize {
|
||||
// SAFE: exclusive access to `pos`
|
||||
unsafe { *self.pos.get() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn next(&self) -> Option<&'x u8> {
|
||||
unsafe {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
let pos = &mut *self.pos.get();
|
||||
let data = &mut *self.data.get();
|
||||
|
||||
if *pos < data.len() {
|
||||
// SAFE: bounds are checked
|
||||
let result = data.get_unchecked(*pos);
|
||||
*pos += 1;
|
||||
Some(result)
|
||||
@@ -77,11 +87,13 @@ impl<'x> MessageStream<'x> {
|
||||
|
||||
#[inline(always)]
|
||||
pub fn peek(&self) -> Option<&'x u8> {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
unsafe { (*self.data.get()).get(*self.pos.get()) }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn advance(&self, pos: usize) {
|
||||
// SAFE: exclusive access to `pos`
|
||||
unsafe {
|
||||
*self.pos.get() += pos;
|
||||
}
|
||||
@@ -90,14 +102,17 @@ impl<'x> MessageStream<'x> {
|
||||
pub fn seek_next_part(&self, boundary: &[u8]) -> bool {
|
||||
if !boundary.is_empty() {
|
||||
unsafe {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
let cur_pos = &mut *self.pos.get();
|
||||
let data = &mut *self.data.get();
|
||||
|
||||
let mut pos = *cur_pos;
|
||||
let mut match_count = 0;
|
||||
|
||||
for ch in (*data)[*cur_pos..].iter() {
|
||||
pos += 1;
|
||||
|
||||
// SAFE: bounds are checked after the first match occurs
|
||||
if ch == boundary.get_unchecked(match_count) {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
@@ -107,6 +122,7 @@ impl<'x> MessageStream<'x> {
|
||||
continue;
|
||||
}
|
||||
} else if match_count > 0 {
|
||||
// SAFE: `boundary` can't be empty
|
||||
if ch == boundary.get_unchecked(0) {
|
||||
match_count = 1;
|
||||
continue;
|
||||
@@ -123,9 +139,10 @@ impl<'x> MessageStream<'x> {
|
||||
|
||||
pub fn get_bytes_to_boundary(&self, boundary: &[u8]) -> (bool, bool, Option<&'x [u8]>) {
|
||||
unsafe {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
let mut data = &mut *self.data.get();
|
||||
|
||||
let stream_pos = &mut *self.pos.get();
|
||||
|
||||
let start_pos = *stream_pos;
|
||||
|
||||
return if !boundary.is_empty() {
|
||||
@@ -140,9 +157,12 @@ impl<'x> MessageStream<'x> {
|
||||
is_utf8_safe = false;
|
||||
}
|
||||
|
||||
// SAFE: bounds are checked after the first match occurs
|
||||
if ch == boundary.get_unchecked(match_count) {
|
||||
match_count += 1;
|
||||
if match_count == boundary.len() {
|
||||
// SAFE: exclusive access to `self.data` is re-obtained after
|
||||
// is_boundary_end finishes.
|
||||
let is_boundary_end = self.is_boundary_end(pos);
|
||||
data = &mut *self.data.get(); // Avoid violating the Stacked Borrows rules
|
||||
|
||||
@@ -165,6 +185,7 @@ impl<'x> MessageStream<'x> {
|
||||
}
|
||||
continue;
|
||||
} else if match_count > 0 {
|
||||
// SAFE: `boundary` is never empty
|
||||
if ch == boundary.get_unchecked(0) {
|
||||
match_count = 1;
|
||||
continue;
|
||||
@@ -187,8 +208,10 @@ impl<'x> MessageStream<'x> {
|
||||
#[inline(always)]
|
||||
pub fn skip_crlf(&self) {
|
||||
unsafe {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
let cur_pos = &mut *self.pos.get();
|
||||
let data = &mut *self.data.get();
|
||||
|
||||
let mut pos = *cur_pos;
|
||||
|
||||
for ch in (*data)[*cur_pos..].iter() {
|
||||
@@ -207,6 +230,7 @@ impl<'x> MessageStream<'x> {
|
||||
#[inline(always)]
|
||||
pub fn skip_byte(&self, ch: &u8) -> bool {
|
||||
unsafe {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
let pos = &mut *self.pos.get();
|
||||
let data = &mut *self.data.get();
|
||||
|
||||
@@ -221,6 +245,7 @@ impl<'x> MessageStream<'x> {
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_boundary_end(&self, pos: usize) -> bool {
|
||||
// SAFE: exclusive access to `data` and `pos`
|
||||
matches!(
|
||||
unsafe { (*self.data.get()).get(pos..) },
|
||||
Some([b'\n' | b'\r' | b' ' | b'\t', ..]) | Some([b'-', b'-', ..]) | Some([]) | None
|
||||
@@ -229,6 +254,7 @@ impl<'x> MessageStream<'x> {
|
||||
|
||||
pub fn skip_multipart_end(&self) -> bool {
|
||||
unsafe {
|
||||
// SAFE: exclusive access to `pos`
|
||||
let pos = &mut *self.pos.get();
|
||||
|
||||
match (*self.data.get()).get(*pos..*pos + 2) {
|
||||
@@ -247,6 +273,7 @@ impl<'x> MessageStream<'x> {
|
||||
}
|
||||
|
||||
pub fn rewind(&self, r: usize) {
|
||||
// SAFE: exclusive access to `pos`
|
||||
unsafe {
|
||||
*self.pos.get() -= r;
|
||||
}
|
||||
|
||||
@@ -143,5 +143,4 @@ fn test_api() {
|
||||
|
||||
//println!("{}", serde_json::to_string_pretty(&message).unwrap());
|
||||
//println!("{}", serde_yaml::to_string(&message).unwrap());
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user