Compare commits

..
109 Commits
Author SHA1 Message Date
Stalwart Git Sync edb426b1a3 html_to_text: line breaks for block elements, spaces between table cells (fixes #172) 2026-11-28 09:42:43 +01:00
Stalwart Git Sync 267239755e v1.0.2 2026-11-23 10:36:24 +01:00
Maurus Decimus 1d449bb5ef html_to_text: keep the space after a leading element, skip quoted attribute values (fixes #168, fixes #169) 2026-11-19 11:18:47 +01:00
Luca Cappelletti 8e149db324 Keep quoted-pairs in a quoted local part inside angle brackets (#167) 2026-11-15 15:53:49 +01:00
Luca Cappelletti 70bba6b551 Keep a quoted local part in an address without angle brackets (#166) 2026-11-15 15:52:32 +01:00
Maurus Decimus a56d5f1dc0 v1.0.1 2026-11-02 09:20:26 +01:00
Maurus Decimus 82a87a063d Keep parameter values after a fold following = (fixes #165) 2026-10-29 12:05:17 +01:00
Maurus Decimus 81ceb39699 v1.0.0 2026-10-24 09:44:11 +02:00
Maurus Decimus acba893086 Updated header_name 2026-10-19 15:09:25 +02:00
Maurus Decimus 14e535a627 Added all_from method 2026-10-10 12:29:22 +02:00
Maurus Decimus c6d9951ad6 Added MessagePart::text_prefix_bytes 2026-10-08 11:33:48 +02:00
sftse 17927ce5f6 add rfc6854 to conformed rfcs, allows groups as senders (#163) 2026-10-06 16:42:26 +02:00
Maurus Decimus f39064dc3c Fix HTML text parsing issues 2026-10-06 15:45:20 +02:00
Maurus Decimus 79b2f3fd5e Non-conforming RFC5322 address oddly mangled (fixes #162) 2026-10-06 15:32:24 +02:00
Maurus Decimus 52cb6bd6c7 SSSE3 tier vectorises 2026-10-02 17:36:31 +02:00
Maurus Decimus 4a6bacfbd8 Updated decoders 2026-10-02 16:41:05 +02:00
Maurus Decimus bf226297ac Added header_count function 2026-10-01 21:48:59 +02:00
Maurus Decimus c22d5fe970 Updated Miri details 2026-09-29 10:58:56 +02:00
Maurus Decimus 096b8b01e2 Updated benchmarks 2026-09-28 19:26:54 +02:00
Maurus Decimus a5a5d74ba0 Merge v1.0.0 branch into main (fixes #156 closes #127 fixes #109 closes #107 closes #98 closes #82 closes #73 fixes #119 fixes #70 fixes #67) 2026-09-28 14:00:35 +02:00
Maurus Decimus 4eba485d94 Bump to hashify 0.3 2026-09-23 11:35:41 +02:00
Maurus Decimus cac12a5c2b Updated threading algorithm 2026-09-18 14:05:03 +02:00
Maurus Decimus 918cc0c891 v0.11.9 2026-09-09 19:13:19 +01:00
Maurus Decimus d26ec82e6a Added base64_decode_slice behind the new base64_slice feature, which adds a memchr dependency 2026-09-09 19:12:46 +01:00
Maurus Decimus 499ae0f2ff Fix: HeaderName breaks rkyv serialization from <= 0.11.6 2026-08-22 10:39:04 +02:00
Maurus Decimus 350034b33c clippy fixes 2026-08-21 17:24:58 +02:00
Maurus Decimus 1883c39102 v0.11.7 2026-08-20 16:14:00 +02:00
Maurus Decimus 5528d5b49f Fix: DateTime::to_timezone corrupting non-whole-hour offsets by storing leftover seconds in tz_minute (closes #158) 2026-08-20 15:10:50 +02:00
Maurus Decimus b4366b7537 v0.11.6 2026-08-10 19:32:04 +02:00
Maurus Decimus 3574f17a22 Fix: Multi-word display names followed by a comment no longer produce a fabricated address (closes #153) 2026-08-10 19:28:16 +02:00
Maurus Decimus f9a580c551 Fix: panic when a Received header ends with a folded line (closes #155) 2026-08-10 19:22:45 +02:00
sftse 339a4306d3 fix: return all To, Cc, Bcc headers (#152) 2026-07-20 11:54:36 +02:00
Maurus Decimus e2bcdf1e03 Fix: Missing whitespace between a quoted name and a following encoded word (closes #150) 2026-07-20 11:42:07 +02:00
Maurus Decimus 67a53e3ded Fix: panic with messages containing corrupted eml attachments (closes #120). 2026-07-08 17:59:12 +02:00
Maurus Decimus b47ebe0d8f Recognize additional charset labels supported by encoding_rs (closes #123) 2026-07-08 17:07:13 +02:00
Maurus Decimus 67055bdc30 Fix: Decode the iso-8859-1 label as windows-1252 per the WHATWG Encoding Standard (closes #131) 2026-07-08 16:38:27 +02:00
Maurus Decimus 7da1ecc33c Added Dkim2Signature and MessageInstance to support DKIM2 headers 2026-07-08 16:32:47 +02:00
Maurus Decimus a6d6e10a82 Fix: Address names containing LF are not parsed correctly (closes #149) 2026-07-08 16:17:52 +02:00
Maurus Decimus 250f3a1cf4 v0.11.4 2026-06-21 10:10:49 +02:00
Maurus Decimus 6da7920ab6 Leniently decode quoted-printable bodies with invalid = escapes (closes #144) 2026-06-21 09:07:56 +02:00
Maurus Decimus 0128bc1da0 Add Message::received_all() to iterate over all Received header fields (closes #146) 2026-06-21 08:12:03 +02:00
Maurus Decimus a13fe5c32d Bump edition to 2024 (closes #147) 2026-06-21 08:05:08 +02:00
Maurus Decimus 8d571e4c7e Fix: parse_date() does not handle UTC+12 and greater (fixes #148) 2026-06-21 08:02:57 +02:00
Maurus Decimus b905fda07d Reject dates with invalid month names 2026-05-10 11:15:48 +02:00
Maurus Decimus 2bff6e8d9d Fix panic with messages containing corrupted attachments (closes #145) 2026-05-02 09:15:12 +02:00
Teal Bauer ebd2b179df fix(html): skip style/script/template blocks in html_to_text (#134) 2026-02-24 19:45:37 +01:00
mdecimus af44d480ad v0.11.2 2026-02-14 18:43:43 +00:00
mdecimus 9122a32e08 Fix CRLF tests (closes #132) 2026-02-04 20:48:44 +01:00
mdecimus 7fada6e911 Clippy fixes 2026-01-29 11:04:22 +01:00
Cameron Little df057edf09 Fix broken receive header date parsing when tab is used in long header syntax (#130)
* Add example tests for broken received parsing in shapelib email

This comes from http://lists.maptools.org/pipermail/shapelib.mbox/shapelib.mbox, where several of the emails received headers are incorrectly parsed.

The bad parsing looks like this:

Original header value:

```
from [217.146.183.184] by nm2.bullet.mail.ukl.yahoo.com with NNFMP; 09 Mar 2011 11:19:46 -0000
```

```json
"date": {
  "year": 1911,
  "month": 219,
  "day": 3,
  "hour": 19,
  "minute": 46,
  "second": 0,
  "tz_before_gmt": true,
  "tz_hour": 0,
  "tz_minute": 0
}
```

Where the year should be 2011 and the month 3.

Weirdly, this reproduces in full message parsing, but not in the individual `received.json` tests.

This looks like it's similar to https://learn.microsoft.com/en-us/answers/questions/2737324/windows-live-mail-has-received-date-set-well-into

* Fix

* Add test case from https://github.com/stalwartlabs/mail-parser/issues/81
2026-01-15 00:18:34 +01:00
mdecimus 6c5d330285 Updated roundtip date conversion tests 2025-08-18 12:03:32 +01:00
mdecimus 957185aed4 v0.11.1 2025-08-18 11:56:55 +01:00
mdecimus c5d47b5b8e v0.11.0 2025-05-11 16:29:41 +02:00
andreadev-it 0a07a6f3d4 Fixed typo in header.rs (#105) 2025-03-24 10:10:09 +01:00
Stephen Becker IV b29325709a fix-no-newline-parse (#102)
* fix-no-newline-parse

Dearest Reviewer,

Issue #90 brought up the issue that if there was no newline. the user
provided an easy reproduction case. I was able to track it down to the
parse raw function.

The issue is that the loop hits the end of the string and returns Empty.
However, if there is a start offset then some characters were found. This
code just checks the offset after the loop.

If this is not the correct behavior please close.

Thanks for your time
Becker

* pr feedback

Add break instead of duplicating code.
2025-03-09 18:25:07 +01:00
Stephen Becker IV 41a96cd647 fix-fuzz-targets (#103)
* fix-fuzz-targets

Dearest Reviewer,

While creating PR #102 I tried running the fuzz command and found it
failing. It looks like the functions were made private and parse headers
arguments were updated.

I dont know if this is a complete update or what is covered but it does
get `cargo +nightly fuzz run mail_parser` working again.

Thanks for your time.
Becker

* readd space
2025-03-02 18:37:17 +01:00
mdecimus b0ba8dba3b Clippy fix 2025-02-27 17:24:43 +01:00
sftse 60fe70d2c5 fix: express custom trait with stdlib traits (#101) 2025-02-09 15:53:53 +01:00
sftse 209778f080 Informing callers of buffering requirements prevents accidental double buffering (#100) 2025-02-09 15:52:22 +01:00
mdecimus 0bcf5f513c v0.10.2 2025-01-28 18:26:37 +01:00
mdecimus 3e300dd2c2 Fixed Headername::parse 2025-01-26 16:07:18 +01:00
mdecimus c177ffaca3 v0.10.0 2025-01-26 15:31:53 +01:00
mdecimus fa34e10927 Moved HTML entity mappings to hashify large map 2025-01-26 10:18:46 +01:00
mdecimus 2b37017cf8 Fixed OOB 2025-01-25 18:15:29 +01:00
mdecimus 5f25e1291f REUSE licensing 2025-01-25 17:47:39 +01:00
mdecimus 8b2ad20bf3 Hashing with hashify + cosmetic fixes 2025-01-25 17:45:23 +01:00
sftse bc6a5b1e94 Retain mbox IO errors (#91)
* Simplify

* Clear line buffer explicitly

* Move line clearing outside logic branching

* Switch if-else branch order

* Delete needless branching, other branch early-returns, so this is equivalent

* fmt

* Inline return statement

* Equivalence transform of logic branches

* Equivalence transform of logic branches

* Hoist if across if let

* Delete else block

* Make explicit that !is_from holds implicitly for these branches

* Switch if let {...}; if {...} into if {...}; if let {...}

* Pull out common if check

* Merge common if clauses

* Introduce early continue

* Fixed clippy warnings

* Remove collecting into Vec

* Dont throw away IO error
2025-01-25 15:17:32 +01:00
sftse 20fa3dbd46 Fix deserialize (#93)
* Expand test to cover deserialization

* Fix deserialization
2025-01-25 15:15:10 +01:00
sftse e97d14ad89 Add .eml example with odd behavior (#88)
* Add .eml example with odd behavior

* Parse malformed, non-multipart, single text/plain messages best-effort as if text is not malformed
2025-01-25 15:14:19 +01:00
sftse ed16429bcc Hide concrete type behind impl type (#94)
Without this, the doc(hidden) interacts poorly with the fact that both
BodyPartIterator and AttachmentIterator can be seen in the public api of
other functions. The types still show up, but there's no simple way to know
they implement Iterator or what the Item they return is.
2025-01-25 15:12:27 +01:00
sftse c733600b75 Obsolete timezones (#95)
* Expand date time tests by section 4.3 Obsolete Date and Time from RFC5322

* Needless branching

* fmt

* Implement obsolete time zones RFC5322 section 4.3

* Sanity check: constrain hours below 12 and minutes below 60
2025-01-25 15:11:41 +01:00
sftse 76669a32c6 Folding ws between "Content-Type:" and "plain/text" leads to empty header (#96)
* Add testcase with folding whitespace between "Content-Type:" and "text/plain"

* Fix handling of newlines between Content-Type and the type itself
2025-01-25 15:10:27 +01:00
mdecimus c8bf355494 Multiline quoted continuations (closes #92) 2024-12-01 20:54:09 +13:00
mdecimus 9bf766dcf1 Clippy fixes 2024-12-01 20:18:17 +13:00
George 0eba00b4e9 Update lib.rs (#75)
For ergonomic reasons a default implementation for `DateTime` is useful and all zero's and false is fine, though some specific other value may be more suitable
2024-10-21 17:22:28 +02:00
sftse 0baffddb28 Minor fixes (#87)
* Move multipart classification into own closure

* Add classification enum

* Express classification indirectly with an enum

* Express logic clause in equivalent way, add assert inline test to make sure of it

* Remove old classifier

* Remove enum indirection

* Remove closure

* Hoist common if condition into outer scope

* Simplify expression

* Simplify lifetime bounds

A missing lifetime in the GetHeader trait was inferred by lifetime elision rules
to be shorter than necessary, leading to awkward lifetime constraints being
propagated throughout many functions that didnt need them.

* Prohibit Rust 2018 idioms, return longest feasible lifetimes

* Dont duplicate crlf in extension when saving failing results
2024-10-21 17:21:56 +02:00
董彬 54ca7df6eb Update multi_byte.rs (#86)
Under some extreme circumstances, the pre-allocated length might not be sufficient.
2024-09-08 18:18:48 +02:00
mdecimus c3f28cb4d1 v0.9.4 2024-09-04 09:10:33 +02:00
mdecimus e512a66bb0 More flexible charset name parsing (closes #85) 2024-08-30 17:04:00 +02:00
mdecimus 6a48ed69b6 Removed FUNDING 2024-08-09 18:28:23 +02:00
mdecimus dfda00c939 Fix nestead attachment contents and len functions (fixes #84) 2024-08-09 18:27:09 +02:00
mdecimus a96497d7a3 v0.9.3 2024-03-28 15:46:25 +01:00
Clément DOUIN ad4dff69c3 fix address name containing @ (#80) 2024-03-14 13:29:37 +01:00
Arif Driessen cf87d3556c initial commit (#77) 2024-02-07 13:48:28 +01:00
Mauro D 4ff4c57e2c Clippy fixes 2024-01-08 19:31:34 +01:00
Mauro D 598cba3b87 Added liberapay 2024-01-08 19:23:59 +01:00
sftse 716c0d747e correctly parse obsolete years as in RFC5322 section 4.3 (#72) 2024-01-05 18:28:36 +01:00
mdecimus 65533d3faf v0.9.2 2023-11-27 09:34:59 +01:00
mdecimus 28a9b67b9a Fix Received struct serialization for bincode compatibility 2023-11-09 17:40:47 +01:00
mdecimus b6c080ff45 Updaded keywords 2023-09-22 13:39:53 +02:00
mdecimus 56d2c3b8b0 v0.9.1 2023-09-22 13:38:55 +02:00
mdecimus 816d944f2e Updated Rust version 2023-09-16 17:28:58 +02:00
mdecimus e5a4e65112 v0.9.0 2023-09-05 18:11:49 +02:00
mdecimus b0a5925eac v0.9.0 2023-09-05 11:07:39 +02:00
mdecimus 4b5455c196 MessageParser builder 2023-09-05 10:54:39 +02:00
mdecimus ec04c1412d Merged RfcHeader into HeaderName 2023-09-04 19:48:47 +02:00
mdecimus e230000856 Moved address related object to Address enum 2023-09-04 18:27:15 +02:00
mdecimus 8e5381f60b Project reorganization 2023-09-04 15:23:45 +02:00
mdecimus 5a7b50059f Received header parser 2023-09-03 20:49:20 +02:00
mdecimus 7c08078617 Into_owned returns static lifetime 2023-09-01 09:01:29 +02:00
mdecimus da62659eb6 Support for trailing whitespaces in quoted printable MIME encoded parts. 2023-07-03 11:05:03 +02:00
mdecimus 405b742be2 Support for trailing whitespaces in quoted printable MIME encoded parts. 2023-07-03 10:42:33 +02:00
mdecimus 743aacafad Support for trailing whitespaces in quoted printable MIME encoded parts. 2023-07-03 10:17:26 +02:00
mdecimus ffb5a7fd61 Added header_as function 2023-07-03 09:14:24 +02:00
Geert Stappers 154591697f cargo fmt (#48) 2023-05-14 11:01:14 +02:00
Mauro D c7790a8925 Clippy fixes. 2023-04-12 09:13:48 +00:00
Mauro D 77fe8cd0d1 v0.8.2 2023-02-22 13:18:24 +00:00
Mauro D b4478f74e2 Fix: Missing space when folded header begins with RFC2047 word (#43) 2023-02-21 18:39:25 +00:00
Dany Laporte da1e6180db Fix parsing name from address (#41) 2023-02-19 20:25:42 +01:00
952 changed files with 132309 additions and 234861 deletions
-13
View File
@@ -1,13 +0,0 @@
# These are supported funding model platforms
github: stalwartlabs
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+2
View File
@@ -20,3 +20,5 @@ jobs:
run: cargo build --verbose run: cargo build --verbose
- name: Run tests - name: Run tests
run: cargo test --verbose run: cargo test --verbose
- name: Run tests with all features
run: cargo test --all-features --verbose
+2
View File
@@ -3,3 +3,5 @@
perf.* perf.*
*.svg *.svg
Cargo.lock Cargo.lock
.ignore
*.failed
+434 -58
View File
@@ -1,127 +1,503 @@
mail-parser 0.8.1 # Change Log
================================
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/).
## [1.0.3] - Unreleased
### Fixed
- `html_to_text` and HTML previews ran words together across block elements, so `<div>One</div><div>Two</div>` gave `OneTwo`. Block elements such as `<div>`, `<li>`, `<tr>` and `<h1>` now end the line and table cells are separated by a space, while a `<br>` or `<p>` inside `<template>`, `<style>` or `<script>` no longer adds a line break (#172).
## [1.0.2] - 2026-11-23
### Fixed
- An address without angle brackets whose local part is a quoted string, such as `"john smith"@example.com`, was read as the display name `john smith` and the address `@example.com` (#166).
- A quoted local part inside angle brackets lost its backslashes, so `<"a\"b"@example.com>` gave the address `"a"b"@example.com`. A quoted-pair now stays in the address as written (#167).
- `html_to_text` dropped the space after an element that started a line, so `<b>Hello</b> world` gave `Helloworld`, and put a stray space at the start of the next paragraph (#168).
- A `>` or `<` inside a quoted attribute value ended the tag, so `<img alt="a > b">` leaked `b">` into the text (#169).
## [1.0.1] - 2026-11-02
### Fixed
- A parameter value on a folded line after `=` was read as a new parameter name, losing `name`, `filename` and `boundary` (#165).
## [1.0.0] - 2026-10-24
A rewrite of the parser for performance, with a new read-only API. Breaking changes are listed under Changed and Removed; the table at the end of this entry maps the 0.11 API to 1.0.
### Added
- Bodies are decoded on access: `MessagePart::decoded()`, `decode_into()`, `decoded_len()` (measures base64 and quoted-printable without decoding), `text()`, `text_into()` and `text_prefix()` (decodes only what the first characters need).
- `MessagePart::decoded_checked()` and `text_checked()` also return the `DecodeProblems` found while decoding (malformed base64 or quoted-printable, unknown transfer encoding, unknown charset, sequences not valid in the charset), which is the RFC 8621 `isEncodingProblem` flag.
- `MessageRef`, a view of the root message or of a nested message, with `id()`, `root_part()`, `container()`, `source()`, `source_bytes()`, `raw()`, `parts()`, the body lists and the header getters; `Message::root()` and `Message::messages()`.
- Access to MIME boundaries (#127): `MessagePart::boundary()`, `MessagePart::delimiter()` and `Message::part_by_boundary()`, and the raw bytes of a part with `raw()`, `raw_headers()` and `raw_body()`, which exclude the line break before the next delimiter as RFC 2046 defines the body part.
- Part roles (#107): `MessagePart::role()` (`PartRole`) gives every part exactly one role, and `MessageRef::other_parts()` returns the parts in no list.
- `MessageRef::has_attachments()`, the RFC 8621 `hasAttachment` rule: an attachment without `Content-Disposition: inline`.
- `MessagePart::html_utf8()` and `strip_charset_meta()` (#109): the HTML with its `<meta>` charset declarations rewritten to UTF-8, looking only before `<body`. The default decoding does not scan HTML.
- `MessagePart::id()`, `message()`, `parent()`, `kind()` (`PartKind`), `children()`, `nested()`, `flags()` (`PartFlags`), `has_problems()`, `in_text_body()`, `in_html_body()`, `is_attachment()`, `is_inline()`, `encoding()`, `content_transfer_encoding()` and `has_known_transfer_encoding()`.
- `PartFlags` records damaged structure: `MISSING_DELIMITER`, `FALLBACK_DELIMITER`, `NO_BLANK_LINE`, `UNTERMINATED`, `NESTING_LIMIT` and `LIMIT_REACHED`.
- `Headers`, a view of the header fields of any part: `iter()`, `get()`, `all()`, `contains()`, `value()`, `has_known()`, `len()` and the typed getters. `Header::raw_name()` keeps the spelling of the name found in the message, `Header::raw_value()` returns the bytes after the colon, and `Header::parse_as()` parses a field again in another form.
- `HeaderForm::parse()` parses a header value on its own into a `ParsedValue`. `HeaderForm` gains `CommaList`, `ContentType`, `Received` and `Ignore`.
- `AddressList` (#98): `iter()` yields `Address::Mailbox` and `Address::Group` items in document order, `mailboxes()` flattens the groups, `groups()` gives the JMAP `asGroupedAddresses` shape, and `first()`, `last()`, `contains()` and `has_groups()`. `TextList` holds message identifiers and comma-separated lists.
- `MessageParser::parse_owned()` gives a `Message<'static>` that owns its input, and `MessageParser::parse_with()` with `MessageBuffers` and `Message::into_buffers()` reuses the storage of one message for the next. `MessageBuffers::shrink_to(max_bytes)` frees that storage when it exceeds `max_bytes`; otherwise the buffers keep the capacity of the largest message parsed with them.
- `MessageParser::header()` sets the form of one header field and `unknown_headers()` the form of unknown fields; `max_depth()`, `max_parts()` and `max_encoded_nesting()` set the limits (64, 10,000 and 3 by default). After the part limit, the rest of the input stays in the part flagged `LIMIT_REACHED`: the last part when it is a leaf of the innermost open multipart, else that multipart, or the `message/rfc822` part whose nested message had no part yet; the containers left open are not flagged `UNTERMINATED`.
- `HeaderName::key()` resolves a name once into a `HeaderKey`, for `Headers::all_key()` and `Headers::get_key()`, which skip the name lookup that `all()` and `get()` do on every call.
- 112 header names from Stalwart's metadata list are `HeaderName` variants: `X-Mailer`, `User-Agent`, `Precedence`, `X-Priority`, the `X-MS-Exchange`, `X-Google` and `X-GitHub` fields and others.
- `Charset`, with `from_label()`, `decode()`, `decode_owned()`, `decode_append()` and `decode_checked()`, and `decoders::charsets::decode()` and `decode_append()`.
- `Encoding::decode()`, `decode_checked()`, `decode_append()` and `decoded_len()` decode a body stored apart from its message exactly as `MessagePart::decoded()` does.
- `PartId` and `MessageId`, and `From<Encoding> for u8`.
- Value equality for `HeaderValue`, `TextList`, `AddressList`, `ContentType`, `Received` and `ParsedValue`; `Debug` output that shows the content of the views; `Debug` for the mailbox iterators. `Message`, `MessageParser` and the views are `Send + Sync`, and `Message<'x>` is covariant in `'x`.
### Changed
- The parser was rewritten for performance: SIMD kernels find boundaries and header fields (NEON, AVX2 and SSE2, `memchr` on other targets), the header field parsers work on bounded slices, a message is stored in a handful of flat vectors whatever its size, and bodies are decoded only on access, through the SIMD codecs of encodify. See the README for measurements.
- New dependencies: `memchr`, `simdutf8` and `encodify`, next to `hashify`; `encoding_rs` and `serde` stay optional. `unsafe` code is used in the SIMD kernels and in the audited UTF-8 module, whose two functions turn bytes already validated as UTF-8 into `str` and `String`: string spans validated during the parse, and decoded text bodies validated with simdutf8; the rest of the crate denies it. The minimum supported Rust version is 1.98.
- A parsed message is read-only and is read through `Copy` views (`MessageRef`, `MessagePart`, `Headers`, `Header`, `HeaderValue`, `AddressList`, `ContentType`, `Received` and others) that borrow the message, so a value can no longer outlive the `Message` it came from. `Message` is still `Send`, `Sync`, `Clone` and `Default`; `Message::default()` is an empty message with one root part (id 0, no header field, empty body), so `root_part()`, `parts()` and `messages()` agree.
- The header getters return views by value: `from()`, `to()`, `cc()`, `bcc()`, `reply_to()`, `sender()`, the `resent_*()` address getters and the `list_*()` getters return `Option<AddressList>`; `date()` and `resent_date()` return `Option<DateTime>`; `comments()` and `mime_version()` return `Option<&str>`; `in_reply_to()`, `references()`, `keywords()`, `resent_message_id()` and `return_path()` return `Option<TextList>`; `received()` returns `Option<Received>`.
- `text_bodies()` and `html_bodies()` yield the text of the parts of the text and HTML bodies (#73), converting HTML to text and text to HTML and skipping parts that are not text; 0.11 yielded the parts, which are now `text_body()` and `html_body()`. This change is silent where the item is only measured: `message.text_bodies().map(|body| body.len())` still compiles and now measures text.
- Part identifiers are global: parts are numbered in document order across the root message and every nested message, and `Message::part()` takes such an id. A nested message is a `MessageRef` (`PartKind::Message`, `MessagePart::nested()`), no longer a `Message` inside the part. A base64 or quoted-printable encoded `message/rfc822` part is decoded and parsed during the parse; the offsets of its parts refer to its decoded body, as `MessageRef::source()` tells.
- Address fields (#98) are an `AddressList` of mailboxes and groups in document order, whether or not they contain a group. 0.11 returned `Address::List` when there was no group and turned every run of mailboxes into an unnamed group as soon as there was one; that shape is now `AddressList::groups()`.
- Message identifier fields, Keywords and Content-Language are always a `TextList`, even with one item; 0.11 switched between `Text` and `TextList`. `HeaderValue::as_text()` returns the last item of a list.
- The body lists follow the RFC 8621 `parseStructure` algorithm exactly (#67). An image, audio or video part shown in both bodies is no longer also an attachment, and a named `text/html` alternative that follows a `text/plain` becomes an attachment while the `text/plain` is copied into `html_body`. Where the algorithm is silent: a text part of an alternative whose list an ancestor dropped goes to no list, a multipart that cannot be opened stays an attachment, a part without a usable Content-Type is `text/plain` (`message/rfc822` in a digest), and the name test uses the Content-Disposition `filename`, else the Content-Type `name`, an empty name counting as none. The `multipart/alternative` fix-up also runs when the alternative is not closed.
- `PartKind::InlineBinary` and `MessagePart::is_inline()` follow the Content-Disposition (#70): `inline`, or no disposition on a child of `multipart/related` other than the first. 0.11 derived them from the RFC 8621 list rule, so images referenced by `cid:` in a `multipart/related` were `Binary`. The body lists are not affected.
- Decoding no longer changes the part tree. 0.11 turned a part whose body failed to decode into a text part flagged `is_encoding_problem`; 1.0 keeps its kind, decodes it on a best-effort basis and reports the problems through `decoded_checked()` and `text_checked()`. `MessagePart::encoding()` is the declared Content-Transfer-Encoding, comments allowed (`base64 (comment)` is base64).
- `is_encoding_problem` is split: `MessagePart::has_problems()` and `flags()` for damaged structure, `decoded_checked()` and `text_checked()` for decoding.
- MIME delimiters (#156): a delimiter is `--boundary` at the start of a line followed by `--`, a space, a tab, CR, LF or the end of the input, checked against every open boundary, innermost first. A `--boundary` in the middle of a line ends a part only when the part has no valid delimiter at all, and the part is then flagged `FALLBACK_DELIMITER`. A multipart whose first delimiter is its close delimiter looks for a delimiter in the middle of a line of its preamble the same way (flagged `FALLBACK_DELIMITER`); a multipart closed before any part is flagged `MISSING_DELIMITER` and keeps its content in its preamble.
- Malformed structure: a header block ends at a delimiter line (flagged `NO_BLANK_LINE`), an inner multipart that is never closed is closed by an outer delimiter, a part whose delimiter is missing is decoded and classified by its type, and every part ends by one rule (the end of the input, or before the line break that precedes the next delimiter), so a part never ends past its container: when a delimiter cuts a header block, or ends a part together with its container, the part ends where the container ends, and the last header field may end one line break past `offset_body()`.
- RFC 2047 encoded words are decoded by encodify. No space is inserted between plain text and an adjacent encoded word, whitespace between two encoded words is dropped and whitespace between text and a word is kept as written. Adjacent words of one charset are joined before conversion, so a character split across two words decodes, and one-byte charset names are accepted.
- Base64 bodies: bytes outside the alphabet are skipped and reported, a final unpadded quantum is decoded (0.11 dropped it) and a lone sextet before `=` no longer produces a byte. Quoted-printable bodies: `==` and other invalid escapes are kept as written (0.11 failed the whole part on `==`), trailing blanks at the end of the input are deleted (RFC 2045, section 6.7), and a soft line break right before a delimiter no longer deletes content.
- Header blocks: a line without a colon at the end of the input is no longer a header field, the last field keeps its value when the input has no final line break, and a bare CR in unstructured text becomes a space.
- Dates: the zone reader no longer consumes the next line after a `UT` or `Z` zone, and a one-digit zone such as `+5` means +05:00. Received fields: two-digit years follow the date parser (00 to 49 are 20xx), and `]` ends an address literal inside comments.
- `MessageParser::header(name, form)` replaces the builder shorthands and changes the form of one field without dropping the default forms of the others. `unknown_headers()` also applies to the header names added in 1.0, unless they are registered with `header()`.
- `HeaderName`: the names added in 1.0 are variants (`HeaderName::XMailer`), and an `Other` spelled like a known name, such as `Other("X-Mailer")`, equals, hashes and orders as that name; `MessageParser::header()`, `Headers::get()` and `Headers::all()` treat it as that name. `HeaderName::parse()` accepts every character RFC 5322 allows in a field name (printable US-ASCII except the colon; 0.11 accepted only letters, digits, `-` and `_`) and never allocates, and the `From` conversions keep any other string in `Other` with its spelling (0.11 returned `Other("")`, which matched no field). `Header::name()` returns a `HeaderName` (0.11: `&str`).
- A header field that is present but blank and parsed as `Raw` or `Text` has the value `HeaderValue::Text("")`, so an empty `Subject:` gives `subject() == Some("")`, as RFC 8621 `asText` does; 0.11 returned no value. `HeaderValue::Empty` now means that the value does not parse in its form (an empty address list, date or Content-Type included) or that the field is parsed with `HeaderForm::Ignore`.
- Header field names are matched strictly: a name with whitespace or a control character inside it (`Fr om`, `Sub\tject`) or starting with a colon (`:From`) is an unknown field kept with its spelling, where 0.11 read it as the known field, so mail-parser sees the same From and Subject as DKIM and DMARC verifiers. Space and tab between the name and the colon are still accepted (RFC 5322 obsolete syntax).
- RFC 2231 parameters: the sections of a continued parameter are joined before they are converted, with the charset of the first section that declares one (section 0 in conforming input), and a language parameter (`name-language`) is reported once; 0.11 moved a repeated `'lang'` prefix into the value. A Content-Type or Content-Disposition field keeps at most 1,000 parameters.
- `MessageParser::parse_headers()` records the real body offset; 0.11 reported the end of the input.
- `MessageParser::parse()` returns `None` for input with no header field and no blank line, where 0.11 returned a message without headers and with an empty body, dropping the text. It also returns `None` for empty input and for input of 4 GiB or more.
- `preview_text()`, `preview_html()`, `truncate_text()` and `truncate_html()` take `&str`, remove carriage returns themselves and borrow when they can; `body_preview()` decodes only the beginning of the body.
- `text_to_html()` also escapes `&` and `>`.
- `Charset::from_label()` maps the UTF-8 labels to `Charset::Utf8`; `charset_decoder()`, kept for compatibility, still returns `None` for them.
- With the `serde` feature, a `Message` serializes to a new JSON shape (messages and parts in flat lists, with roles, flags and decoding problems) and implements `Serialize` only.
- `mailbox::mbox::MessageIterator` finds separator lines with `memchr` and copies message contents in bulk. After an I/O error inside a line, the partial line is kept and reading continues on the next call.
### Removed
- The `rkyv` and `base64_slice` features.
- The public fields and struct literals of `Message`, `MessagePart`, `Header`, `ContentType`, `Addr`, `Group` and `Attribute`, the methods that changed them (`Message::remove_header()`, `ContentType::remove_attribute()`), and `into_owned()` on parts and values.
- `PartType` (replaced by `PartKind` and the decoding methods), `Addr` (replaced by `Mailbox`), `Attribute`, the `Address::List` and `Address::Group` shapes, `MessagePartId` (now `PartId`), the `GetHeader` and `MimeHeaders` traits (their methods are inherent), `MessageStream`, and the `core` and `parsers` modules.
- `HeaderValue::unwrap_*()`, `into_*()`, `into_owned()` and `len()`; `HeaderForm::GroupedAddresses` and `HeaderForm::URLs` (use `HeaderForm::Addresses`); `HeaderName::len()`, `is_empty()` and `into_string()`.
- The base64, quoted-printable and hex helpers: `base64_decode()`, `base64_decode_slice()`, `base64_decode_stream()`, `quoted_printable_decode()`, `quoted_printable_decode_char()`, `decode_hex()`, `HEX_MAP` and `BASE64_MAP`, with the `decoders::base64`, `decoders::quoted_printable`, `decoders::hex` and `decoders::encoded_word` modules; use encodify directly (`encodify::base64`, `qp`, `hex` and `rfc2047`). The `decoders::charsets::{map, multi_byte, single_byte, utf}` modules are replaced by `Charset`.
- `MessagePart::is_text_html()`, `is_binary()` and `is_empty()`.
- `PartialEq` for `Message` and `MessagePart`, and `Deserialize` for `Message`.
- `trim_trailing_fwd()`, an internal step of `thread_name()`.
### Fixed
- MIME boundaries were matched anywhere in a line, which silently truncated body parts (#156).
- Inline images in `multipart/related` were reported as `Binary` (#70).
- `attachments` included inline media shown in both body lists, against RFC 8621 (#67).
- `resent_cc()` returned the Resent-To field.
- Registering one header parser disabled the default parsers of every other field.
- An RFC 2231 value with a third apostrophe (`filename*=utf-8''O'Brien.txt`) was split at it.
- The comment of an empty address group was attached to the next group.
- `add_html_token()` panicked on invalid UTF-8.
- `FolderIterator::next()` panicked when called after the end of the folders.
- A multipart whose first delimiter line carried text after the boundary (`--b5Content-Type: ...`) made 0.11 panic in debug builds ("Invalid part ID, could not find multipart"); 1.0 keeps the content as a part.
- RFC 2231 parameter sections were converted one by one, so a character split across two sections, or any section after the first in a charset other than UTF-8, became U+FFFD (`name*0*=utf-8''%E2%98; name*1*=%95.txt` now gives `☕.txt`).
- RFC 2231 continuations took quadratic time in the number of sections or parameters of a field.
- UTF-7 dropped the character that ends a base64 run (`+AKM.` gave `£` instead of `£.`) and did not decode `+-` to `+` (RFC 2152).
- A UTF-16 text with an odd number of bytes lost its last byte silently; it now ends with U+FFFD, as documented.
- `DateTime::to_timezone()` overflowed (a panic in debug builds) for offsets near `i64::MIN` or `i64::MAX`; it saturates.
### Migrating from 0.11
| 0.11 | 1.0 |
|---|---|
| `MessageParser::new().with_mime_headers()`, `with_date_headers()`, `with_address_headers()`, `with_message_ids()`, `with_minimal_headers()` | `MessageParser::new()`: the default forms parse these fields |
| `header_text(name)`, `header_date(name)`, `header_address(name)`, `header_id(name)`, `header_comma_separated(name)`, `header_content_type(name)`, `header_received(name)`, `header_raw(name)`, `ignore_header(name)` | `header(name, form)` with `HeaderForm::Text`, `Date`, `Addresses`, `MessageIds`, `CommaList`, `ContentType`, `Received`, `Raw` or `Ignore` |
| `without_header(name)` | `header(name, HeaderForm::Raw)` |
| `default_header_text()`, `default_header_raw()`, `default_header_ignore()` | `unknown_headers(HeaderForm::Text)`, `Raw` or `Ignore` |
| `MessageStream::new(value).parse_address()` and the other `parse_*()` | `HeaderForm::Addresses.parse(value).value()` and the other forms |
| `message.header_as(name, form)` | `header.parse_as(form)` for each field of `message.headers().all(name)` |
| `message.parts`, `message.parts[i]` | `message.parts()`, `message.part(id)` (ids are global across nested messages) |
| `message.text_body`, `html_body`, `attachments` (lists of ids) | `message.text_body()`, `html_body()`, `attachments()` (iterators of `MessagePart`; `part.id()` gives the id) |
| `message.text_part(i)`, `html_part(i)`, `attachment(i)` | `message.text_body().nth(i)`, `html_body().nth(i)`, `attachments().nth(i)` |
| `message.text_body_count()`, `html_body_count()`, `attachment_count()` | `message.text_body().len()`, `html_body().len()`, `attachments().len()` |
| `message.text_bodies()`, `html_bodies()` (parts) | `message.text_body()`, `html_body()`; `text_bodies()` and `html_bodies()` now yield text |
| `message.raw_message`, `raw_message()` | `message.raw()` (the input) or `message.root().raw()` (the range of the root message) |
| `message.header(name)` | `message.headers().value(name)` |
| `message.header_raw(name)` | `raw_value()` (bytes) of `message.headers().get(name)` |
| `message.header_values(name)` | `value()` of each field of `message.headers().all(name)` |
| `message.headers()` (a slice), `headers_raw()` | `message.headers()` (a `Headers` view, iterated with `for header in message.headers()` or `iter()`); `raw_name()` and `raw_value()` of each field |
| `message.remove_header(name)` | No replacement: messages are read-only |
| `message.is_empty()` | `parse()` returns `None` for such input; `headers().has_known()` |
| `from()`, `to()`, `cc()` and the other address getters (`Option<&Address>`) | `Option<AddressList>` |
| `date()` (`Option<&DateTime>`), `resent_date()` (`&HeaderValue`) | `Option<DateTime>` |
| `in_reply_to()`, `references()`, `keywords()`, `resent_message_id()`, `return_path()` (`&HeaderValue`) | `Option<TextList>` |
| `list_archive()` to `list_unsubscribe()` (`&HeaderValue`) | `Option<AddressList>` |
| `comments()`, `mime_version()` (`&HeaderValue`) | `Option<&str>` |
| `received()` (`Option<&Received>`) | `Option<Received>` |
| `received_all()` | `all_received()`, like `all_to()`, `all_cc()` and `all_bcc()` |
| `part.body` (`PartType`) | `part.kind()` (`PartKind`), with `text()`, `decoded()`, `nested()` and `children()` for the content |
| `part.contents()` | `part.decoded()` |
| `part.text_contents()` | `part.text()` |
| `part.message()` (the nested message) | `part.nested()`; `part.message()` now returns the message the part belongs to |
| `part.sub_parts()` | `part.children()` |
| `part.len()` | `part.decoded_len()` |
| `part.is_text_html()`, `part.is_binary()`, `part.is_empty()` | a match on `part.kind()`; `part.decoded_len() == 0` |
| `part.is_encoding_problem` | `part.has_problems()` and `part.flags()`; `decoded_checked()` and `text_checked()` |
| `part.encoding`, `part.headers` | `part.encoding()`, `part.headers()` |
| `part.offset_header`, `offset_body`, `offset_end`, `raw_header_offset()`, `raw_body_offset()`, `raw_end_offset()` | `part.offset_header()`, `offset_body()`, `offset_end()` |
| `part.raw_len()` | `part.raw().len()` |
| `MimeHeaders` methods (`content_type()`, `content_id()`, `attachment_name()`, ...) | Inherent methods of `MessagePart` and `MessageRef`; `content_language()` returns `Option<TextList>` |
| `PartType::Message(message)` | `PartKind::Message(message)`, a `MessageRef` |
| `header.name` (a `HeaderName`), `header.name()` (a `&str`) | `header.name()` (a `HeaderName`), `header.raw_name()` (as written) |
| `header.value`, `header.offset_*` | `header.value()`, `header.offset_field()`, `offset_start()`, `offset_end()` (same meaning) |
| `GetHeader::header()`, `header_value()` | `Headers::get()`, `Headers::value()` |
| `HeaderValue::Text(Cow<str>)` | `HeaderValue::Text(&str)` |
| `HeaderValue::TextList(Vec<Cow<str>>)` | `HeaderValue::TextList(TextList)`, also for a single item |
| `HeaderValue::Address(Address::List(..))`, `HeaderValue::Address(Address::Group(..))` | `HeaderValue::Address(AddressList)` with `iter()`, `mailboxes()` and `groups()` |
| `HeaderValue::Received(Box<Received>)` | `HeaderValue::Received(Received)`; hosts are returned by value |
| `value.unwrap_text()`, `into_text()` and the other `unwrap_*()` and `into_*()` | `as_text()`, `as_text_list()`, `as_address()`, `as_datetime()`, `as_content_type()`, `as_received()` |
| `Address::first()`, `last()`, `contains()`, `iter()` | `AddressList::first()`, `last()`, `contains()`, `mailboxes()` |
| `Address::as_list()`, `as_group()`, `into_list()`, `into_group()` | `AddressList::mailboxes()`, `AddressList::groups()` |
| `Addr` (`name`, `address`) | `Mailbox` (`name()`, `address()`) |
| `Group` (`name`, `addresses`) | `Group` (`name()`, `mailboxes()`) |
| `ContentType` (`c_type`, `c_subtype`, `attributes`) | `ContentType` (`ctype()`, `subtype()`, `attribute()`, `attributes()` yielding name and value) |
| `HeaderName::Other("X-Mailer")` and the other names added in 1.0 | `HeaderName::XMailer`; an `Other` with the same spelling still finds and configures the field, but `header.name()` returns the variant |
| `HeaderValue::Empty` for a blank Subject or other text field (`subject() == None`) | `HeaderValue::Text("")` (`subject() == Some("")`) |
| `HeaderName::from("X.Spam")` gave `Other("")` | `Other("X.Spam")`, which finds the field |
| `HeaderName::into_string()`, `len()` | `String::from(name)`, `name.as_str().len()` |
| `MessagePartId` | `PartId` |
| `decoders::base64::base64_decode()`, `base64_decode_slice()`, `base64_decode_stream()`, `BASE64_MAP` | `encodify::base64` |
| `decoders::quoted_printable::quoted_printable_decode()`, `quoted_printable_decode_char()`, `HEX_MAP` | `encodify::qp` |
| `decoders::hex::decode_hex()` | `encodify::hex` |
| `decoders::charsets::map::charset_decoder()` | `Charset::from_label()` and `Charset::decode()`; `decoders::charsets::charset_decoder()` is kept |
| `parsers::preview::preview_text()` and the other preview functions (taking `Cow<str>`) | `preview_text()` and the others at the crate root, taking `&str` |
| `parsers::fields::thread::thread_name()` | `thread_name()` |
| `parsers::fields::address::parse_address_local_part()` and the other address helpers | `parse_address_local_part()` and the others at the crate root |
| `rkyv` feature | No replacement |
| `base64_slice` feature | encodify |
## [0.11.9] - 2026-09-09
### Added
- Added `base64_decode_slice` behind the new `base64_slice` feature, which adds a `memchr` dependency.
## [0.11.8] - 2026-08-22
### Fixed
- `HeaderName` breaks rkyv serialization from <= 0.11.6.
## [0.11.7] - 2026-08-20
### Added
- Added more IANA headers.
### Fixed
- `DateTime::to_timezone` corrupting non-whole-hour offsets by storing leftover seconds in `tz_minute` (#158)
## [0.11.6] - 2026-08-10
### Fixed
- Missing whitespace between a quoted name and a following encoded word (#150)
- `panic` when a `Received` header ends with a folded line (#155)
- `Received` header tokens losing their last character at the end of the input, retaining folding characters, and failing to parse a clause folded before its value (#155)
- Multi-word display names followed by a comment no longer produce a fabricated address (#153)
## [0.11.5] - 2026-07-08
### Added
- Recognize additional charset labels supported by `encoding_rs` (#123)
- Added `Dkim2Signature` and `MessageInstance` to support DKIM2 headers.
### Fixed
- Address names containing LF are not parsed correctly (#149)
- Decode the `iso-8859-1` label as `windows-1252` per the WHATWG Encoding Standard (#131)
- `panic` with messages containing corrupted eml attachments (#120).
## [0.11.4] - 2026-06-21
### Added
- Add `Message::received_all()` to iterate over all Received header fields (#146)
### Changed
- Reject dates with invalid month names.
- Leniently decode quoted-printable bodies with invalid `=` escapes (#144)
### Fixed
- `parse_date()` doesn't handle UTC+12 and greater (#148)
## [0.11.3] - 2026-05-02
### Fixed
- Fix panic with messages containing corrupted attachments (#145)
## [0.11.2] - 2026-02-14
### Fixed
- Do not return invalid mime parts when parsing broken nested messages.
- Fix broken receive header date parsing when tab is used in long header syntax (#130)
## [0.11.1] - 2025-08-18
### Fixed
- Fix `DateTime::from_timestamp` to handle negative timestamps correctly.
## [0.11.0] - 2025-05-11
### Added
- `rkyv` zero-copy deserialization support.
### Changed
- Changed `usize` to `u32` types.
- Renamed `serde_support` feature to `serde`.
### Fixed
- Parsing of headers without LFs (#102)
## [0.10.2] - 2025-01-28
### Fixed
- Fixed `HeaderName` enum order to avoid breaking bincode serialization.
## [0.10.1] - 2025-01-26
### Fixed
- Fixed `HeaderName::parse` function.
## [0.10.0] - 2025-01-26
### Added
- Added `DkimSignature`, `ArcAuthenticationResults`, `ArcMessageSignature` and `ArcSeal` headers.
### Changed
- Perfect hashing using `hashify` crate rather than static `gperf` generated code.
- `HeaderName` is non-exhaustive.
- Parse obsolete timezones (#95).
- Retain mbox IO errors (#91).
- Hide concrete type behind impl type (#94).
### Removed
- Removed `ludicrous` feature, the Rust compiler is smart enough to optimize array lookups.
### Fixed
- Folding ws between "Content-Type:" and "plain/text" leads to empty header (#96).
- Multiline quoted continuations (closes #92).
- Deserialize (#93).
## [0.9.4] - 2024-09-04
### Changed
- Flexible parsing of charset names (#85).
## [0.9.3] - 2024-03-28
### Fixed
- Fixed parsing of address names containing @ (#80)
## [0.9.2] - 2023-11-27
### Fixed
- Fixed `quoted_printable_decode` external function (not used by mail-parser directly).
- Fix `Received` header serialization for bincode compatibility.
## [0.9.1] - 2023-09-22
### Changed
- Updated Rust edition to 2021.
### Removed
- Removed `content_type()` and `address()` functions that could `panic!`. Use `as_content_type()` and `as_address()` instead.
### Fixed
- Fixed panic when Content-Disposition is empty (#63)
## [0.9.0] - 2023-09-05
This version introduces multiple breaking changes. Please read the following notes carefully.
### Added
- Added parser for `Received` headers.
- Added `MessageParser::parse_headers` function to parse only the headers of a message.
### Changed
- Parsing is now done using `MessageParser`, which allows to customize the parsing process.
- All address types are now stored in the `HeaderValue::Address` variant using the `Address` enum.
- Renamed the `as_` prefix to `to_` in some functions.
### Removed
- Removed `RfcHeader` enum, now all headers are represented using `HeaderName`.
## [0.8.2] - 2023-02-22
### Fixed
- Parsing address name with \ characters (#41)
- Missing space when folded header begins with RFC2047 word (#43)
## [0.8.1] - 2023-02-09
### Added
- Added `raw_message()` function. - Added `raw_message()` function.
mail-parser 0.8.0 ## [0.8.0] - 2022-12-01
================================
### Changed
- Removed get_() prefixes (#31). - Removed get_() prefixes (#31).
- Maildir import: Use modified time instead of created time (#32) - Maildir import: Use modified time instead of created time (#32)
mail-parser 0.7.0 ## [0.7.0] - 2022-10-21
================================
- Base64/QuotedPrintable decoding optimizations. ### Added
- Automatic parsing of base64/qp encoded nested messages. - Automatic parsing of base64/qp encoded nested messages.
- Refactoring or ``MessageStream`` to use iterators more efficiently.
- Added "ludicrous mode" Cargo option to use some unsafe code for additional performance. - Added "ludicrous mode" Cargo option to use some unsafe code for additional performance.
### Changed
- Base64/QuotedPrintable decoding optimizations.
- Refactoring or ``MessageStream`` to use iterators more efficiently.
### Fixed
- Fixed support for empty messages. - Fixed support for empty messages.
- Fixed raw offsets of multipart/* parts to include MIME epilogue. - Fixed raw offsets of multipart/* parts to include MIME epilogue.
- Fixed values of non-RFC headers. - Fixed values of non-RFC headers.
mail-parser 0.6.1 ## [0.6.1] - 2022-09-09
================================
### Added
- Support for malformed unstructured fields containing encoded words (#29). - Support for malformed unstructured fields containing encoded words (#29).
- Add support for gb2312 charsets (#30). - Add support for gb2312 charsets (#30).
mail-parser 0.6.0 ## [0.6.0] - 2022-08-21
================================
### Added
- Maildir parsing support. - Maildir parsing support.
- Headers and attributes are now stored in a `Vec` instead of a `HashMap` for tiny performance enhancement.
- Support for Content-Type attributes spanning multiple lines. - Support for Content-Type attributes spanning multiple lines.
- Support for malformed Thunderbird messages (#27). - Support for malformed Thunderbird messages (#27).
### Changed
- Headers and attributes are now stored in a `Vec` instead of a `HashMap` for a tiny performance enhancement.
### Fixed
- Fixed raw offset range for body parts. - Fixed raw offset range for body parts.
mail-parser 0.5.0 ## [0.5.0] - 2022-07-15
================================
### Added
- Added raw offsets to MIME parts.
### Changed
- `Message` headers are now stored as a `MessagePart` with index 0. - `Message` headers are now stored as a `MessagePart` with index 0.
- Improved `MessagePart` API. - Improved `MessagePart` API.
- Nested base64/quoted-printable encoded message/rfc822 parts are automatically parsed when calling `get_message`. - Nested base64/quoted-printable encoded message/rfc822 parts are automatically parsed when calling `get_message`.
- Better handling of malformed MIME messages. - Better handling of malformed MIME messages.
- Added raw offsets to MIME parts.
mail-parser 0.4.8 ## [0.4.8] - 2022-06-06
================================
### Fixed
- get_bytes_to_boundary fix (#21) - get_bytes_to_boundary fix (#21)
mail-parser 0.4.7 ## [0.4.7] - 2022-06-03
================================
### Added
- Retrieving message headers in order (#19) - Retrieving message headers in order (#19)
- Added `get_raw_headers` and `get_header` methods. - Added `get_raw_headers` and `get_header` methods.
- Added `get_return_address` method to obtain the return address from the Return-Path or From headers. - Added `get_return_address` method to obtain the return address from the Return-Path or From headers.
- Support for malformed Return-Path headers. - Support for malformed Return-Path headers.
- Support for ks_c_5601 charsets (#20) - Support for ks_c_5601 charsets (#20)
mail-parser 0.4.6 ## [0.4.6]
================================
### Fixed
- DateTime is_valid() fix (#15) - DateTime is_valid() fix (#15)
mail-parser 0.4.5 ## [0.4.5] - 2022-03-14
================================
### Added
- DateTime to UNIX timestamp conversion. - DateTime to UNIX timestamp conversion.
- Ord, PartialOrd support for DateTime (#13). - Ord, PartialOrd support for DateTime (#13).
### Fixed
- Fixed Message::parse() panic on duplicate Content-Type headers (#14). - Fixed Message::parse() panic on duplicate Content-Type headers (#14).
mail-parser 0.4.4 ## [0.4.4] - 2022-01-24
================================
### Added
- Support for multi-line headers. - Support for multi-line headers.
- Text and HTML message body preview. - Text and HTML message body preview.
### Changed
- Improved support for raw headers. - Improved support for raw headers.
mail-parser 0.4.3 ## [0.4.3] - 2021-12-31
================================
### Added
- Mbox file parsing support (issue #11) conforming to the [QMail specification](http://qmail.org/qmail-manual-html/man5/mbox.html). - Mbox file parsing support (issue #11) conforming to the [QMail specification](http://qmail.org/qmail-manual-html/man5/mbox.html).
- Support for bincode serialize/deserialize. - Support for bincode serialize/deserialize.
mail-parser 0.4.2 ## [0.4.2] - 2021-12-22
================================
### Added
- Added `Message::get_thread_name()` to obtain the base subject of a message as defined in [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1). - Added `Message::get_thread_name()` to obtain the base subject of a message as defined in [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1).
- Added `MimeHeader::get_attachment_name` for simplified access to a MIME attachment file name. - Added `MimeHeader::get_attachment_name` for simplified access to a MIME attachment file name.
mail-parser 0.4.1 ## [0.4.1] - 2021-12-16
================================
- Lazy parsing of nested e-mail messages. ### Added
- Support for base64/quoted-printable nested messages. - Support for base64/quoted-printable nested messages.
mail-parser 0.4.0 ### Changed
================================ - Lazy parsing of nested e-mail messages.
## [0.4.0] - 2021-12-16
### Changed
- Lazy conversion to/from HTML an plain text parts. - Lazy conversion to/from HTML an plain text parts.
- Improved API. - Improved API.
- Parts are now generics. - Parts are now generics.
mail-parser 0.3.1 ## [0.3.1] - 2021-12-15
================================
### Added
- Support for non-standard headers. - Support for non-standard headers.
### Changed
- Raw message offsets are stored in the message object. - Raw message offsets are stored in the message object.
- Message body structure is now stored in the message object. - Message body structure is now stored in the message object.
mail-parser 0.3 ## [0.3.0] - 2021-11-08
================================
- Improved API, now `Message::parse` returns `Option<Message>` to indicate when parsing was successful. ### Added
- Headers are now stored internally in a `HashMap` instead of `struct` fields.
- Added support for new RFCs: - Added support for new RFCs:
- [RFC 2557 - MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)](https://datatracker.ietf.org/doc/html/rfc2557) - [RFC 2557 - MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)](https://datatracker.ietf.org/doc/html/rfc2557)
- [RFC 2392 - Content-ID and Message-ID Uniform Resource Locators](https://datatracker.ietf.org/doc/html/rfc2392) - [RFC 2392 - Content-ID and Message-ID Uniform Resource Locators](https://datatracker.ietf.org/doc/html/rfc2392)
- [RFC 3282 - Content Language Headers](https://datatracker.ietf.org/doc/html/rfc3282) - [RFC 3282 - Content Language Headers](https://datatracker.ietf.org/doc/html/rfc3282)
- [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339) - [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339)
mail-parser 0.2.1 ### Changed
================================ - Improved API, now `Message::parse` returns `Option<Message>` to indicate when parsing was successful.
- Headers are now stored internally in a `HashMap` instead of `struct` fields.
## [0.2.2] - 2021-11-04
### Changed
- Improved decoder results.
- Dependency requirements for `encoding_rs`, `serde` and `serde_bytes` use caret ranges (`0.8`, `1.0` and `0.11`) instead of `>=0.8.28`, `>=1.0.117` and `>=0.11.5`.
## [0.2.1] - 2021-11-03
### Changed
- Performance enhacements, now *mail-parser* is almost as fast as the `unsafe` 0.1 version. - Performance enhacements, now *mail-parser* is almost as fast as the `unsafe` 0.1 version.
mail-parser 0.2 ## [0.2.0] - 2021-11-03
================================
- Re-factoring to use **100% safe** Rust after a [discussion on Reddit](https://www.reddit.com/r/rust/comments/qkc5rk/fast_and_robust_email_parsing_library_for_rust/). ### Added
- Added `Message::is_empty`. - Added `Message::is_empty`.
mail-parser 0.1.1 ### Changed
================================ - Re-factoring to use **100% safe** Rust after a [discussion on Reddit](https://www.reddit.com/r/rust/comments/qkc5rk/fast_and_robust_email_parsing_library_for_rust/).
## [0.1.1] - 2021-11-02
### Fixed
- Bug-fixing after **fuzzing** the library. - Bug-fixing after **fuzzing** the library.
mail-parser 0.1 ## [0.1.0] - 2021-11-01
================================
### Added
- Initial release with plenty of `unsafe` code to speed things up. - Initial release with plenty of `unsafe` code to speed things up.
+41 -14
View File
@@ -1,34 +1,61 @@
[package] [package]
name = "mail-parser" name = "mail-parser"
description = "Fast and robust e-mail parsing library for Rust" description = "Fast and robust e-mail parsing library for Rust"
version = "0.8.1" version = "1.0.3"
edition = "2018" edition = "2024"
rust-version = "1.98"
authors = [ "Stalwart Labs <hello@stalw.art>"] authors = [ "Stalwart Labs <hello@stalw.art>"]
license = "Apache-2.0 OR MIT" license = "Apache-2.0 OR MIT"
repository = "https://github.com/stalwartlabs/mail-parser" repository = "https://github.com/stalwartlabs/mail-parser"
homepage = "https://github.com/stalwartlabs/mail-parser" homepage = "https://github.com/stalwartlabs/mail-parser"
keywords = ["email", "mime", "mail", "parser", "e-mail"] keywords = ["email", "mail", "parser", "parse", "mime"]
categories = ["email", "parser-implementations"] categories = ["email", "parser-implementations"]
readme = "README.md" readme = "README.md"
resolver = "2" exclude = ["benches/compare"]
[dependencies] [dependencies]
encoding_rs = { version="0.8", optional=true } hashify = "0.3"
serde = { version = "1.0", features = ["derive"], optional=true } memchr = "2.8"
simdutf8 = "0.1"
encodify = { version = "1.0" }
encoding_rs = { version = "0.8", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
[dev-dependencies] [dev-dependencies]
mail-parser = { path = ".", features = ["serde_support", "full_encoding"] }
serde = { version = "1.0", features = ["derive"] }
serde_yaml = "0.8" # Version 0.9 fails to parse certain inputs
serde_json = "1.0" serde_json = "1.0"
bincode = "1.3.3"
chrono = "0.4" chrono = "0.4"
criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support"] }
[features] [features]
default = ["full_encoding"] default = []
full_encoding = ["encoding_rs"] full_encoding = ["dep:encoding_rs"]
serde_support = ["serde"] serde = ["dep:serde"]
ludicrous_mode = []
[[bench]]
name = "kernels"
harness = false
[[bench]]
name = "resolve"
harness = false
[[bench]]
name = "text_prefix"
harness = false
[[bench]]
name = "html"
harness = false
[lints.rust]
rust_2018_idioms = { level = "deny", priority = -1 }
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "deny"
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(mail_parser_checked_str)"] }
[lints.clippy]
undocumented_unsafe_blocks = "deny"
unwrap_used = "deny"
[profile.bench] [profile.bench]
debug = true debug = true
View File
+404 -156
View File
@@ -3,38 +3,40 @@
[![crates.io](https://img.shields.io/crates/v/mail-parser)](https://crates.io/crates/mail-parser) [![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) [![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) [![docs.rs](https://img.shields.io/docsrs/mail-parser)](https://docs.rs/mail-parser)
[![msrv](https://img.shields.io/crates/msrv/mail-parser)](https://crates.io/crates/mail-parser)
[![crates.io](https://img.shields.io/crates/l/mail-parser)](http://www.apache.org/licenses/LICENSE-2.0) [![crates.io](https://img.shields.io/crates/l/mail-parser)](http://www.apache.org/licenses/LICENSE-2.0)
_mail-parser_ is an **e-mail parsing library** written in Rust that fully conforms to the Internet Message Format standard (_RFC 5322_), the _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 many other [internet messaging RFCs](#conformed-rfcs).
Multipurpose Internet Mail Extensions (MIME; _RFC 2045 - 2049_) as well as many 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. 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 Japanese languages such as BIG5 or ISO-2022-JP is provided by the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs).
All Unicode (UTF-*) and single-byte character sets are handled internally by the library while support for legacy multi-byte encodings of Chinese
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 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-conformant e-mail messages as long as these do not deviate too much from the standard.
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-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 Besides the MIME tree, every message comes with the three body lists of [RFC 8621, Section 4.1.4](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4): the text body, the HTML body and the attachments. HTML is converted to plain text, and plain text to HTML, when a part has no alternative in the other format.
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_: ## Features
- **Zero-copy**: Practically all strings returned by this library are `Cow<str>` references to the input raw message. - **Fast parsing**:
- **High performance Base64 decoding** based on Chromium's decoder ([the fastest non-SIMD decoder](https://github.com/lemire/fastbase64)). - Boundaries and header fields are found by SIMD kernels (NEON on aarch64, AVX2 and SSE2 on x86-64, `memchr` on every other target).
- **Fast parsing** of message header fields, character set names and HTML entities using [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function). - Base64 and quoted-printable are decoded by the SIMD codecs of [encodify](https://github.com/stalwartlabs/encodify)
- Written in **100% safe** Rust with no external dependencies. - UTF-8 is validated by [simdutf8](https://crates.io/crates/simdutf8)
- Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and - Header names, charset labels and HTML entities are looked up with perfect hashing through [hashify](https://crates.io/crates/hashify).
thoroughly [tested with MIRI](#testing-fuzzing--benchmarking). - **Lazy decoding**: Nothing is transfer-decoded or converted from its character set during the parse; a message whose attachments are never read never pays for decoding them.
- **Battle-tested** with millions of real-world e-mail messages dating from 1995 until today. - **Zero-copy**: Practically all strings returned by this library are references to the input raw message.
- **Battle-tested** with millions of real-world e-mail messages dating from 1995 until today.
- Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and thoroughly [tested with MIRI](#testing-fuzzing--benchmarking).
- Used in production environments worldwide by [Stalwart Mail Server](https://github.com/stalwartlabs/mail-server).
## Usage Example > Note: This library does not support building e-mail messages as this functionality is provided separately by the [`mail-builder`](https://crates.io/crates/mail-builder) crate.
## Usage
### Parse a message
```rust ```rust
let input = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries) use mail_parser::{Address, MessageParser, PartKind};
let input = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)
To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends: To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends:
jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>; jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;
Date: Sat, 20 Nov 2021 14:22:01 -0800 Date: Sat, 20 Nov 2021 14:22:01 -0800
@@ -75,127 +77,365 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
--festivus-- --festivus--
"#; "#;
let message = Message::parse(input).unwrap(); let message = MessageParser::default().parse(input).expect("a message");
// Parses addresses (including comments), lists and groups let sender = message.from().and_then(|from| from.first()).expect("a sender");
assert_eq!( assert_eq!(sender.name(), Some("Art Vandelay (Vandelay Industries)"));
message.from(), assert_eq!(sender.address(), Some("art@vandelay.com"));
&HeaderValue::Address(Addr::new(
"Art Vandelay (Vandelay Industries)".into(),
"art@vandelay.com"
))
);
assert_eq!( let to = message.to().expect("recipients");
message.to(), let addresses: Vec<_> = to.mailboxes().filter_map(|mailbox| mailbox.address()).collect();
&HeaderValue::GroupList(vec![ assert_eq!(addresses, ["james@vandelay.com", "jane@example.com", "john@example.com"]);
Group::new( let Some(Address::Group(friends)) = to.iter().nth(1) else {
"Colleagues", panic!("the second item is a group");
vec![Addr::new("James Smythe".into(), "james@vandelay.com")] };
), assert_eq!(friends.name(), Some("Friends"));
Group::new( assert_eq!(friends.mailboxes().nth(1).and_then(|mailbox| mailbox.name()), Some("John Smîth"));
"Friends",
vec![
Addr::new(None, "jane@example.com"),
Addr::new("John Smîth".into(), "john@example.com"),
]
)
])
);
assert_eq!( assert_eq!(message.date().expect("a date").to_rfc3339(), "2021-11-20T14:22:01-08:00");
message.date().unwrap().to_rfc3339(), assert_eq!(message.subject(), Some("Why not both importing AND exporting? ☺"));
"2021-11-20T14:22:01-08:00"
);
// RFC2047 support for encoded text in message readers assert_eq!(
assert_eq!( message.body_html(0).as_deref(),
message.subject().unwrap(), Some(concat!(
"Why not both importing AND exporting? ☺" "<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>"
))
);
assert_eq!(
message.body_text(0).as_deref(),
Some(concat!(
"I was thinking about quitting the “exporting” to focus just on the",
" “importing”,\nbut then I thought, why not do both? ☺\n"
))
);
// HTML and text body parts are returned conforming to RFC8621, Section 4.1.4 let nested = message
assert_eq!( .attachments()
message.body_html(0).unwrap(), .find_map(|part| part.nested())
concat!( .expect("a nested message");
"<html><p>I was thinking about quitting the &ldquo;exporting&rdquo; to ", assert_eq!(nested.subject(), Some("Exporting my book about coffee tables"));
"focus just on the &ldquo;importing&rdquo;,</p><p>but then I thought,", assert_eq!(nested.body_text(0).as_deref(), Some("ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"));
" why not do both? &#x263A;</p></html>" assert_eq!(
) nested.body_html(0).as_deref(),
); Some("<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>")
);
// HTML parts are converted to plain text (and viceversa) when missing let image = nested.attachments().next().expect("an attachment");
assert_eq!( assert_eq!(image.attachment_name(), Some("Book about ☕ tables.gif"));
message.body_text(0).unwrap(), assert!(matches!(image.kind(), PartKind::Binary));
concat!( assert_eq!(image.decoded_len(), 42);
"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 = message
.attachment(0)
.unwrap()
.message();
.unwrap();
assert_eq!(
nested_message.subject().unwrap(),
"Exporting my book about coffee tables"
);
// Handles UTF-* as well as many legacy encodings
assert_eq!(
nested_message.body_text(0).unwrap(),
"ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!"
);
assert_eq!(
nested_message.body_html(0).unwrap(),
"<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
);
let nested_attachment = nested_message.attachment(0).unwrap();
assert_eq!(nested_attachment.len(), 42);
// Full RFC2231 support for continuations and character sets
assert_eq!(
nested_attachment.attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
// Integrates with Serde
println!("{}", serde_json::to_string_pretty(&message).unwrap());
println!("{}", serde_yaml::to_string(&message).unwrap());
``` ```
More examples available under the [examples](examples) directory. Please note that this library does not support building e-mail messages as this functionality is provided separately by the [`mail-builder`](https://crates.io/crates/mail-builder) crate. ### Read header fields
```rust
use mail_parser::{HeaderName, HeaderValue, MessageParser};
let raw = b"Received: from mx.example.com by mail.example.org; Sat, 20 Nov 2021 14:22:05 -0800\r\n\
Message-ID: <1234@example.com>\r\n\
X-Priority: 1\r\n\
X-Custom: first\r\n\
X-Custom: second\r\n\
Subject: Status report\r\n\
\r\n\
Body\r\n";
let message = MessageParser::new().parse(raw).expect("a message");
let headers = message.headers();
assert_eq!(message.message_id(), Some("1234@example.com"));
assert_eq!(headers.get("x-custom").map(|header| header.raw_value()), Some(&b" second\r\n"[..]));
assert_eq!(headers.all("X-Custom").count(), 2);
assert!(headers.contains(HeaderName::XPriority));
for header in headers {
match header.value() {
HeaderValue::Text(text) => println!("{}: {text}", header.raw_name()),
HeaderValue::Received(received) => println!("received by {:?}", received.by()),
other => println!("{}: {other:?}", header.raw_name()),
}
}
```
### Decode bodies on demand
```rust
use mail_parser::{DecodeProblems, MessageParser};
let raw = concat!(
"Content-Type: multipart/mixed; boundary=\"b\"\r\n",
"\r\n",
"--b\r\n",
"Content-Type: text/plain; charset=iso-8859-1\r\n",
"Content-Transfer-Encoding: quoted-printable\r\n",
"\r\n",
"Caf=E9 cr=E8me\r\n",
"--b\r\n",
"Content-Type: application/octet-stream\r\n",
"Content-Transfer-Encoding: base64\r\n",
"\r\n",
"AAEC*AwQF\r\n",
"--b--\r\n",
);
let message = MessageParser::new().parse(raw).expect("a message");
let text = message.text_body().next().expect("a text part");
assert_eq!(text.text().as_deref(), Some("Café crème"));
assert_eq!(text.text_prefix(4).as_deref(), Some("Café"));
let file = message.attachments().next().expect("an attachment");
assert_eq!(file.decoded().as_ref(), b"\x00\x01\x02\x03\x04\x05");
assert_eq!(file.decoded_len(), 6);
let (_, problems) = file.decoded_checked();
assert!(problems.contains(DecodeProblems::MALFORMED_TRANSFER_ENCODING));
```
### Walk the MIME structure
```rust
use mail_parser::{MessageParser, Source};
let raw = concat!(
"Content-Type: multipart/mixed; boundary=\"outer\"\r\n",
"\r\n",
"--outer\r\n",
"Content-Type: multipart/alternative; boundary=\"inner\"\r\n",
"\r\n",
"--inner\r\n",
"Content-Type: text/plain\r\n",
"\r\n",
"Hello\r\n",
"--inner\r\n",
"Content-Type: text/html\r\n",
"\r\n",
"<p>Hello</p>\r\n",
"--inner--\r\n",
"--outer\r\n",
"Content-Type: message/rfc822\r\n",
"Content-Transfer-Encoding: base64\r\n",
"\r\n",
"U3ViamVjdDogRm9yd2FyZGVkDQoNCkJvZHkNCg==\r\n",
"--outer--\r\n",
);
let message = MessageParser::new().parse(raw).expect("a message");
let alternative = message.part_by_boundary("inner").expect("a multipart");
assert_eq!(alternative.id(), 1);
assert_eq!(alternative.delimiter(), Some("outer"));
let html = alternative.children().nth(1).expect("the HTML part");
assert_eq!(html.delimiter(), Some("inner"));
assert_eq!(html.raw_body(), b"<p>Hello</p>");
let forwarded = message.parts().find_map(|part| part.nested()).expect("a nested message");
assert_eq!(forwarded.subject(), Some("Forwarded"));
assert_eq!(forwarded.container().map(|part| part.id()), Some(4));
assert_eq!(forwarded.source(), Source::Decoded(4));
assert_eq!(forwarded.body_text(0).as_deref(), Some("Body\r\n"));
assert_eq!(message.parts().len(), 6);
```
### Parse many messages
```rust
use mail_parser::{MessageBuffers, MessageParser, mailbox::mbox::MessageIterator};
let mbox = b"From ann@example.com Sat Jan 3 01:05:34 1996\n\
Subject: first\n\
\n\
Hello\n\
From bob@example.com Sat Jan 3 01:06:10 1996\n\
Subject: second\n\
\n\
Hi\n";
let parser = MessageParser::new();
let mut buffers = MessageBuffers::new();
let mut subjects = Vec::new();
for entry in MessageIterator::new(&mbox[..]) {
let entry = entry.expect("a readable mbox");
if let Some(message) = parser.parse_with(entry.contents(), &mut buffers) {
subjects.push(message.subject().unwrap_or_default().to_string());
buffers = message.into_buffers();
}
}
assert_eq!(subjects, ["first", "second"]);
```
### Parse header values on their own
```rust
use mail_parser::{DateTime, HeaderForm};
let parsed = HeaderForm::Addresses.parse(b" Ann <ann@example.com>, bob@example.com\r\n");
let list = parsed.value().as_address().expect("an address list");
assert_eq!(list.mailboxes().count(), 2);
let subject = HeaderForm::Text.parse(b" =?utf-8?q?caf=C3=A9?= au lait\r\n");
assert_eq!(subject.value().as_text(), Some("café au lait"));
let date = DateTime::parse_rfc822("Sat, 20 Nov 2021 14:22:01 -0800").expect("a date");
assert_eq!(date.to_timestamp(), 1_637_446_921);
```
### Configure the parser
```rust
use mail_parser::{HeaderForm, HeaderName, MessageParser};
let parser = MessageParser::new()
.header(HeaderName::Received, HeaderForm::Raw)
.header("X-Sender", HeaderForm::Addresses)
.unknown_headers(HeaderForm::Ignore)
.max_depth(16)
.max_parts(500);
let message = parser
.parse(b"X-Sender: <kel@vandelay.com>\r\nX-Spam: yes\r\n\r\nbody")
.expect("a message");
let sender = message
.headers()
.value("X-Sender")
.and_then(|value| value.as_address())
.and_then(|list| list.first());
assert_eq!(sender.and_then(|mailbox| mailbox.address()), Some("kel@vandelay.com"));
assert!(message.headers().value("X-Spam").is_some_and(|value| value.is_empty()));
```
Build a parser once and share it; it is `Send` and `Sync`. `header(name, form)` sets the form of one header field, `unknown_headers(form)` the form of every field with a name the parser does not know. Content-Type, Content-Disposition and Content-Transfer-Encoding always keep their MIME form. The defaults are the forms 0.11 used:
| Form | Header fields |
|---|---|
| `Text` | Subject, Comments, Content-Description, Content-Location, Content-Transfer-Encoding |
| `Addresses` | From, To, Cc, Bcc, Reply-To, Sender, Resent-From, Resent-To, Resent-Cc, Resent-Bcc, Resent-Sender, List-Archive, List-Help, List-ID, List-Owner, List-Post, List-Subscribe, List-Unsubscribe |
| `MessageIds` | Message-ID, In-Reply-To, References, Return-Path, Content-ID, Resent-Message-ID |
| `CommaList` | Keywords, Content-Language |
| `Date` | Date, Resent-Date |
| `ContentType` | Content-Type, Content-Disposition |
| `Received` | Received |
| `Raw` | every other field |
`Ignore` keeps a field with an empty value, and any form can be set for any name. `parse_headers()` stops after the header block of the message, for callers that need no MIME structure, such as DKIM verification. The limits bound the nesting depth (64 by default), the number of parts (10,000) and the levels of transfer-encoded nested messages that are decoded and parsed (3); content past a limit stays in the last part, which is flagged.
### Keep a message
```rust
use mail_parser::{Message, MessageParser};
let raw = b"Subject: moved\r\n\r\nbody".to_vec();
let message: Message<'static> = MessageParser::new().parse_owned(raw).expect("a message");
let subject = std::thread::spawn(move || message.subject().map(str::to_string))
.join()
.expect("the thread finished");
assert_eq!(subject.as_deref(), Some("moved"));
```
`parse_owned()` takes ownership of the input, and `into_owned()` copies a borrowed input; either way only the raw bytes are copied or moved, never the parsed values.
## Performance
mail-parser is compared with the most used email parsers in Rust ([mailparse](https://crates.io/crates/mailparse) 0.17.0) and C/C++ ([GMime](https://github.com/jstedfast/gmime) 3.2.15, [VMime](https://github.com/kisli/vmime) at commit 5b01911, [libEtPan!](https://github.com/dinhvh/libetpan) 1.10.1 and the `lib-mail` parser of [Dovecot](https://github.com/dovecot/core) 2.4.5). Every library parses one message per call, as a user would, and does the same work:
- `full`: parse, then read every leaf body decoded, with charset conversion to UTF-8 for text parts.
- `headers`: parse, then read the decoded Subject, the first From address, the Date as a timestamp and the Message-ID.
- `structure`: parse, then read the content type of every MIME part.
Nested messages are parsed in every workload, by the library itself when it returns them as bytes. Measured on an Apple M4 (Mac mini, macOS 26.6, rustc 1.98.1, Apple clang 21 with `-O3`), median of three runs.
How many times faster mail-parser is than each library (geometric mean over the corpora in the tables below, `structure` over those of the `headers` table, with the range):
| Workload | mailparse | GMime | VMime | libEtPan! | Dovecot |
|---|---:|---:|---:|---:|---:|
| `full` | 3.0x (1.3 to 4.6) | 31x (13 to 177) | 20x (7.8 to 80) | 15x (5.7 to 69) | 9.3x (4.4 to 24) |
| `headers` | 3.2x (2.6 to 5.5) | 14x (8.1 to 20) | 33x (13 to 131) | 19x (7.5 to 59) | 5.2x (2.5 to 16) |
| `structure` | 2.8x (2.1 to 5.3) | 14x (8.2 to 21) | 31x (11 to 117) | 17x (6.5 to 60) | 3.9x (2.0 to 16) |
Throughput in MiB/s (input size divided by time):
`full`:
| Corpus | mail-parser | mailparse | GMime | VMime | libEtPan! | Dovecot |
|---|---:|---:|---:|---:|---:|---:|
| Test suite (123 messages) | **1,597** | 558 | 75 | 20 | 93 | 153 |
| Enron (3,000 messages) | **2,420** | 942 | 65 | 70 | 96 | 366 |
| Large attachments | **12,747** | 2,781 | 960 | 380 | 185 | 522 |
| Newsletters | **2,942** | 638 | 113 | 299 | 257 | 353 |
| Long header blocks | **1,989** | 556 | 116 | 230 | 352 | 391 |
| Forwarded messages | **2,639** | 897 | 79 | 152 | 150 | 606 |
| 1 MB plain text | **17,171** | 13,732 | 97 | 2,212 | 2,796 | 856 |
`headers`:
| Corpus | mail-parser | mailparse | GMime | VMime | libEtPan! | Dovecot |
|---|---:|---:|---:|---:|---:|---:|
| Test suite (123 messages) | **2,089** | 687 | 122 | 16 | 176 | 514 |
| Enron (3,000 messages) | **2,638** | 873 | 132 | 137 | 266 | 480 |
| Large attachments | **80,868** | 31,344 | 4,662 | 1,471 | 1,362 | 5,205 |
| Newsletters | **25,529** | 4,671 | 2,178 | 643 | 522 | 3,074 |
| Long header blocks | **3,805** | 1,483 | 469 | 299 | 508 | 1,390 |
| Forwarded messages | **2,962** | 924 | 226 | 161 | 153 | 1,179 |
mail-parser does not decode a body until it is read, which is why `headers` and `structure` reach tens of GB/s on messages with large bodies. The benchmark, the equivalence check of the work each library does, and the tables for every workload and corpus (including LF input) are in [`benches/compare`](benches/compare/README.md); the results are in [`benches/compare/results`](benches/compare/results/summary.md).
## Feature flags
| Feature | Effect |
|---|---|
| `full_encoding` | Decodes the multi-byte character sets through `encoding_rs`: Shift_JIS, EUC-JP, ISO-2022-JP, Big5, GBK, GB18030, EUC-KR, windows-874, IBM866, x-mac-cyrillic and x-user-defined. Without it, text in these character sets is decoded as UTF-8 and reported as an unknown charset by `text_checked()`. |
| `serde` | `Serialize` for `Message` and the views; `Serialize` and `Deserialize` for `DateTime`, `HeaderName` and the Received enums. |
No feature is enabled by default. The minimum supported Rust version is 1.98.
## Testing, Fuzzing & Benchmarking ## Testing, Fuzzing & Benchmarking
To run the testsuite: To run the test suite, including the comparison of every message under `resources/eml/` with its expected JSON (in LF and CRLF form; a mismatch writes the parsed message to a `.failed` file next to it):
```bash ```bash
$ cargo test --all-features $ cargo test --all-features
``` ```
or, to run the testsuite with MIRI: and without optional features:
```bash ```bash
$ cargo +nightly miri test --all-features $ cargo test
``` ```
To fuzz the library with `cargo-fuzz`: To fuzz the parser (requires [cargo-fuzz](https://crates.io/crates/cargo-fuzz) and a nightly toolchain), optionally seeding the corpus with the test messages:
```bash ```bash
$ cargo +nightly fuzz run mail_parser $ cargo +nightly fuzz run parse -- -dict=fuzz/mime.dict -max_len=65536 -timeout=20
$ mkdir -p fuzz/corpus/parse
$ cargo +nightly fuzz run parse fuzz/corpus/parse resources/eml -- -dict=fuzz/mime.dict -max_len=65536 -timeout=20
``` ```
and, to run the benchmarks: The other targets are `limits` (parser limits), `fields` (header field parsers), `charsets` (charset and HTML decoders), `kernels` (every SIMD kernel against the scalar one) and `mbox` (mbox reader); `kernels`, `fields` and `charsets` use `-max_len=4096`, `limits` uses `-max_len=16384` and `mbox` uses `-max_len=65536`.
To run the unit tests under [Miri](https://github.com/rust-lang/miri) (the tests use fewer samples under Miri; each line takes about an hour): the span resolver and the charset decoders, the SIMD kernels natively and on x86-64 (SSE2 only, then AVX2), and the parser. Miri does not implement every NEON instruction used by encodify, so the parser tests use its portable code (`--cfg encodify_scalar`, encodify 1.0.1 or later):
```bash ```bash
$ cargo +nightly bench --all-features $ MIRIFLAGS=-Zmiri-disable-isolation cargo +nightly miri test --lib -- store:: decoders::charsets::
$ MIRIFLAGS=-Zmiri-disable-isolation cargo +nightly miri test --lib -- scan::
$ MIRIFLAGS=-Zmiri-disable-isolation cargo +nightly miri test --lib --target x86_64-unknown-linux-gnu -- scan::
$ MIRIFLAGS=-Zmiri-disable-isolation RUSTFLAGS="-Ctarget-feature=+avx2" cargo +nightly miri test --lib --target x86_64-unknown-linux-gnu -- scan::
$ MIRIFLAGS=-Zmiri-disable-isolation RUSTFLAGS="--cfg encodify_scalar" cargo +nightly miri test --lib -- parser:: --skip truncated_inputs_never_panic --skip mutated_inputs_never_panic
```
On macOS, the x86-64 runs also need `CC_x86_64_unknown_linux_gnu=clang AR_x86_64_unknown_linux_gnu=ar CFLAGS_x86_64_unknown_linux_gnu=-ffreestanding`.
The benchmarks read the Enron maildir and the Stalwart SMTP test messages, which `scripts/fetch-corpora.sh` downloads into `target/corpora` (or the directory named by `MAIL_PARSER_CORPORA`) and checks against `scripts/corpora.sha256`; a missing corpus is skipped with a warning. To download them and run the micro-benchmarks of the SIMD kernels and of string resolution:
```bash
$ scripts/fetch-corpora.sh enron stalwart
$ cargo bench --bench kernels
$ cargo bench --bench resolve
```
To reproduce the comparison with other parsers (requires a C/C++ toolchain, GLib and cmake; see [`benches/compare`](benches/compare/README.md)):
```bash
$ scripts/fetch-corpora.sh enron stalwart
$ cd benches/compare
$ vendor/build.sh
$ ./run.sh
``` ```
## Conformed RFCs ## Conformed RFCs
@@ -216,66 +456,74 @@ and, to run the benchmarks:
- [RFC 2152 - UTF-7 - A Mail-Safe Transformation Format of Unicode](https://datatracker.ietf.org/doc/html/rfc2152) - [RFC 2152 - UTF-7 - A Mail-Safe Transformation Format of Unicode](https://datatracker.ietf.org/doc/html/rfc2152)
- [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 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 2919 - List-Id: A Structured Field and Namespace for the Identification of Mailing Lists](https://datatracker.ietf.org/doc/html/rfc2919)
- [RFC 5321 - Simple Mail Transfer Protocol (Section 4.4, trace information)](https://datatracker.ietf.org/doc/html/rfc5321#section-4.4)
- [RFC 3848 - ESMTP and LMTP Transmission Types Registration](https://datatracker.ietf.org/doc/html/rfc3848)
- [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339) - [RFC 3339 - Date and Time on the Internet: Timestamps](https://datatracker.ietf.org/doc/html/rfc3339)
- [RFC 5233 - Sieve Email Filtering: Subaddress Extension](https://datatracker.ietf.org/doc/html/rfc5233)
- [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) - [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)
- [RFC 5957 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1) - [RFC 5256 - Internet Message Access Protocol - SORT and THREAD Extensions (Section 2.1)](https://datatracker.ietf.org/doc/html/rfc5256#section-2.1)
- [RFC 6854 - Group Syntax for Senders](https://datatracker.ietf.org/doc/html/rfc6854)
## Supported Character Sets ## Supported Character Sets
Every label of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/#names-and-labels) is recognized, along with the MIME names of the character sets below. As in that standard, text labeled US-ASCII or ISO-8859-1 is decoded as windows-1252, TIS-620 covers ISO-8859-11, and with the `full_encoding` feature the labels mapped to the replacement encoding (ISO-2022-KR, ISO-2022-CN, HZ-GB-2312) turn the text into a single U+FFFD.
- UTF-8 - UTF-8
- UTF-16, UTF-16BE, UTF-16LE - UTF-16, UTF-16BE, UTF-16LE
- UTF-7 - UTF-7
- US-ASCII - US-ASCII
- ISO-8859-1 - ISO-8859-1
- ISO-8859-2 - ISO-8859-2
- ISO-8859-3 - ISO-8859-3
- ISO-8859-4 - ISO-8859-4
- ISO-8859-5 - ISO-8859-5
- ISO-8859-6 - ISO-8859-6
- ISO-8859-7 - ISO-8859-7
- ISO-8859-8 - ISO-8859-8
- ISO-8859-9 - ISO-8859-9
- ISO-8859-10 - ISO-8859-10
- ISO-8859-13 - ISO-8859-13
- ISO-8859-14 - ISO-8859-14
- ISO-8859-15 - ISO-8859-15
- ISO-8859-16 - ISO-8859-16
- CP1250 - windows-1250
- CP1251 - windows-1251
- CP1252 - windows-1252
- CP1253 - windows-1253
- CP1254 - windows-1254
- CP1255 - windows-1255
- CP1256 - windows-1256
- CP1257 - windows-1257
- CP1258 - windows-1258
- KOI8-R - KOI8-R
- KOI8_U - KOI8-U
- MACINTOSH - Macintosh (Mac OS Roman)
- IBM850 - IBM850
- TIS-620 - TIS-620
Supported character sets via the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs): With the `full_encoding` feature, through [encoding_rs](https://crates.io/crates/encoding_rs):
- SHIFT_JIS - Shift_JIS
- BIG5 - EUC-JP
- EUC-JP - ISO-2022-JP
- EUC-KR - Big5
- GBK (GB2312)
- GB18030 - GB18030
- GBK - EUC-KR
- ISO-2022-JP - windows-874
- WINDOWS-874 - IBM866
- IBM-866 - x-mac-cyrillic
- x-user-defined
## License ## License
Licensed under either of Licensed under either of
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * Apache License, Version 2.0 ([LICENSES/Apache-2.0.txt](LICENSES/Apache-2.0.txt) or <https://www.apache.org/licenses/LICENSE-2.0>)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) * MIT license ([LICENSES/MIT.txt](LICENSES/MIT.txt) or <https://opensource.org/licenses/MIT>)
at your option. at your option.
## Copyright ## Copyright
Copyright (C) 2020-2022, Stalwart Labs Ltd. Copyright (C) 2020, Stalwart Labs LLC
+6
View File
@@ -0,0 +1,6 @@
/target/
/vendor/downloads/
/vendor/build/
/vendor/prefix/
/vendor/logs/
!/Cargo.lock
+630
View File
@@ -0,0 +1,630 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "alloca"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4"
dependencies = [
"cc",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cc"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "charset"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1f927b07c74ba84c7e5fe4db2baeb3e996ab2688992e39ac68ce3220a677c7e"
dependencies = [
"base64",
"encoding_rs",
]
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstyle",
"clap_lex",
]
[[package]]
name = "clap_lex"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "criterion"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3"
dependencies = [
"alloca",
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
"itertools",
"num-traits",
"oorandom",
"page_size",
"regex",
"serde",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea"
dependencies = [
"cast",
"itertools",
]
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "either"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
[[package]]
name = "encodify"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fda1e5c788c2b59096e152ad1a76ce72a2ab80c75985eb94ca82de0b6555db7"
dependencies = [
"memchr",
"simdutf8",
]
[[package]]
name = "encoding_rs"
version = "0.8.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679"
dependencies = [
"cfg-if",
"core_detect",
"multiversion_no_op",
"rustversion",
"scopeguard",
"simdutf8",
]
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"zerocopy",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hashify"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd1246c0e5493286aeb2dde35b1f4eb9c4ce00e628641210a5e553fc001a1f26"
dependencies = [
"indexmap",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "hashify"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66f5a65bf7824ada2de4a2cf9fa0981dabffc5392bb8550767c3c3d71ed52e4d"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "mail-parser"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ec00bda90c6e645a54506c630c2820cd6b1890cfd2b0a169b50f74b2b8c7c86"
dependencies = [
"encoding_rs",
"hashify 0.2.9",
]
[[package]]
name = "mail-parser"
version = "1.0.0"
dependencies = [
"encodify",
"encoding_rs",
"hashify 0.3.1",
"memchr",
"simdutf8",
]
[[package]]
name = "mail-parser-compare"
version = "0.1.0"
dependencies = [
"cc",
"criterion",
"mail-parser 0.11.9",
"mail-parser 1.0.0",
"mailparse",
"pkg-config",
"serde_json",
]
[[package]]
name = "mailparse"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8469955699e572455f8e1a40689e07ab309911d659632f65062598192254c091"
dependencies = [
"charset",
"data-encoding",
"quoted_printable",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "page_size"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "quoted_printable"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972"
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zerocopy"
version = "0.8.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+40
View File
@@ -0,0 +1,40 @@
[package]
name = "mail-parser-compare"
description = "Throughput comparison of mail-parser with other Rust and C/C++ email parsers"
version = "0.1.0"
edition = "2024"
rust-version = "1.98"
publish = false
[workspace]
[dependencies]
mail-parser = { path = "../..", features = ["full_encoding"] }
mail-parser-011 = { package = "mail-parser", version = "=0.11.9", features = ["full_encoding"] }
mailparse = "=0.17.0"
serde_json = "1.0"
[dev-dependencies]
criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support"] }
[build-dependencies]
cc = "1"
pkg-config = "0.3"
[[bench]]
name = "compare"
harness = false
[lints.rust]
rust_2018_idioms = { level = "deny", priority = -1 }
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "deny"
[lints.clippy]
unwrap_used = "deny"
[profile.release]
debug = "line-tables-only"
[profile.bench]
debug = "line-tables-only"
+383
View File
@@ -0,0 +1,383 @@
# mail-parser compared with other email parsers
This crate measures the throughput of mail-parser 1.0 and of other Rust and
C/C++ email parsers on the same messages, with every library doing the same
work. It is a standalone crate (its own `[workspace]`, never published) that
depends on the mail-parser in this repository by path and builds the C and
C++ libraries from their release sources.
Results measured on a Mac mini with an Apple M4 on 2026-09-28 are in
[`results/summary.md`](results/summary.md) (throughput, median of three
runs) and [`results/check.md`](results/check.md) (equivalence check).
mail-parser 1.0 is the fastest implementation in every workload and corpus.
## Requirements
- macOS or Linux, Rust 1.98 or later, a C and C++ toolchain (Apple clang on
macOS), `make`, `curl`, `tar` with xz support, `perl`.
- GLib 2.x headers and libraries (GMime needs them; the C shims also use
GLib's UTF-8 validator). On macOS: `brew install glib`. On Linux: the GLib
development package; `build.rs` and `vendor/build.sh` find it with
`pkg-config`.
- CMake (VMime). On macOS: `brew install cmake`.
- OpenSSL headers, only because Dovecot's `configure` refuses to run without
them; nothing from OpenSSL is compiled into or linked with the benchmark.
On macOS `vendor/build.sh` uses Homebrew's `openssl@3`; set
`OPENSSL_PREFIX` to use another installation.
- About 3 GB of disk for the Enron corpus (archive and extracted maildir).
Only macOS (Apple silicon, Homebrew) has been verified. The Linux paths are
there to make a port cheap, not tested.
## Run the comparison
All commands run from this directory (`benches/compare`).
1. Fetch the external corpora (Enron and the Stalwart SMTP test messages)
into the repository's `target/corpora`, or into `$MAIL_PARSER_CORPORA`:
```sh
../../scripts/fetch-corpora.sh enron stalwart
```
2. Download, verify and build the C/C++ libraries into `vendor/prefix/`
(a few minutes; logs in `vendor/logs/`):
```sh
vendor/build.sh
```
The script checks the SHA-256 of each source archive and stops on a
mismatch. It takes `all` (default), `gmime`, `vmime`, `libetpan` or
`dovecot`.
3. Build, check and measure:
```sh
./run.sh
```
`run.sh` builds the crate and the benchmark, runs the equivalence check
(`results/check.md`), measures three runs of the whole matrix (231
benchmarks, about 20 minutes per run) and writes the median of the runs to
`results/summary.md`. `RUNS=1 ./run.sh` measures once.
Close other applications first: the numbers are only as good as the machine
is idle.
### Individual steps
```sh
cargo build --release --bins
cargo bench --no-run > target/bench-build.log 2>&1
target/release/check --out results/check.md
target/release/check --corpus enron-crlf --workload full --examples 10
./measure.sh 1
./measure.sh 1 full-a full-b
cargo bench --bench compare -- '^headers/testsuite-crlf/'
target/release/summary target/compare-runs/r*/criterion --out results/summary.md
```
`measure.sh <run> [session...]` measures one run of the matrix as six
sessions of a few minutes each (`structure-a`, `structure-b`, `headers-a`,
`headers-b`, `full-a`, `full-b`: one workload and half of the corpora each)
and copies each session's criterion results to
`target/compare-runs/r<run>/criterion`. It logs the busiest processes every
10 seconds next to each session's output, and stops before the next session
when `target/compare-runs/STOP` exists.
`summary` reads one or more criterion directories (default
`target/criterion`) and prints the median MiB/s of every implementation,
workload and corpus, the speed of mail-parser 1.0 divided by the speed of
each other implementation (`1.0 / x`: above 1 means mail-parser 1.0 is
faster) and, with several runs, the spread of each cell ((max - min) /
median). `--exclude <implementation>` leaves an implementation out of the
table; `check` takes the same option.
Benchmark ids are `<workload>/<corpus>/<implementation>`, so criterion's
filter selects any subset. Criterion settings: 0.5 s warm-up, 3 s
measurement, 30 samples, throughput in bytes of the corpus.
### Environment variables
| Variable | Used by | Effect |
|---|---|---|
| `MAIL_PARSER_CORPORA` | corpus loader | directory of the external corpora (default: `target/corpora` of the repository) |
| `RUNS` | `run.sh` | number of measured runs (default 3) |
| `EXCLUDE` | `run.sh` | implementations left out of `check.md` and `summary.md`, separated by spaces |
| `BUILD_WRAP` | all scripts | command that wraps every build step, for example a machine-wide build lock; the step also gets a time limit (`BUILD_TIME_LIMIT`, default 10800 s) |
| `BENCH_LOCK` | `measure.sh` | path of a [bench-lock](#machine-wide-locking)-style wrapper for the measurements (`<wrapper> <label> <command>`); flagged sessions are rerun (`ATTEMPTS`, default 5, `PAUSE` seconds apart, default 240) |
| `GLIB_PREFIX`, `GETTEXT_PREFIX`, `HOMEBREW_PREFIX`, `OPENSSL_PREFIX` | `build.rs`, `vendor/build.sh` | library locations on macOS (default: Homebrew's `opt` links) |
| `CC`, `CXX`, `JOBS` | `vendor/build.sh`, `build.rs` | compilers (default `/usr/bin/clang` and `/usr/bin/clang++` on macOS, `cc` and `c++` elsewhere) and `make -j` |
### Machine-wide locking
The published numbers were measured on a machine shared with other work,
through two wrappers: one that holds builds back while a measurement runs
(`BUILD_WRAP`), and one that takes a machine-wide lock, waits until the CPU
is idle, samples the idle time during the run and records a session as noisy
in `state/noisy.log` next to itself when the machine got busy (`BENCH_LOCK`).
Without these variables the scripts run every command directly.
## Implementations
| Id | Library | Version | Language | Source |
|---|---|---|---|---|
| `mail-parser-1.0` | mail-parser | 1.0.0 (this repository, feature `full_encoding`) | Rust | `../..` |
| `mail-parser-0.11` | mail-parser | 0.11.9 (feature `full_encoding`) | Rust | crates.io |
| `mailparse` | mailparse | 0.17.0 | Rust | crates.io |
| `gmime` | GMime | 3.2.15 (2024-06-20, latest release) | C (GLib) | release tarball |
| `vmime` | VMime | master at `5b0191136f84c177b737c9cf9aa7cf59d1c65ef1` (2026-03-24) | C++ | GitHub archive of that commit |
| `libetpan` | libEtPan! | 1.10.1 (2026-06-14, latest release) | C | GitHub tag archive |
| `dovecot` | Dovecot lib-mail, lib-charset and lib | 2.4.5 (2026-08-28, latest release) | C | dovecot.org release tarball |
mail-parser 0.11 is part of the harness to measure the rewrite against the
previous release; the published tables leave it out.
### Choice of libraries
Rust crates, from the crates.io API on 2026-09-26 (total downloads,
downloads in the last 90 days, crates depending on it):
| Crate | Version | Total | Last 90 days | Reverse deps | Compared |
|---|---|---:|---:|---:|---|
| mailparse | 0.17.0 (2026-09-06) | 14,169,109 | 3,808,629 | 106 | yes |
| mail-parser | 0.11.9 | 3,820,512 | 1,531,183 | 143 | yes |
| eml-parser | 0.1.5 (2025-11-30) | 1,279,717 | 224,356 | 2 | no |
| email (rust-email) | 0.0.21 (2020-02-16) | 1,112,663 | 77,620 | 8 | no |
| email-format | 0.8.1 (2022-07-27) | 67,242 | 603 | 3 | no |
| melib | 0.8.13 (2026-01-05) | 35,027 | 362 | 1 | no |
| rustyknife | 0.2.11 (2021-01-04) | 30,215 | 493 | 3 | no |
| email-parser | 0.5.0 (2020-12-17) | 24,057 | 499 | 2 | no |
| eml-codec | 0.4.1 (2026-08-18) | 4,411 | 153 | 0 | no |
| mailparsing (KumoMTA) | not published on crates.io | | | | no |
- mailparse is the most used Rust email parser by a wide margin.
- eml-parser's downloads come from one dependent, Nushell's `from eml`
plugin. It does no MIME work (no part structure, no transfer or charset
decoding of bodies, no Date or Message-ID parsing) and only takes a UTF-8
`String`, so it cannot run any of the three workloads.
- email (rust-email) has had no release since 2020; most of its downloads
come through the builder of the old lettre_email 0.9.
- The others have under 1,000 downloads in the last 90 days.
C and C++ libraries:
- GMime is the most widely used C MIME library (notmuch, Balsa, Pan).
- VMime is the maintained C++ mail library. Its only tagged release, v0.9.2,
is from 2017 and development continues on master, so the benchmark pins a
master commit.
- libEtPan! is maintained (1.10 and 1.10.1 were released in 2026) and used
by Claws Mail.
- Dovecot's lib-mail is the MIME parser of the most deployed IMAP server:
`message-parser` (streaming MIME structure), `message-header-parser`,
`message-address`, `message-date`, `message-id`, `message-header-decode`,
`rfc822-parser`, `rfc2231-parser` and `message-decoder` (transfer decoding
plus conversion to UTF-8 through lib-charset and iconv). It is not a
standalone library, but its static convenience libraries build on their
own from the release tarball.
- mimetic (C++) is not compared: its last release, 0.9.8, is from 2014.
- Not considered further: KMime (needs Qt), mailio (needs Boost), POCO's
`MailMessage` (a small part of a large framework), and the MIME parsers
built into Cyrus, rspamd, Postfix or Thunderbird (not standalone
libraries).
### Build of the C and C++ libraries
`vendor/build.sh` builds each library from its source archive, static, at
`-O3`, into `vendor/prefix/<library>`; nothing is installed elsewhere.
| Library | Build | Flags |
|---|---|---|
| GMime 3.2.15 | release `configure`, `make` of `util` and `gmime` | `CFLAGS=-O3`, `--disable-crypto --without-libidn --enable-introspection=no --enable-vala=no`; `GLIB_CFLAGS`/`GLIB_LIBS` given explicitly (Homebrew GLib on macOS, `pkg-config` elsewhere), `ZLIB_LIBS=-lz`; charset conversion through the system iconv |
| VMime master | CMake (Unix Makefiles), Release | `CMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG"`, messaging, TLS and SASL off, `VMIME_CHARSETCONV_LIB=iconv` |
| libEtPan! 1.10.1 | the tag has no `configure`; `build-mac/autogen-result.tar.gz` (the autogen output its Xcode build uses) provides one, run only to generate `config.h` (its version string says 1.6: the archive is stale, the sources are 1.10.1); the 22 IMF, MIME and data-type sources the parser needs are compiled directly into `libetpan-mime.a`, as the Xcode project does | `-O3`, iconv on, no SSL, SASL, DB, curl, expat or zlib |
| Dovecot 2.4.5 | release `configure`, then `make` of the `liblib.la`, `libcharset.la` and `libmail.la` targets only, installed as `libdovecot-{lib,charset,mail}.a` with their headers and `config.h` | `CFLAGS=-O3`, `--enable-static --disable-shared --without-shared-libs`, every optional dependency off; `am_cv_func_iconv_works=yes` (gnulib's iconv self-test rejects macOS's iconv, which the other C libraries use anyway; without the override lib-charset would convert nothing); OpenSSL include and library paths for `configure`'s checks only; `ZLIB_CFLAGS=" " ZLIB_LIBS=-lz` |
The Dovecot archive's SHA-256 equals Homebrew's formula checksum, and its
GPG signature (`dovecot-2.4.5.tar.gz.sig` on dovecot.org) verifies with the
Dovecot CE key `EF0882079FD4ED32BF8B23B2A1B09EF84EDC5219`.
The shims in `shim/` (`gmime.c`, `vmime.cpp`, `libetpan.c`, `dovecot.c`,
and `utf8.c`) are compiled by `build.rs` with the `cc` crate at `-O3`
(`-std=gnu11`, `-std=c++17`). The Rust code uses the release profile
(opt-level 3). `Cargo.lock` pins mailparse 0.17.0 (charset 0.1.5), mail-parser
0.11.9, criterion 0.8.2 and cc 1.5.1. `src/ffi.rs` is the only module with
`unsafe`.
## Corpora
Eleven corpora, 17.8 MiB and 3,292 messages in total:
| Corpus | Messages | Content |
|---|---:|---|
| `testsuite-lf`, `testsuite-crlf` | 123 | the RFC, legacy, third-party and malformed test messages of `resources/eml`, the Stalwart SMTP test messages and `resources/sieve`, with LF and with CRLF line endings |
| `enron-crlf` | 3,000 | the first 20 messages of each mailbox of the Enron corpus (CMU, 2015-05-07 release) |
| `attachments-crlf`, `attachments-lf` | 3 | generated: quoted-printable text and HTML alternatives with large base64 PDF and PNG attachments |
| `newsletter-crlf`, `newsletter-lf` | 6 | generated: 8bit text and quoted-printable HTML with an inline base64 image (`multipart/related`) |
| `modern-headers-crlf` | 20 | generated: long header blocks (Received chains, ARC, DKIM, List-Unsubscribe) over short quoted-printable alternatives |
| `forwarded-crlf` | 6 | generated: 1 to 6 levels of forwarded `message/rfc822` |
| `dashes-crlf` | 1 | generated: three 200 KB parts whose bodies contain lines that start with the boundary |
| `plain-large-crlf` | 1 | generated: one 1 MB `text/plain; charset=utf-8` body |
The generated corpora come from a fixed seed (`src/corpus/synthetic.rs`), so
every machine gets the same bytes. `check.md` lists the size and an FNV-1a
digest of every corpus: equal digests mean equal input. `check` and the
benchmark warn when a corpus cannot be loaded.
## Workloads
Each benchmark iteration handles every message of a corpus. Each message is
parsed, read and freed as a user would, with no state kept between messages
besides one-time library initialization (`g_mime_init`, Dovecot's
`lib_init`). Every value read feeds a digest (lengths, timestamps;
`black_box` in Rust), and C/C++ calls go through one function per workload
taking `(pointer, length)`.
1. `structure`: parse, then walk every MIME part, nested messages included,
and read its content type and subtype.
2. `headers`: parse, then read the root message's decoded Subject, the first
From mailbox (display name and address; groups flattened), the Date as a
Unix timestamp and the Message-ID (without angle brackets); then walk the
parts, nested messages included.
3. `full`: parse, then read every leaf body decoded: transfer decoding for
every leaf and charset conversion to UTF-8 for `text/*` leaves, ending with
text the caller can use as UTF-8.
Nested messages are walked the same way in all three workloads. mail-parser
parses `message/rfc822` and `message/global` parts during `parse`. When a
library hands such a body back as bytes, the shim transfer-decodes the bytes
and parses them again with the same library (up to 8 levels). In `headers`
the walk reads nothing: it only makes each library parse what mail-parser's
`parse` parses. Each implementation has one tree walk shared by the three
workloads.
UTF-8 in `full`: mail-parser's `text()` validates UTF-8 even when no
conversion is needed. A C library that returns the raw bytes of a UTF-8 (or
undeclared) text body without checking them gives the caller bytes that may
not be UTF-8, so its shim validates them as a user would, with GLib's
`g_utf8_validate_len` (`shim/utf8.c`). This applies to libEtPan! (charset
UTF-8, or a failed `charconv_buffer`), VMime (charset UTF-8, or a failed
`charset::convert`) and GMime (no charset parameter: `g_mime_text_part_get_text`
then returns the bytes unconverted). GMime with a charset converts through
iconv, Dovecot's `message-decoder` validates UTF-8 itself (U+FFFD for
invalid sequences), mailparse decodes through `charset` and encoding_rs, and
mail-parser 0.11 builds `String`s: none of these needs a separate check.
### Calls per implementation
| Implementation | Parse | structure | headers | full |
|---|---|---|---|---|
| mail-parser 1.0 | `MessageParser::default().parse(raw)` | `Message::parts()` (every part of every nested message), `content_type()`, `ctype()`, `subtype()` | `subject()`, `from()?.first()` with `name()`, `address()`; `date()?.to_timestamp()`; `message_id()` | `PartKind::Text`/`Html`: `text()`; `Binary`/`InlineBinary`: `decoded()` |
| mail-parser 0.11 | `MessageParser::default().parse(raw)` (decodes every body) | `message.parts` of the root and of every `PartType::Message`, `MimeHeaders::content_type()` | the same getters as 1.0 | the already decoded `PartType::Text`/`Html`/`Binary`/`InlineBinary` bodies |
| mailparse | `parse_mail(raw)` | `subparts` tree, `ctype.mimetype` split at `/`; nested messages are leaves: `get_body_raw()`, then `parse_mail` again | `headers.get_first_value("Subject")`, `addrparse_header(get_first_header("From"))` first mailbox, `dateparse(get_first_value("Date"))`, `msgidparse(get_first_value("Message-ID"))` first id | `text/*`: `get_body()`; others: `get_body_raw()` |
| GMime | `g_mime_stream_mem_new_with_buffer`, `g_mime_parser_new_with_stream`, `g_mime_parser_construct_message` | `g_mime_message_get_mime_part`, `GMimeMultipart` children, `g_mime_message_part_get_message`; `g_mime_object_get_content_type`, `g_mime_content_type_get_media_type`/`_subtype` | `g_mime_message_get_subject`, `g_mime_message_get_from` first mailbox (`internet_address_get_name`, `internet_address_mailbox_get_addr`), `g_mime_message_get_date` with `g_date_time_to_unix`, `g_mime_message_get_message_id` | `GMimeTextPart`: `g_mime_text_part_get_text`; other `GMimePart`: `g_mime_data_wrapper_write_to_stream` into a memory stream; transfer-encoded `message/rfc822` (kept as leaves): decoded, then parsed from the memory stream |
| VMime | `vmime::message::parse(std::string)` | `body::getContentType()` over `getPartAt()`; nested messages are leaves: `contentHandler::extract()`, then parsed as a new `vmime::message` | `findField` for Subject (`text::getConvertedText(utf-8)`), From (`mailbox`: `getName().getConvertedText`, `getEmail().toString()`), Date (`datetime` to a timestamp), Message-ID (`messageId::getId()`) | `contentHandler::extract()`; `text/*`: `charset::convert(..., utf-8)` unless the charset is UTF-8 |
| libEtPan! | `mailmime_parse(raw, len, &index, &mime)` | `mailmime` tree (`MAILMIME_MULTIPLE` children, `MAILMIME_MESSAGE` nested root), `mm_content_type` type and subtype; transfer-encoded nested messages (kept as leaves): `mailmime_part_parse`, then `mailmime_parse` again | root `mm_fields`: Subject and the From display name through `mailmime_encoded_phrase_parse(..., "utf-8")`, first `mailimf_mailbox`, `mailimf_date_time` to a timestamp, `mid_value` | `MAILMIME_SINGLE`: `mailmime_part_parse`; `text/*`: `charconv_buffer` to UTF-8 unless the charset is UTF-8 |
| Dovecot | `i_stream_create_from_data`, `message_parser_init`, `message_parser_parse_next_block` until the end, `message_parser_deinit` (gives the `message_part` tree); `MESSAGE_PARSER_FLAG_SKIP_BODY_BLOCK` in `structure` and `headers` | `Content-Type` header blocks through `rfc822_parse_content_type`; the `message_part` tree (`children`, `next`) | root header blocks: Subject through `message_header_decode_utf8`, From through `message_address_parse` (display name through `message_header_decode_utf8`), `message_date_parse`, `message_id_get_next` | `message_decoder_init(NULL, MESSAGE_DECODER_FLAG_RETURN_BINARY)` fed every body block plus the `Content-Type` and `Content-Transfer-Encoding` header blocks |
## Equivalence check
`check` runs every implementation, workload and corpus once, in one worker
process per implementation, workload and corpus (a worker that crashes is
restarted after the message that crashed it, and the crash is counted), with
`catch_unwind` around every Rust call. For each cell it prints messages
parsed and rejected, panics, crashes, and the counts the workload produced
(messages walked, parts, leaves, text leaves, decoded bytes, headers found),
each with its difference from mail-parser 1.0 and the number of messages
whose counts differ. `--examples N` lists the first N differing messages of
each cell. The check shows whether the libraries do comparable work; it does
not judge their correctness.
Findings (`results/check.md`):
- No panic and no crash in any implementation, workload or corpus.
- Rejected messages, out of 123 in each test suite: mailparse rejects
`malformed/019.eml` (a header line `Fro :...` with a space before the
colon) and GMime rejects `malformed/023.eml` (its first line is not a
header field). Every other library parses every message.
- Enron and the generated corpora give identical message, part and leaf
counts for every implementation in all three workloads (`forwarded-crlf`:
27 messages, 93 parts, 39 leaves everywhere), and decoded byte counts
equal to 0.01%, except `dashes-crlf` and quoted-printable in LF (below).
- `dashes-crlf`: its bodies contain lines `--<boundary>x not a delimiter`.
mailparse and Dovecot match boundaries by prefix and split the message
into 1,064 leaves (1,402 decoded bytes instead of 611,851); mail-parser
0.11 finds the 3 parts but also decodes only 1,402 bytes. mail-parser 1.0,
GMime, VMime and libEtPan! follow RFC 2046 (a delimiter line is the
boundary plus optional whitespace) and decode all 611,851 bytes. The
`dashes-crlf` cells of mailparse and Dovecot measure different, and in
`full` much less, work: they are not comparable.
- `headers`: all libraries find the same Subject, From, Date and Message-ID
on the generated corpora. Enron: GMime finds no From mailbox in 327
messages whose local part is not a valid dot-atom (`k..allen@enron.com`,
`.hall@enron.com`), which the others accept. Test suites: mailparse finds
3 fewer From mailboxes (`addrparse` rejects From fields without a domain)
and 1 fewer Subject and Message-ID (the rejected message); mailparse and
VMime return a date for `Date: Whenever`, mail-parser 1.0 does not;
Dovecot finds 3 fewer Message-IDs (`message_id_get_next` requires an `@`)
and one fewer Date.
- `structure`, test suites: part counts within 12 of 479. The differences
come from malformed messages recovered differently, VMime ignoring the
`multipart/digest` default type (digest parts stay text leaves, 5 fewer
messages), and Dovecot parsing a base64-encoded `message/rfc822` body as
if it were not encoded (its parser ignores the transfer encoding of nested
messages).
- `full`, test suites: decoded bytes within 2% of mail-parser 1.0 for every
library except Dovecot (-6%). The differences come from invalid or
undeclared 8-bit text (mail-parser writes U+FFFD, 3 bytes, per invalid
sequence; iconv-based conversions substitute or drop), malformed messages
and digests recovered differently, and for Dovecot mostly from
`x-uuencode` bodies: `message-decoder` skips a body whose transfer
encoding it does not know, mail-parser decodes uuencode.
- Quoted-printable in the LF corpora: mailparse, libEtPan! and Dovecot write
CRLF for the line breaks of quoted-printable bodies (the canonical form),
so they decode 0.04% (`attachments-lf`) to 0.76% (`newsletter-lf`) more
bytes.
- No corpus contains `message/global`. Dovecot's parser treats it as a leaf
(only `message/rfc822` is parsed as nested) and its shim does not parse it
again.
## Caveats
- GMime, VMime and libEtPan! keep transfer-encoded (base64 or
quoted-printable) `message/rfc822` parts as leaves; the shims decode and
parse them, as mail-parser does during `parse`. Dovecot parses nested
messages without transfer-decoding them.
- mail-parser 0.11 decodes every body during `parse`, whatever the workload
reads.
- The C/C++ digest uses `strlen` on returned C strings (subject, names,
GMime's decoded text), a cost the Rust implementations do not have; it is
small next to parsing.
- GMime copies the input into its memory stream, VMime into a
`std::string`, and libEtPan! each 7bit or 8bit body into a new buffer
(`mailmime_part_parse`), as their users do; these copies are part of the
measured time. Dovecot and the Rust libraries read the input in place.
- Dovecot's `message-decoder` is fed only the two header fields it needs in
`full`. Feeding every header block would add RFC 2047 decoding of every
header, which no other implementation does in `full`.
- Throughput is the corpus size divided by the time to handle it, whether
or not a workload reads every byte. In `structure` and `headers` no
library needs to read the single 1 MB body of `plain-large-crlf`, so
those cells measure one header parse and reach hundreds of GB/s; in
`full` they measure one scan or validation of that body.
- The numbers come from one machine (Apple M4, macOS). Other CPUs, and GLib
or iconv builds on other systems, can change the ratios.
## Layout
| Path | Content |
|---|---|
| `vendor/build.sh` | download, verify, build and install GMime, VMime, libEtPan! and Dovecot lib-mail; `vendor/downloads/`, `vendor/build/`, `vendor/prefix/` and `vendor/logs/` are generated |
| `shim/` | the C and C++ workload functions, one per library and workload, `tally.h` (the counters shared with Rust) and `utf8.c` (UTF-8 validation shared by the C/C++ shims) |
| `build.rs` | compiles the shims and links the libraries |
| `src/corpus/` | the corpus loader and the generated corpora |
| `src/impls/` | the Rust implementations of the workloads |
| `src/ffi.rs` | calls into the shims (the only `unsafe` code) |
| `src/tally.rs`, `src/workload.rs` | digest and counters, workload and implementation lists |
| `src/bin/check/` | equivalence check |
| `src/bin/summary.rs` | criterion results to a markdown table |
| `benches/compare.rs` | the criterion benchmark |
| `run.sh` | build, check, measure and summarize |
| `measure.sh` | one run of the matrix as six short sessions |
| `results/` | published results |
+40
View File
@@ -0,0 +1,40 @@
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use mail_parser_compare::{
bench_corpora,
workload::{Implementation, Parsers, Workload},
};
use std::{hint::black_box, time::Duration};
const WARM_UP: Duration = Duration::from_millis(500);
const MEASUREMENT: Duration = Duration::from_secs(3);
const SAMPLES: usize = 30;
fn compare(c: &mut Criterion) {
let parsers = Parsers::default();
for corpus in bench_corpora() {
for workload in Workload::ALL {
let mut group = c.benchmark_group(format!("{}/{}", workload.name(), corpus.name));
group.throughput(Throughput::Bytes(corpus.total_bytes()));
for implementation in Implementation::ALL {
group.bench_function(implementation.name(), |b| {
b.iter(|| parsers.run_corpus(implementation, workload, black_box(corpus)))
});
}
group.finish();
}
}
}
fn config() -> Criterion {
Criterion::default()
.warm_up_time(WARM_UP)
.measurement_time(MEASUREMENT)
.sample_size(SAMPLES)
}
criterion_group! {
name = benches;
config = config();
targets = compare
}
criterion_main!(benches);
+250
View File
@@ -0,0 +1,250 @@
use std::{
env,
path::{Path, PathBuf},
};
const OPT_LEVEL: u32 = 3;
const APPLE_CC: &str = "/usr/bin/clang";
const APPLE_CXX: &str = "/usr/bin/clang++";
const HOMEBREW_PREFIXES: [&str; 2] = ["/opt/homebrew", "/usr/local"];
const GLIB_MODULES: [&str; 3] = ["gio-2.0", "gobject-2.0", "gmodule-2.0"];
const APPLE_DYLIBS: [&str; 7] = [
"gio-2.0",
"gobject-2.0",
"gmodule-2.0",
"glib-2.0",
"intl",
"iconv",
"z",
];
const LINUX_DYLIBS: [&str; 2] = ["z", "m"];
const SHIMS: [&str; 6] = [
"tally.h",
"utf8.c",
"gmime.c",
"vmime.cpp",
"libetpan.c",
"dovecot.c",
];
struct Library {
name: &'static str,
archive: &'static str,
static_lib: &'static str,
}
const LIBRARIES: [Library; 6] = [
Library {
name: "gmime",
archive: "lib/libgmime-3.0.a",
static_lib: "gmime-3.0",
},
Library {
name: "vmime",
archive: "lib/libvmime.a",
static_lib: "vmime",
},
Library {
name: "libetpan",
archive: "lib/libetpan-mime.a",
static_lib: "etpan-mime",
},
Library {
name: "dovecot",
archive: "lib/libdovecot-mail.a",
static_lib: "dovecot-mail",
},
Library {
name: "dovecot",
archive: "lib/libdovecot-charset.a",
static_lib: "dovecot-charset",
},
Library {
name: "dovecot",
archive: "lib/libdovecot-lib.a",
static_lib: "dovecot-lib",
},
];
#[derive(Default)]
struct Glib {
includes: Vec<PathBuf>,
link_paths: Vec<PathBuf>,
libs: Vec<String>,
}
impl Glib {
fn link(&self) {
for path in &self.link_paths {
println!("cargo:rustc-link-search=native={}", path.display());
}
for lib in &self.libs {
println!("cargo:rustc-link-lib=dylib={lib}");
}
}
}
struct Toolchain {
apple: bool,
glib: Glib,
}
impl Toolchain {
fn detect() -> Toolchain {
let apple = env::var("CARGO_CFG_TARGET_VENDOR").is_ok_and(|vendor| vendor == "apple");
for variable in ["GLIB_PREFIX", "GETTEXT_PREFIX", "HOMEBREW_PREFIX"] {
println!("cargo:rerun-if-env-changed={variable}");
}
let glib = if apple {
homebrew_glib()
} else {
pkg_config_glib()
};
Toolchain { apple, glib }
}
fn c(&self, shim: &Path) -> cc::Build {
let mut build = cc::Build::new();
if self.apple && env::var_os("CC").is_none() {
build.compiler(APPLE_CC);
}
build
.opt_level(OPT_LEVEL)
.flag("-std=gnu11")
.include(shim)
.warnings(false);
build
}
fn cpp(&self, shim: &Path) -> cc::Build {
let mut build = cc::Build::new();
build.cpp(true);
if self.apple && env::var_os("CXX").is_none() {
build.compiler(APPLE_CXX);
}
build
.opt_level(OPT_LEVEL)
.std("c++17")
.include(shim)
.warnings(false);
build
}
fn with_glib(&self, mut build: cc::Build) -> cc::Build {
build.includes(&self.glib.includes);
build
}
}
fn homebrew_prefix() -> PathBuf {
env::var_os("HOMEBREW_PREFIX").map_or_else(
|| {
HOMEBREW_PREFIXES
.iter()
.map(PathBuf::from)
.find(|prefix| prefix.join("opt/glib").is_dir())
.unwrap_or_else(|| PathBuf::from(HOMEBREW_PREFIXES[0]))
},
PathBuf::from,
)
}
fn homebrew_glib() -> Glib {
let homebrew = homebrew_prefix();
let glib = env::var_os("GLIB_PREFIX").map_or_else(|| homebrew.join("opt/glib"), PathBuf::from);
let gettext =
env::var_os("GETTEXT_PREFIX").map_or_else(|| homebrew.join("opt/gettext"), PathBuf::from);
assert!(
glib.join("include/glib-2.0/glib.h").is_file(),
"GLib not found in {} (brew install glib, or set GLIB_PREFIX)",
glib.display()
);
Glib {
includes: vec![
glib.join("include/glib-2.0"),
glib.join("lib/glib-2.0/include"),
gettext.join("include"),
],
link_paths: vec![glib.join("lib"), gettext.join("lib")],
libs: APPLE_DYLIBS.iter().map(ToString::to_string).collect(),
}
}
fn pkg_config_glib() -> Glib {
let mut glib = Glib::default();
for module in GLIB_MODULES {
let library = pkg_config::Config::new()
.cargo_metadata(false)
.probe(module)
.unwrap_or_else(|error| panic!("pkg-config cannot find {module}: {error}"));
glib.includes.extend(library.include_paths);
glib.link_paths.extend(library.link_paths);
glib.libs.extend(library.libs);
}
glib.libs
.extend(LINUX_DYLIBS.iter().map(ToString::to_string));
glib
}
fn main() {
let manifest =
PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"));
let prefix = manifest.join("vendor").join("prefix");
let shim = manifest.join("shim");
for library in &LIBRARIES {
let archive = prefix.join(library.name).join(library.archive);
assert!(
archive.is_file(),
"{} is missing: run vendor/build.sh first",
archive.display()
);
println!("cargo:rerun-if-changed={}", archive.display());
}
for file in SHIMS {
println!("cargo:rerun-if-changed={}", shim.join(file).display());
}
let toolchain = Toolchain::detect();
toolchain
.with_glib(toolchain.c(&shim))
.file(shim.join("utf8.c"))
.compile("cmp_utf8");
toolchain
.with_glib(toolchain.c(&shim))
.include(prefix.join("gmime/include/gmime-3.0"))
.file(shim.join("gmime.c"))
.compile("cmp_gmime");
toolchain
.c(&shim)
.include(prefix.join("libetpan/include"))
.flag("-iquote")
.flag(
prefix
.join("libetpan/include/libetpan")
.display()
.to_string(),
)
.file(shim.join("libetpan.c"))
.compile("cmp_libetpan");
toolchain
.c(&shim)
.include(prefix.join("dovecot/include"))
.define("HAVE_CONFIG_H", None)
.file(shim.join("dovecot.c"))
.compile("cmp_dovecot");
toolchain
.cpp(&shim)
.include(prefix.join("vmime/include"))
.define("VMIME_STATIC", None)
.file(shim.join("vmime.cpp"))
.compile("cmp_vmime");
for library in &LIBRARIES {
println!(
"cargo:rustc-link-search=native={}",
prefix.join(library.name).join("lib").display()
);
println!("cargo:rustc-link-lib=static={}", library.static_lib);
}
toolchain.glib.link();
}
+138
View File
@@ -0,0 +1,138 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")"
TARGET=${CARGO_TARGET_DIR:-$(pwd)/target}
RUNS_DIR=${RUNS_DIR:-$TARGET/compare-runs}
LABEL_PREFIX=${LABEL_PREFIX:-compare}
ATTEMPTS=${ATTEMPTS:-5}
PAUSE=${PAUSE:-240}
BUILD_TIME_LIMIT=${BUILD_TIME_LIMIT:-10800}
MEASURE_TIME_LIMIT=${MEASURE_TIME_LIMIT:-1800}
PART_A="testsuite-lf testsuite-crlf enron-crlf attachments-crlf newsletter-crlf"
PART_B="modern-headers-crlf forwarded-crlf dashes-crlf plain-large-crlf attachments-lf newsletter-lf"
STOP="$RUNS_DIR/STOP"
if [ $# -lt 1 ]; then
echo "usage: $0 <run> [session...] (sessions: <structure|headers|full>-<a|b>)" >&2
exit 2
fi
run=$1
shift
sessions=${*:-"structure-a structure-b headers-a headers-b full-a full-b"}
step() {
if [ -n "${BUILD_WRAP:-}" ]; then
"$BUILD_WRAP" perl -e 'alarm shift; exec @ARGV' "$BUILD_TIME_LIMIT" "$@"
else
"$@"
fi
}
stopped() {
if [ -e "$STOP" ]; then
echo "$STOP exists: stopping before the next session" >&2
exit 3
fi
}
pause() {
waited=0
while [ "$waited" -lt "$PAUSE" ]; do
stopped
sleep 10
waited=$((waited + 10))
done
}
top_processes() {
case "$(uname -s)" in
Darwin) ps -Arco pid,pcpu,comm | head -n 8 ;;
*) ps -eo pid,pcpu,comm --sort=-pcpu | head -n 8 ;;
esac
}
BENCH=$(sed -n 's/.*Executable benches\/compare\.rs (\(.*\))$/\1/p' "$TARGET/bench-build.log" 2>/dev/null | tail -n 1)
case "$BENCH" in
"")
echo "no compare bench executable in $TARGET/bench-build.log: run cargo bench --no-run > $TARGET/bench-build.log 2>&1 first" >&2
exit 1
;;
/*) ;;
*) BENCH="$(pwd)/$BENCH" ;;
esac
NOISY=
if [ -n "${BENCH_LOCK:-}" ]; then
NOISY=${BENCH_NOISY_LOG:-${BENCH_LOCK_STATE:-$(dirname "$BENCH_LOCK")/state}/noisy.log}
export BENCH_IDLE_MIN="${BENCH_IDLE_MIN:-92}"
mkdir -p "$(dirname "$NOISY")"
touch "$NOISY"
fi
for session in $sessions; do
case "$session" in
structure-a | structure-b | headers-a | headers-b | full-a | full-b) ;;
*) echo "unknown session $session" >&2; exit 2 ;;
esac
done
out="$RUNS_DIR/r$run"
mkdir -p "$out/criterion"
stopped
step "$BENCH" --list > /dev/null
for session in $sessions; do
workload=${session%-*}
case "${session##*-}" in
a) corpora=$PART_A ;;
*) corpora=$PART_B ;;
esac
filter="^$workload/($(echo $corpora | tr ' ' '|'))/"
attempt=1
while :; do
stopped
label="$LABEL_PREFIX-$session-r$run-a$attempt"
(
while :; do
date '+%H:%M:%S'
top_processes
sleep 10
done
) > "$out/ps-$label.log" 2>&1 &
sampler=$!
status=0
if [ -n "$NOISY" ]; then
before=$(wc -l < "$NOISY")
"$BENCH_LOCK" "$label" perl -e 'alarm shift; exec @ARGV' "$MEASURE_TIME_LIMIT" \
"$BENCH" --bench "$filter" > "$out/$label.log" 2>&1 || status=$?
else
"$BENCH" --bench "$filter" > "$out/$label.log" 2>&1 || status=$?
fi
kill "$sampler" 2> /dev/null || true
wait "$sampler" 2> /dev/null || true
if [ "$status" -ne 0 ]; then
echo "$label: exit status $status (log: $out/$label.log)" >&2
exit "$status"
fi
if [ -n "$NOISY" ] && tail -n +"$((before + 1))" "$NOISY" | grep -q " $label "; then
echo "$label: noisy ($(grep " $label " "$NOISY" | tail -n 1))"
attempt=$((attempt + 1))
if [ "$attempt" -gt "$ATTEMPTS" ]; then
echo "$session: still noisy after $ATTEMPTS attempts" >&2
exit 1
fi
pause
continue
fi
echo "$label: clean"
for corpus in $corpora; do
if [ -d "$TARGET/criterion/${workload}_$corpus" ]; then
rm -rf "$out/criterion/${workload}_$corpus"
cp -R "$TARGET/criterion/${workload}_$corpus" "$out/criterion/"
fi
done
break
done
done
echo "run $run done: $out/criterion"
+391
View File
@@ -0,0 +1,391 @@
# Equivalence check
| corpus | messages | bytes | MiB | FNV-1a digest |
|---|---:|---:|---:|---|
| testsuite-lf | 123 | 316654 | 0.30 | `af8205bb38c165c5` |
| testsuite-crlf | 123 | 323727 | 0.31 | `85b9d080427109fc` |
| enron-crlf | 3000 | 6233382 | 5.94 | `ebbdb99ac861ae3b` |
| attachments-crlf | 3 | 4132787 | 3.94 | `00b8baeef0f9bbd4` |
| newsletter-crlf | 6 | 772947 | 0.74 | `0e0201fa1f217fc7` |
| modern-headers-crlf | 20 | 266601 | 0.25 | `20154783c10bbdf1` |
| forwarded-crlf | 6 | 110231 | 0.11 | `0b5bbf02c3108c4a` |
| dashes-crlf | 1 | 612915 | 0.58 | `5454fa53e5cb9b78` |
| plain-large-crlf | 1 | 1019901 | 0.97 | `bc625341e62c7a37` |
| attachments-lf | 3 | 4079113 | 3.89 | `1acc9c82b41557e9` |
| newsletter-lf | 6 | 759992 | 0.72 | `289c346c5a2549d8` |
## structure
| corpus | implementation | parsed | rejected | panics | crashes | messages | parts | differing messages |
|---|---|---:|---:|---:|---:|---:|---:|---:|
| testsuite-lf | mail-parser-1.0 | 123 | 0 | 0 | 0 | 143 | 479 | 0 |
| testsuite-lf | mailparse | 122 | 1 | 0 | 0 | 143 | 475 (-4) | 10 |
| testsuite-lf | gmime | 122 | 1 | 0 | 0 | 143 | 474 (-5) | 5 |
| testsuite-lf | vmime | 123 | 0 | 0 | 0 | 138 (-5) | 467 (-12) | 13 |
| testsuite-lf | libetpan | 123 | 0 | 0 | 0 | 143 | 467 (-12) | 12 |
| testsuite-lf | dovecot | 123 | 0 | 0 | 0 | 144 (+1) | 486 (+7) | 10 |
| testsuite-crlf | mail-parser-1.0 | 123 | 0 | 0 | 0 | 143 | 479 | 0 |
| testsuite-crlf | mailparse | 122 | 1 | 0 | 0 | 143 | 479 | 12 |
| testsuite-crlf | gmime | 122 | 1 | 0 | 0 | 143 | 474 (-5) | 5 |
| testsuite-crlf | vmime | 123 | 0 | 0 | 0 | 138 (-5) | 467 (-12) | 13 |
| testsuite-crlf | libetpan | 123 | 0 | 0 | 0 | 143 | 467 (-12) | 12 |
| testsuite-crlf | dovecot | 123 | 0 | 0 | 0 | 144 (+1) | 486 (+7) | 10 |
| enron-crlf | mail-parser-1.0 | 3000 | 0 | 0 | 0 | 3000 | 3000 | 0 |
| enron-crlf | mailparse | 3000 | 0 | 0 | 0 | 3000 | 3000 | 0 |
| enron-crlf | gmime | 3000 | 0 | 0 | 0 | 3000 | 3000 | 0 |
| enron-crlf | vmime | 3000 | 0 | 0 | 0 | 3000 | 3000 | 0 |
| enron-crlf | libetpan | 3000 | 0 | 0 | 0 | 3000 | 3000 | 0 |
| enron-crlf | dovecot | 3000 | 0 | 0 | 0 | 3000 | 3000 | 0 |
| attachments-crlf | mail-parser-1.0 | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-crlf | mailparse | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-crlf | gmime | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-crlf | vmime | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-crlf | libetpan | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-crlf | dovecot | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| newsletter-crlf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-crlf | mailparse | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-crlf | gmime | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-crlf | vmime | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-crlf | libetpan | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-crlf | dovecot | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| modern-headers-crlf | mail-parser-1.0 | 20 | 0 | 0 | 0 | 20 | 60 | 0 |
| modern-headers-crlf | mailparse | 20 | 0 | 0 | 0 | 20 | 60 | 0 |
| modern-headers-crlf | gmime | 20 | 0 | 0 | 0 | 20 | 60 | 0 |
| modern-headers-crlf | vmime | 20 | 0 | 0 | 0 | 20 | 60 | 0 |
| modern-headers-crlf | libetpan | 20 | 0 | 0 | 0 | 20 | 60 | 0 |
| modern-headers-crlf | dovecot | 20 | 0 | 0 | 0 | 20 | 60 | 0 |
| forwarded-crlf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 27 | 93 | 0 |
| forwarded-crlf | mailparse | 6 | 0 | 0 | 0 | 27 | 93 | 0 |
| forwarded-crlf | gmime | 6 | 0 | 0 | 0 | 27 | 93 | 0 |
| forwarded-crlf | vmime | 6 | 0 | 0 | 0 | 27 | 93 | 0 |
| forwarded-crlf | libetpan | 6 | 0 | 0 | 0 | 27 | 93 | 0 |
| forwarded-crlf | dovecot | 6 | 0 | 0 | 0 | 27 | 93 | 0 |
| dashes-crlf | mail-parser-1.0 | 1 | 0 | 0 | 0 | 1 | 4 | 0 |
| dashes-crlf | mailparse | 1 | 0 | 0 | 0 | 1 | 1065 (+1061) | 1 |
| dashes-crlf | gmime | 1 | 0 | 0 | 0 | 1 | 4 | 0 |
| dashes-crlf | vmime | 1 | 0 | 0 | 0 | 1 | 4 | 0 |
| dashes-crlf | libetpan | 1 | 0 | 0 | 0 | 1 | 4 | 0 |
| dashes-crlf | dovecot | 1 | 0 | 0 | 0 | 1 | 1065 (+1061) | 1 |
| plain-large-crlf | mail-parser-1.0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
| plain-large-crlf | mailparse | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
| plain-large-crlf | gmime | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
| plain-large-crlf | vmime | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
| plain-large-crlf | libetpan | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
| plain-large-crlf | dovecot | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
| attachments-lf | mail-parser-1.0 | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-lf | mailparse | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-lf | gmime | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-lf | vmime | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-lf | libetpan | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| attachments-lf | dovecot | 3 | 0 | 0 | 0 | 3 | 18 | 0 |
| newsletter-lf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-lf | mailparse | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-lf | gmime | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-lf | vmime | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-lf | libetpan | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
| newsletter-lf | dovecot | 6 | 0 | 0 | 0 | 6 | 30 | 0 |
## headers
| corpus | implementation | parsed | rejected | panics | crashes | subject | from | date | message-id | differing messages |
|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| testsuite-lf | mail-parser-1.0 | 123 | 0 | 0 | 0 | 94 | 92 | 83 | 73 | 0 |
| testsuite-lf | mailparse | 122 | 1 | 0 | 0 | 93 (-1) | 89 (-3) | 83 | 72 (-1) | 4 |
| testsuite-lf | gmime | 122 | 1 | 0 | 0 | 94 | 92 | 83 | 73 | 1 |
| testsuite-lf | vmime | 123 | 0 | 0 | 0 | 94 | 92 | 84 (+1) | 73 | 1 |
| testsuite-lf | libetpan | 123 | 0 | 0 | 0 | 94 | 92 | 83 | 73 | 0 |
| testsuite-lf | dovecot | 123 | 0 | 0 | 0 | 94 | 92 | 82 (-1) | 70 (-3) | 4 |
| testsuite-crlf | mail-parser-1.0 | 123 | 0 | 0 | 0 | 94 | 92 | 83 | 73 | 0 |
| testsuite-crlf | mailparse | 122 | 1 | 0 | 0 | 93 (-1) | 89 (-3) | 83 | 72 (-1) | 4 |
| testsuite-crlf | gmime | 122 | 1 | 0 | 0 | 94 | 92 | 83 | 73 | 1 |
| testsuite-crlf | vmime | 123 | 0 | 0 | 0 | 94 | 92 | 84 (+1) | 73 | 1 |
| testsuite-crlf | libetpan | 123 | 0 | 0 | 0 | 94 | 92 | 83 | 73 | 0 |
| testsuite-crlf | dovecot | 123 | 0 | 0 | 0 | 94 | 92 | 82 (-1) | 70 (-3) | 4 |
| enron-crlf | mail-parser-1.0 | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3000 | 0 |
| enron-crlf | mailparse | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3000 | 0 |
| enron-crlf | gmime | 3000 | 0 | 0 | 0 | 3000 | 2673 (-327) | 3000 | 3000 | 327 |
| enron-crlf | vmime | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3000 | 0 |
| enron-crlf | libetpan | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3000 | 0 |
| enron-crlf | dovecot | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3000 | 0 |
| attachments-crlf | mail-parser-1.0 | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-crlf | mailparse | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-crlf | gmime | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-crlf | vmime | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-crlf | libetpan | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-crlf | dovecot | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| newsletter-crlf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-crlf | mailparse | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-crlf | gmime | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-crlf | vmime | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-crlf | libetpan | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-crlf | dovecot | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| modern-headers-crlf | mail-parser-1.0 | 20 | 0 | 0 | 0 | 20 | 20 | 20 | 20 | 0 |
| modern-headers-crlf | mailparse | 20 | 0 | 0 | 0 | 20 | 20 | 20 | 20 | 0 |
| modern-headers-crlf | gmime | 20 | 0 | 0 | 0 | 20 | 20 | 20 | 20 | 0 |
| modern-headers-crlf | vmime | 20 | 0 | 0 | 0 | 20 | 20 | 20 | 20 | 0 |
| modern-headers-crlf | libetpan | 20 | 0 | 0 | 0 | 20 | 20 | 20 | 20 | 0 |
| modern-headers-crlf | dovecot | 20 | 0 | 0 | 0 | 20 | 20 | 20 | 20 | 0 |
| forwarded-crlf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| forwarded-crlf | mailparse | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| forwarded-crlf | gmime | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| forwarded-crlf | vmime | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| forwarded-crlf | libetpan | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| forwarded-crlf | dovecot | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| dashes-crlf | mail-parser-1.0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| dashes-crlf | mailparse | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| dashes-crlf | gmime | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| dashes-crlf | vmime | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| dashes-crlf | libetpan | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| dashes-crlf | dovecot | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| plain-large-crlf | mail-parser-1.0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| plain-large-crlf | mailparse | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| plain-large-crlf | gmime | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| plain-large-crlf | vmime | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| plain-large-crlf | libetpan | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| plain-large-crlf | dovecot | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 |
| attachments-lf | mail-parser-1.0 | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-lf | mailparse | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-lf | gmime | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-lf | vmime | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-lf | libetpan | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| attachments-lf | dovecot | 3 | 0 | 0 | 0 | 3 | 3 | 3 | 3 | 0 |
| newsletter-lf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-lf | mailparse | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-lf | gmime | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-lf | vmime | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-lf | libetpan | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
| newsletter-lf | dovecot | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 0 |
## full
| corpus | implementation | parsed | rejected | panics | crashes | messages | leaves | text leaves | decoded MiB | decoded vs 1.0 | failures | differing messages |
|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| testsuite-lf | mail-parser-1.0 | 123 | 0 | 0 | 0 | 143 | 316 | 223 | 0.17 | = | 0 | 0 |
| testsuite-lf | mailparse | 122 | 1 | 0 | 0 | 143 | 303 (-13) | 213 (-10) | 0.17 | -0.33% | 4 | 59 |
| testsuite-lf | gmime | 122 | 1 | 0 | 0 | 143 | 308 (-8) | 216 (-7) | 0.16 | -1.91% | 0 | 18 |
| testsuite-lf | vmime | 123 | 0 | 0 | 0 | 138 (-5) | 301 (-15) | 209 (-14) | 0.16 | -1.72% | 3 | 31 |
| testsuite-lf | libetpan | 123 | 0 | 0 | 0 | 143 | 307 (-9) | 214 (-9) | 0.17 | +1.46% | 0 | 69 |
| testsuite-lf | dovecot | 123 | 0 | 0 | 0 | 144 (+1) | 318 (+2) | 224 (+1) | 0.16 | -6.04% | 0 | 63 |
| testsuite-crlf | mail-parser-1.0 | 123 | 0 | 0 | 0 | 143 | 316 | 223 | 0.17 | = | 0 | 0 |
| testsuite-crlf | mailparse | 122 | 1 | 0 | 0 | 143 | 307 (-9) | 217 (-6) | 0.17 | -0.70% | 4 | 24 |
| testsuite-crlf | gmime | 122 | 1 | 0 | 0 | 143 | 308 (-8) | 216 (-7) | 0.17 | -1.99% | 0 | 19 |
| testsuite-crlf | vmime | 123 | 0 | 0 | 0 | 138 (-5) | 301 (-15) | 209 (-14) | 0.17 | -1.80% | 3 | 31 |
| testsuite-crlf | libetpan | 123 | 0 | 0 | 0 | 143 | 307 (-9) | 214 (-9) | 0.17 | +1.11% | 0 | 33 |
| testsuite-crlf | dovecot | 123 | 0 | 0 | 0 | 144 (+1) | 318 (+2) | 224 (+1) | 0.16 | -6.45% | 0 | 21 |
| enron-crlf | mail-parser-1.0 | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3.51 | = | 0 | 0 |
| enron-crlf | mailparse | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3.51 | = | 0 | 0 |
| enron-crlf | gmime | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3.51 | +0.00% | 0 | 2 |
| enron-crlf | vmime | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3.51 | +0.00% | 0 | 2 |
| enron-crlf | libetpan | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3.51 | +0.00% | 0 | 2 |
| enron-crlf | dovecot | 3000 | 0 | 0 | 0 | 3000 | 3000 | 3000 | 3.51 | = | 0 | 0 |
| attachments-crlf | mail-parser-1.0 | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-crlf | mailparse | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-crlf | gmime | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-crlf | vmime | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-crlf | libetpan | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-crlf | dovecot | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| newsletter-crlf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | = | 0 | 0 |
| newsletter-crlf | mailparse | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | = | 0 | 0 |
| newsletter-crlf | gmime | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | = | 0 | 0 |
| newsletter-crlf | vmime | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | = | 0 | 0 |
| newsletter-crlf | libetpan | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | = | 0 | 0 |
| newsletter-crlf | dovecot | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | = | 0 | 0 |
| modern-headers-crlf | mail-parser-1.0 | 20 | 0 | 0 | 0 | 20 | 40 | 40 | 0.15 | = | 0 | 0 |
| modern-headers-crlf | mailparse | 20 | 0 | 0 | 0 | 20 | 40 | 40 | 0.15 | = | 0 | 0 |
| modern-headers-crlf | gmime | 20 | 0 | 0 | 0 | 20 | 40 | 40 | 0.15 | = | 0 | 0 |
| modern-headers-crlf | vmime | 20 | 0 | 0 | 0 | 20 | 40 | 40 | 0.15 | = | 0 | 0 |
| modern-headers-crlf | libetpan | 20 | 0 | 0 | 0 | 20 | 40 | 40 | 0.15 | = | 0 | 0 |
| modern-headers-crlf | dovecot | 20 | 0 | 0 | 0 | 20 | 40 | 40 | 0.15 | = | 0 | 0 |
| forwarded-crlf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 27 | 39 | 39 | 0.08 | = | 0 | 0 |
| forwarded-crlf | mailparse | 6 | 0 | 0 | 0 | 27 | 39 | 39 | 0.08 | = | 0 | 0 |
| forwarded-crlf | gmime | 6 | 0 | 0 | 0 | 27 | 39 | 39 | 0.08 | = | 0 | 0 |
| forwarded-crlf | vmime | 6 | 0 | 0 | 0 | 27 | 39 | 39 | 0.08 | = | 0 | 0 |
| forwarded-crlf | libetpan | 6 | 0 | 0 | 0 | 27 | 39 | 39 | 0.08 | = | 0 | 0 |
| forwarded-crlf | dovecot | 6 | 0 | 0 | 0 | 27 | 39 | 39 | 0.08 | = | 0 | 0 |
| dashes-crlf | mail-parser-1.0 | 1 | 0 | 0 | 0 | 1 | 3 | 3 | 0.58 | = | 0 | 0 |
| dashes-crlf | mailparse | 1 | 0 | 0 | 0 | 1 | 1064 (+1061) | 1064 (+1061) | 0.00 | -99.77% | 0 | 1 |
| dashes-crlf | gmime | 1 | 0 | 0 | 0 | 1 | 3 | 3 | 0.58 | = | 0 | 0 |
| dashes-crlf | vmime | 1 | 0 | 0 | 0 | 1 | 3 | 3 | 0.58 | = | 0 | 0 |
| dashes-crlf | libetpan | 1 | 0 | 0 | 0 | 1 | 3 | 3 | 0.58 | = | 0 | 0 |
| dashes-crlf | dovecot | 1 | 0 | 0 | 0 | 1 | 1064 (+1061) | 1064 (+1061) | 0.00 | -99.77% | 0 | 1 |
| plain-large-crlf | mail-parser-1.0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0.97 | = | 0 | 0 |
| plain-large-crlf | mailparse | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0.97 | = | 0 | 0 |
| plain-large-crlf | gmime | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0.97 | = | 0 | 0 |
| plain-large-crlf | vmime | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0.97 | = | 0 | 0 |
| plain-large-crlf | libetpan | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0.97 | = | 0 | 0 |
| plain-large-crlf | dovecot | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0.97 | = | 0 | 0 |
| attachments-lf | mail-parser-1.0 | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-lf | mailparse | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | +0.04% | 0 | 3 |
| attachments-lf | gmime | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-lf | vmime | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | = | 0 | 0 |
| attachments-lf | libetpan | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | +0.04% | 0 | 3 |
| attachments-lf | dovecot | 3 | 0 | 0 | 0 | 3 | 12 | 6 | 2.89 | +0.04% | 0 | 3 |
| newsletter-lf | mail-parser-1.0 | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.63 | = | 0 | 0 |
| newsletter-lf | mailparse | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | +0.76% | 0 | 6 |
| newsletter-lf | gmime | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.63 | = | 0 | 0 |
| newsletter-lf | vmime | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.63 | = | 0 | 0 |
| newsletter-lf | libetpan | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | +0.76% | 0 | 6 |
| newsletter-lf | dovecot | 6 | 0 | 0 | 0 | 6 | 18 | 12 | 0.64 | +0.76% | 0 | 6 |
## Differing messages (first 5 per cell)
- structure testsuite-lf mailparse `legacy/015.eml`: 1 messages, 10 parts (1.0: 1 messages, 9 parts)
- structure testsuite-lf mailparse `legacy/025.eml`: 1 messages, 8 parts (1.0: 1 messages, 7 parts)
- structure testsuite-lf mailparse `legacy/051.eml`: 1 messages, 8 parts (1.0: 1 messages, 7 parts)
- structure testsuite-lf mailparse `malformed/005.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-lf mailparse `malformed/007.eml`: 1 messages, 4 parts (1.0: 1 messages, 2 parts)
- structure testsuite-lf gmime `malformed/000.eml`: 1 messages, 4 parts (1.0: 1 messages, 5 parts)
- structure testsuite-lf gmime `malformed/004.eml`: 1 messages, 1 parts (1.0: 1 messages, 3 parts)
- structure testsuite-lf gmime `malformed/017.eml`: 1 messages, 1 parts (1.0: 1 messages, 2 parts)
- structure testsuite-lf gmime `malformed/022.eml`: 2 messages, 4 parts (1.0: 1 messages, 3 parts)
- structure testsuite-lf gmime `malformed/023.eml`: rejected (1.0: 1 messages, 2 parts)
- structure testsuite-lf vmime `rfc/004.eml`: 1 messages, 5 parts (1.0: 3 messages, 7 parts)
- structure testsuite-lf vmime `thirdparty/007.eml`: 1 messages, 4 parts (1.0: 4 messages, 9 parts)
- structure testsuite-lf vmime `malformed/002.eml`: 1 messages, 2 parts (1.0: 1 messages, 1 parts)
- structure testsuite-lf vmime `malformed/005.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-lf vmime `malformed/008.eml`: 1 messages, 3 parts (1.0: 1 messages, 4 parts)
- structure testsuite-lf libetpan `thirdparty/007.eml`: 3 messages, 8 parts (1.0: 4 messages, 9 parts)
- structure testsuite-lf libetpan `malformed/000.eml`: 1 messages, 4 parts (1.0: 1 messages, 5 parts)
- structure testsuite-lf libetpan `malformed/002.eml`: 1 messages, 2 parts (1.0: 1 messages, 1 parts)
- structure testsuite-lf libetpan `malformed/004.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-lf libetpan `malformed/005.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-lf dovecot `rfc/008.eml`: 2 messages, 4 parts (1.0: 2 messages, 6 parts)
- structure testsuite-lf dovecot `malformed/007.eml`: 1 messages, 4 parts (1.0: 1 messages, 2 parts)
- structure testsuite-lf dovecot `malformed/013.eml`: 1 messages, 9 parts (1.0: 1 messages, 8 parts)
- structure testsuite-lf dovecot `malformed/014.eml`: 1 messages, 3 parts (1.0: 1 messages, 2 parts)
- structure testsuite-lf dovecot `malformed/016.eml`: 1 messages, 7 parts (1.0: 1 messages, 5 parts)
- structure testsuite-crlf mailparse `legacy/015.eml`: 1 messages, 10 parts (1.0: 1 messages, 9 parts)
- structure testsuite-crlf mailparse `legacy/025.eml`: 1 messages, 8 parts (1.0: 1 messages, 7 parts)
- structure testsuite-crlf mailparse `legacy/051.eml`: 1 messages, 8 parts (1.0: 1 messages, 7 parts)
- structure testsuite-crlf mailparse `malformed/005.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-crlf mailparse `malformed/007.eml`: 1 messages, 4 parts (1.0: 1 messages, 2 parts)
- structure testsuite-crlf gmime `malformed/000.eml`: 1 messages, 4 parts (1.0: 1 messages, 5 parts)
- structure testsuite-crlf gmime `malformed/004.eml`: 1 messages, 1 parts (1.0: 1 messages, 3 parts)
- structure testsuite-crlf gmime `malformed/017.eml`: 1 messages, 1 parts (1.0: 1 messages, 2 parts)
- structure testsuite-crlf gmime `malformed/022.eml`: 2 messages, 4 parts (1.0: 1 messages, 3 parts)
- structure testsuite-crlf gmime `malformed/023.eml`: rejected (1.0: 1 messages, 2 parts)
- structure testsuite-crlf vmime `rfc/004.eml`: 1 messages, 5 parts (1.0: 3 messages, 7 parts)
- structure testsuite-crlf vmime `thirdparty/007.eml`: 1 messages, 4 parts (1.0: 4 messages, 9 parts)
- structure testsuite-crlf vmime `malformed/002.eml`: 1 messages, 2 parts (1.0: 1 messages, 1 parts)
- structure testsuite-crlf vmime `malformed/005.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-crlf vmime `malformed/008.eml`: 1 messages, 3 parts (1.0: 1 messages, 4 parts)
- structure testsuite-crlf libetpan `thirdparty/007.eml`: 3 messages, 8 parts (1.0: 4 messages, 9 parts)
- structure testsuite-crlf libetpan `malformed/000.eml`: 1 messages, 4 parts (1.0: 1 messages, 5 parts)
- structure testsuite-crlf libetpan `malformed/002.eml`: 1 messages, 2 parts (1.0: 1 messages, 1 parts)
- structure testsuite-crlf libetpan `malformed/004.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-crlf libetpan `malformed/005.eml`: 1 messages, 2 parts (1.0: 1 messages, 3 parts)
- structure testsuite-crlf dovecot `rfc/008.eml`: 2 messages, 4 parts (1.0: 2 messages, 6 parts)
- structure testsuite-crlf dovecot `malformed/007.eml`: 1 messages, 4 parts (1.0: 1 messages, 2 parts)
- structure testsuite-crlf dovecot `malformed/013.eml`: 1 messages, 9 parts (1.0: 1 messages, 8 parts)
- structure testsuite-crlf dovecot `malformed/014.eml`: 1 messages, 3 parts (1.0: 1 messages, 2 parts)
- structure testsuite-crlf dovecot `malformed/016.eml`: 1 messages, 7 parts (1.0: 1 messages, 5 parts)
- structure dashes-crlf mailparse `dashes`: 1 messages, 1065 parts (1.0: 1 messages, 4 parts)
- structure dashes-crlf dovecot `dashes`: 1 messages, 1065 parts (1.0: 1 messages, 4 parts)
- headers testsuite-lf mailparse `rfc/001.eml`: subject 1, from 0, date 1, message-id 1 (1.0: subject 1, from 1, date 0, message-id 1)
- headers testsuite-lf mailparse `rfc/004.eml`: subject 1, from 0, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 0)
- headers testsuite-lf mailparse `thirdparty/007.eml`: subject 0, from 0, date 0, message-id 0 (1.0: subject 0, from 1, date 0, message-id 0)
- headers testsuite-lf mailparse `malformed/019.eml`: rejected (1.0: subject 1, from 0, date 1, message-id 1)
- headers testsuite-lf gmime `malformed/023.eml`: rejected (1.0: subject 0, from 0, date 0, message-id 0)
- headers testsuite-lf vmime `rfc/001.eml`: subject 1, from 1, date 1, message-id 1 (1.0: subject 1, from 1, date 0, message-id 1)
- headers testsuite-lf dovecot `malformed/019.eml`: subject 1, from 0, date 0, message-id 1 (1.0: subject 1, from 0, date 1, message-id 1)
- headers testsuite-lf dovecot `sieve/headers.eml`: subject 1, from 1, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 1)
- headers testsuite-lf dovecot `sieve/mixed-attachment.eml`: subject 1, from 1, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 1)
- headers testsuite-lf dovecot `sieve/nested.eml`: subject 1, from 1, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 1)
- headers testsuite-crlf mailparse `rfc/001.eml`: subject 1, from 0, date 1, message-id 1 (1.0: subject 1, from 1, date 0, message-id 1)
- headers testsuite-crlf mailparse `rfc/004.eml`: subject 1, from 0, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 0)
- headers testsuite-crlf mailparse `thirdparty/007.eml`: subject 0, from 0, date 0, message-id 0 (1.0: subject 0, from 1, date 0, message-id 0)
- headers testsuite-crlf mailparse `malformed/019.eml`: rejected (1.0: subject 1, from 0, date 1, message-id 1)
- headers testsuite-crlf gmime `malformed/023.eml`: rejected (1.0: subject 0, from 0, date 0, message-id 0)
- headers testsuite-crlf vmime `rfc/001.eml`: subject 1, from 1, date 1, message-id 1 (1.0: subject 1, from 1, date 0, message-id 1)
- headers testsuite-crlf dovecot `malformed/019.eml`: subject 1, from 0, date 0, message-id 1 (1.0: subject 1, from 0, date 1, message-id 1)
- headers testsuite-crlf dovecot `sieve/headers.eml`: subject 1, from 1, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 1)
- headers testsuite-crlf dovecot `sieve/mixed-attachment.eml`: subject 1, from 1, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 1)
- headers testsuite-crlf dovecot `sieve/nested.eml`: subject 1, from 1, date 1, message-id 0 (1.0: subject 1, from 1, date 1, message-id 1)
- headers enron-crlf gmime `allen-p/sent_items/1.`: subject 1, from 0, date 1, message-id 1 (1.0: subject 1, from 1, date 1, message-id 1)
- headers enron-crlf gmime `allen-p/sent_items/10.`: subject 1, from 0, date 1, message-id 1 (1.0: subject 1, from 1, date 1, message-id 1)
- headers enron-crlf gmime `allen-p/sent_items/100.`: subject 1, from 0, date 1, message-id 1 (1.0: subject 1, from 1, date 1, message-id 1)
- headers enron-crlf gmime `allen-p/sent_items/101.`: subject 1, from 0, date 1, message-id 1 (1.0: subject 1, from 1, date 1, message-id 1)
- headers enron-crlf gmime `allen-p/sent_items/102.`: subject 1, from 0, date 1, message-id 1 (1.0: subject 1, from 1, date 1, message-id 1)
- full testsuite-lf mailparse `rfc/000.eml`: 2 messages, 4 leaves, 562 bytes (1.0: 2 messages, 6 leaves, 628 bytes)
- full testsuite-lf mailparse `rfc/006.eml`: 1 messages, 2 leaves, 184 bytes (1.0: 1 messages, 2 leaves, 180 bytes)
- full testsuite-lf mailparse `legacy/001.eml`: 1 messages, 1 leaves, 763 bytes (1.0: 1 messages, 1 leaves, 755 bytes)
- full testsuite-lf mailparse `legacy/002.eml`: 1 messages, 1 leaves, 969 bytes (1.0: 1 messages, 1 leaves, 947 bytes)
- full testsuite-lf mailparse `legacy/003.eml`: 1 messages, 2 leaves, 1730 bytes (1.0: 1 messages, 2 leaves, 1701 bytes)
- full testsuite-lf gmime `rfc/000.eml`: 2 messages, 6 leaves, 627 bytes (1.0: 2 messages, 6 leaves, 628 bytes)
- full testsuite-lf gmime `legacy/017.eml`: 1 messages, 3 leaves, 3381 bytes (1.0: 1 messages, 3 leaves, 4437 bytes)
- full testsuite-lf gmime `legacy/026.eml`: 1 messages, 3 leaves, 2289 bytes (1.0: 1 messages, 3 leaves, 2611 bytes)
- full testsuite-lf gmime `legacy/033.eml`: 1 messages, 1 leaves, 721 bytes (1.0: 1 messages, 1 leaves, 769 bytes)
- full testsuite-lf gmime `legacy/048.eml`: 1 messages, 4 leaves, 4829 bytes (1.0: 1 messages, 4 leaves, 6458 bytes)
- full testsuite-lf vmime `rfc/000.eml`: 2 messages, 6 leaves, 639 bytes (1.0: 2 messages, 6 leaves, 628 bytes)
- full testsuite-lf vmime `rfc/004.eml`: 1 messages, 3 leaves, 270 bytes (1.0: 3 messages, 3 leaves, 98 bytes)
- full testsuite-lf vmime `legacy/017.eml`: 1 messages, 3 leaves, 3381 bytes (1.0: 1 messages, 3 leaves, 4437 bytes)
- full testsuite-lf vmime `legacy/026.eml`: 1 messages, 3 leaves, 2289 bytes (1.0: 1 messages, 3 leaves, 2611 bytes)
- full testsuite-lf vmime `legacy/033.eml`: 1 messages, 1 leaves, 737 bytes (1.0: 1 messages, 1 leaves, 769 bytes)
- full testsuite-lf libetpan `rfc/000.eml`: 2 messages, 6 leaves, 629 bytes (1.0: 2 messages, 6 leaves, 628 bytes)
- full testsuite-lf libetpan `rfc/006.eml`: 1 messages, 2 leaves, 184 bytes (1.0: 1 messages, 2 leaves, 180 bytes)
- full testsuite-lf libetpan `legacy/001.eml`: 1 messages, 1 leaves, 763 bytes (1.0: 1 messages, 1 leaves, 755 bytes)
- full testsuite-lf libetpan `legacy/002.eml`: 1 messages, 1 leaves, 969 bytes (1.0: 1 messages, 1 leaves, 947 bytes)
- full testsuite-lf libetpan `legacy/003.eml`: 1 messages, 2 leaves, 1730 bytes (1.0: 1 messages, 2 leaves, 1701 bytes)
- full testsuite-lf dovecot `rfc/000.eml`: 2 messages, 6 leaves, 562 bytes (1.0: 2 messages, 6 leaves, 628 bytes)
- full testsuite-lf dovecot `rfc/006.eml`: 1 messages, 2 leaves, 184 bytes (1.0: 1 messages, 2 leaves, 180 bytes)
- full testsuite-lf dovecot `rfc/008.eml`: 2 messages, 2 leaves, 54 bytes (1.0: 2 messages, 3 leaves, 257 bytes)
- full testsuite-lf dovecot `legacy/001.eml`: 1 messages, 1 leaves, 763 bytes (1.0: 1 messages, 1 leaves, 755 bytes)
- full testsuite-lf dovecot `legacy/002.eml`: 1 messages, 1 leaves, 969 bytes (1.0: 1 messages, 1 leaves, 947 bytes)
- full testsuite-crlf mailparse `rfc/000.eml`: 2 messages, 4 leaves, 577 bytes (1.0: 2 messages, 6 leaves, 644 bytes)
- full testsuite-crlf mailparse `legacy/015.eml`: 1 messages, 7 leaves, 7363 bytes (1.0: 1 messages, 6 leaves, 7363 bytes)
- full testsuite-crlf mailparse `legacy/025.eml`: 1 messages, 6 leaves, 6576 bytes (1.0: 1 messages, 5 leaves, 6576 bytes)
- full testsuite-crlf mailparse `legacy/026.eml`: 1 messages, 3 leaves, 2656 bytes (1.0: 1 messages, 3 leaves, 2657 bytes)
- full testsuite-crlf mailparse `legacy/051.eml`: 1 messages, 6 leaves, 6188 bytes (1.0: 1 messages, 5 leaves, 6188 bytes)
- full testsuite-crlf gmime `rfc/000.eml`: 2 messages, 6 leaves, 643 bytes (1.0: 2 messages, 6 leaves, 644 bytes)
- full testsuite-crlf gmime `legacy/017.eml`: 1 messages, 3 leaves, 3387 bytes (1.0: 1 messages, 3 leaves, 4510 bytes)
- full testsuite-crlf gmime `legacy/026.eml`: 1 messages, 3 leaves, 2314 bytes (1.0: 1 messages, 3 leaves, 2657 bytes)
- full testsuite-crlf gmime `legacy/033.eml`: 1 messages, 1 leaves, 736 bytes (1.0: 1 messages, 1 leaves, 784 bytes)
- full testsuite-crlf gmime `legacy/048.eml`: 1 messages, 4 leaves, 4843 bytes (1.0: 1 messages, 4 leaves, 6570 bytes)
- full testsuite-crlf vmime `rfc/000.eml`: 2 messages, 6 leaves, 655 bytes (1.0: 2 messages, 6 leaves, 644 bytes)
- full testsuite-crlf vmime `rfc/004.eml`: 1 messages, 3 leaves, 281 bytes (1.0: 3 messages, 3 leaves, 101 bytes)
- full testsuite-crlf vmime `legacy/017.eml`: 1 messages, 3 leaves, 3403 bytes (1.0: 1 messages, 3 leaves, 4510 bytes)
- full testsuite-crlf vmime `legacy/026.eml`: 1 messages, 3 leaves, 2314 bytes (1.0: 1 messages, 3 leaves, 2657 bytes)
- full testsuite-crlf vmime `legacy/033.eml`: 1 messages, 1 leaves, 752 bytes (1.0: 1 messages, 1 leaves, 784 bytes)
- full testsuite-crlf libetpan `legacy/026.eml`: 1 messages, 3 leaves, 2655 bytes (1.0: 1 messages, 3 leaves, 2657 bytes)
- full testsuite-crlf libetpan `legacy/033.eml`: 1 messages, 1 leaves, 752 bytes (1.0: 1 messages, 1 leaves, 784 bytes)
- full testsuite-crlf libetpan `legacy/052.eml`: 1 messages, 1 leaves, 752 bytes (1.0: 1 messages, 1 leaves, 784 bytes)
- full testsuite-crlf libetpan `thirdparty/002.eml`: 1 messages, 3 leaves, 35 bytes (1.0: 1 messages, 3 leaves, 45 bytes)
- full testsuite-crlf libetpan `thirdparty/005.eml`: 1 messages, 5 leaves, 77 bytes (1.0: 1 messages, 5 leaves, 75 bytes)
- full testsuite-crlf dovecot `rfc/000.eml`: 2 messages, 6 leaves, 577 bytes (1.0: 2 messages, 6 leaves, 644 bytes)
- full testsuite-crlf dovecot `rfc/008.eml`: 2 messages, 2 leaves, 54 bytes (1.0: 2 messages, 3 leaves, 257 bytes)
- full testsuite-crlf dovecot `legacy/017.eml`: 1 messages, 3 leaves, 764 bytes (1.0: 1 messages, 3 leaves, 4510 bytes)
- full testsuite-crlf dovecot `legacy/026.eml`: 1 messages, 3 leaves, 1567 bytes (1.0: 1 messages, 3 leaves, 2657 bytes)
- full testsuite-crlf dovecot `legacy/048.eml`: 1 messages, 4 leaves, 767 bytes (1.0: 1 messages, 4 leaves, 6570 bytes)
- full enron-crlf gmime `davis-d/vargas_becton_lamb/12.`: 1 messages, 1 leaves, 2317 bytes (1.0: 1 messages, 1 leaves, 2316 bytes)
- full enron-crlf gmime `horton-s/sent_items/108.`: 1 messages, 1 leaves, 3006 bytes (1.0: 1 messages, 1 leaves, 3003 bytes)
- full enron-crlf vmime `davis-d/vargas_becton_lamb/12.`: 1 messages, 1 leaves, 2317 bytes (1.0: 1 messages, 1 leaves, 2316 bytes)
- full enron-crlf vmime `horton-s/sent_items/108.`: 1 messages, 1 leaves, 3006 bytes (1.0: 1 messages, 1 leaves, 3003 bytes)
- full enron-crlf libetpan `davis-d/vargas_becton_lamb/12.`: 1 messages, 1 leaves, 2317 bytes (1.0: 1 messages, 1 leaves, 2316 bytes)
- full enron-crlf libetpan `horton-s/sent_items/108.`: 1 messages, 1 leaves, 3006 bytes (1.0: 1 messages, 1 leaves, 3003 bytes)
- full dashes-crlf mailparse `dashes`: 1 messages, 1064 leaves, 1402 bytes (1.0: 1 messages, 3 leaves, 611851 bytes)
- full dashes-crlf dovecot `dashes`: 1 messages, 1064 leaves, 1402 bytes (1.0: 1 messages, 3 leaves, 611851 bytes)
- full attachments-lf mailparse `attachments-0`: 1 messages, 4 leaves, 584457 bytes (1.0: 1 messages, 4 leaves, 584077 bytes)
- full attachments-lf mailparse `attachments-1`: 1 messages, 4 leaves, 114458 bytes (1.0: 1 messages, 4 leaves, 114097 bytes)
- full attachments-lf mailparse `attachments-2`: 1 messages, 4 leaves, 2334464 bytes (1.0: 1 messages, 4 leaves, 2334079 bytes)
- full attachments-lf libetpan `attachments-0`: 1 messages, 4 leaves, 584457 bytes (1.0: 1 messages, 4 leaves, 584077 bytes)
- full attachments-lf libetpan `attachments-1`: 1 messages, 4 leaves, 114458 bytes (1.0: 1 messages, 4 leaves, 114097 bytes)
- full attachments-lf libetpan `attachments-2`: 1 messages, 4 leaves, 2334464 bytes (1.0: 1 messages, 4 leaves, 2334079 bytes)
- full attachments-lf dovecot `attachments-0`: 1 messages, 4 leaves, 584457 bytes (1.0: 1 messages, 4 leaves, 584077 bytes)
- full attachments-lf dovecot `attachments-1`: 1 messages, 4 leaves, 114458 bytes (1.0: 1 messages, 4 leaves, 114097 bytes)
- full attachments-lf dovecot `attachments-2`: 1 messages, 4 leaves, 2334464 bytes (1.0: 1 messages, 4 leaves, 2334079 bytes)
- full newsletter-lf mailparse `newsletter-0`: 1 messages, 3 leaves, 80845 bytes (1.0: 1 messages, 3 leaves, 80247 bytes)
- full newsletter-lf mailparse `newsletter-1`: 1 messages, 3 leaves, 92907 bytes (1.0: 1 messages, 3 leaves, 92219 bytes)
- full newsletter-lf mailparse `newsletter-2`: 1 messages, 3 leaves, 105017 bytes (1.0: 1 messages, 3 leaves, 104215 bytes)
- full newsletter-lf mailparse `newsletter-3`: 1 messages, 3 leaves, 117218 bytes (1.0: 1 messages, 3 leaves, 116340 bytes)
- full newsletter-lf mailparse `newsletter-4`: 1 messages, 3 leaves, 129240 bytes (1.0: 1 messages, 3 leaves, 128241 bytes)
- full newsletter-lf libetpan `newsletter-0`: 1 messages, 3 leaves, 80845 bytes (1.0: 1 messages, 3 leaves, 80247 bytes)
- full newsletter-lf libetpan `newsletter-1`: 1 messages, 3 leaves, 92907 bytes (1.0: 1 messages, 3 leaves, 92219 bytes)
- full newsletter-lf libetpan `newsletter-2`: 1 messages, 3 leaves, 105017 bytes (1.0: 1 messages, 3 leaves, 104215 bytes)
- full newsletter-lf libetpan `newsletter-3`: 1 messages, 3 leaves, 117218 bytes (1.0: 1 messages, 3 leaves, 116340 bytes)
- full newsletter-lf libetpan `newsletter-4`: 1 messages, 3 leaves, 129240 bytes (1.0: 1 messages, 3 leaves, 128241 bytes)
- full newsletter-lf dovecot `newsletter-0`: 1 messages, 3 leaves, 80845 bytes (1.0: 1 messages, 3 leaves, 80247 bytes)
- full newsletter-lf dovecot `newsletter-1`: 1 messages, 3 leaves, 92907 bytes (1.0: 1 messages, 3 leaves, 92219 bytes)
- full newsletter-lf dovecot `newsletter-2`: 1 messages, 3 leaves, 105017 bytes (1.0: 1 messages, 3 leaves, 104215 bytes)
- full newsletter-lf dovecot `newsletter-3`: 1 messages, 3 leaves, 117218 bytes (1.0: 1 messages, 3 leaves, 116340 bytes)
- full newsletter-lf dovecot `newsletter-4`: 1 messages, 3 leaves, 129240 bytes (1.0: 1 messages, 3 leaves, 128241 bytes)
+105
View File
@@ -0,0 +1,105 @@
# Throughput of mail-parser 1.0 and other email parsers
Measured on 2026-09-28 on a Mac mini with an Apple M4 (4 performance and 6
efficiency cores, 16 GB), macOS 26.6.2, rustc 1.98.1, Apple clang 21.0.0
(clang-2100.3.34.2), Homebrew GLib 2.90.0 and CMake 4.4.3. Library versions
and build flags are in the [README](../README.md#implementations).
Method: three runs of the whole matrix (`./measure.sh 1`, `2`, `3`), each
run as six sessions of about two and a half minutes. Every session ran under
a machine-wide lock that waited for at least 92% idle CPU before starting
and sampled the idle time during the run; none of the 18 sessions was
flagged as busy, and none was repeated. Each cell is the median over the
three runs of criterion's median (30 samples, 3 s of measurement after 0.5 s
of warm-up). Throughput is the size of the corpus divided by the time to
handle all of its messages. `1.0 / x` is the throughput of mail-parser 1.0
divided by that of the other library: above 1 means mail-parser 1.0 is
faster.
Reading the table:
- The `dashes-crlf` cells of mailparse and Dovecot are not comparable: both
split that message at lines that only start with the boundary and decode
1,402 bytes where the other libraries decode 611,851 (see the
[equivalence check](check.md)).
- `plain-large-crlf` is one message with a single 1 MB text body. In
`structure` and `headers` no library needs to read that body, so those
cells measure a header parse against a megabyte of input and reach
hundreds of GB/s.
- The equivalence check behind these numbers is in [check.md](check.md).
Median of 3 runs: MiB/s, and mail-parser 1.0 divided by each other implementation.
| workload | corpus | mail-parser-1.0 MiB/s | mailparse MiB/s | gmime MiB/s | vmime MiB/s | libetpan MiB/s | dovecot MiB/s | 1.0 / mailparse | 1.0 / gmime | 1.0 / vmime | 1.0 / libetpan | 1.0 / dovecot |
|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| structure | testsuite-lf | 2078 | 830 | 120 | 19 | 228 | 766 | 2.50x | 17.25x | 107.87x | 9.11x | 2.71x |
| structure | testsuite-crlf | 2113 | 851 | 123 | 18 | 233 | 784 | 2.48x | 17.11x | 118.18x | 9.08x | 2.69x |
| structure | enron-crlf | 2774 | 1326 | 133 | 155 | 342 | 1223 | 2.09x | 20.90x | 17.85x | 8.10x | 2.27x |
| structure | attachments-crlf | 81210 | 32013 | 4707 | 1479 | 1362 | 5254 | 2.54x | 17.25x | 54.91x | 59.63x | 15.46x |
| structure | newsletter-crlf | 25502 | 4826 | 2173 | 650 | 526 | 3237 | 5.28x | 11.73x | 39.21x | 48.46x | 7.88x |
| structure | modern-headers-crlf | 3839 | 1691 | 471 | 337 | 588 | 1908 | 2.27x | 8.15x | 11.39x | 6.53x | 2.01x |
| structure | forwarded-crlf | 2951 | 969 | 225 | 163 | 154 | 1319 | 3.05x | 13.14x | 18.14x | 19.12x | 2.24x |
| structure | dashes-crlf | 11912 | 414 | 2295 | 1933 | 1092 | 614 | 28.80x | 5.19x | 6.16x | 10.91x | 19.39x |
| structure | plain-large-crlf | 836089 | 658492 | 3190 | 14725 | 237513 | 6972 | 1.27x | 262.07x | 56.78x | 3.52x | 119.92x |
| structure | attachments-lf | 80959 | 31830 | 4493 | 1472 | 1337 | 4917 | 2.54x | 18.02x | 55.00x | 60.55x | 16.46x |
| structure | newsletter-lf | 25381 | 4762 | 2130 | 648 | 524 | 3200 | 5.33x | 11.91x | 39.18x | 48.46x | 7.93x |
| headers | testsuite-lf | 2034 | 671 | 121 | 20 | 174 | 504 | 3.03x | 16.84x | 101.46x | 11.71x | 4.04x |
| headers | testsuite-crlf | 2089 | 687 | 122 | 16 | 176 | 514 | 3.04x | 17.06x | 127.70x | 11.84x | 4.06x |
| headers | enron-crlf | 2638 | 873 | 132 | 137 | 266 | 480 | 3.02x | 19.96x | 19.28x | 9.92x | 5.49x |
| headers | attachments-crlf | 80868 | 31344 | 4662 | 1471 | 1362 | 5205 | 2.58x | 17.35x | 54.96x | 59.36x | 15.54x |
| headers | newsletter-crlf | 25529 | 4671 | 2178 | 643 | 522 | 3074 | 5.46x | 11.72x | 39.71x | 48.94x | 8.30x |
| headers | modern-headers-crlf | 3805 | 1483 | 469 | 299 | 508 | 1390 | 2.57x | 8.12x | 12.71x | 7.48x | 2.74x |
| headers | forwarded-crlf | 2962 | 924 | 226 | 161 | 153 | 1179 | 3.21x | 13.11x | 18.43x | 19.37x | 2.51x |
| headers | dashes-crlf | 11781 | 400 | 2298 | 1913 | 1083 | 612 | 29.44x | 5.13x | 6.16x | 10.88x | 19.26x |
| headers | plain-large-crlf | 811217 | 424327 | 3188 | 14467 | 172706 | 6885 | 1.91x | 254.46x | 56.07x | 4.70x | 117.82x |
| headers | attachments-lf | 80278 | 31193 | 4496 | 1464 | 1341 | 4872 | 2.57x | 17.86x | 54.82x | 59.86x | 16.48x |
| headers | newsletter-lf | 25192 | 4589 | 2127 | 645 | 517 | 3038 | 5.49x | 11.85x | 39.05x | 48.73x | 8.29x |
| full | testsuite-lf | 1582 | 544 | 74 | 20 | 91 | 150 | 2.91x | 21.49x | 79.55x | 17.36x | 10.57x |
| full | testsuite-crlf | 1597 | 558 | 75 | 20 | 93 | 153 | 2.86x | 21.40x | 77.94x | 17.10x | 10.42x |
| full | enron-crlf | 2420 | 942 | 65 | 70 | 96 | 366 | 2.57x | 37.10x | 34.77x | 25.23x | 6.60x |
| full | attachments-crlf | 12747 | 2781 | 960 | 380 | 185 | 522 | 4.58x | 13.28x | 33.51x | 68.80x | 24.41x |
| full | newsletter-crlf | 2942 | 638 | 113 | 299 | 257 | 353 | 4.61x | 26.03x | 9.83x | 11.44x | 8.33x |
| full | modern-headers-crlf | 1989 | 556 | 116 | 230 | 352 | 391 | 3.58x | 17.09x | 8.67x | 5.66x | 5.09x |
| full | forwarded-crlf | 2639 | 897 | 79 | 152 | 150 | 606 | 2.94x | 33.58x | 17.41x | 17.65x | 4.35x |
| full | dashes-crlf | 7512 | 321 | 96 | 1250 | 868 | 582 | 23.38x | 77.92x | 6.01x | 8.65x | 12.90x |
| full | plain-large-crlf | 17171 | 13732 | 97 | 2212 | 2796 | 856 | 1.25x | 176.61x | 7.76x | 6.14x | 20.05x |
| full | attachments-lf | 12701 | 2836 | 957 | 372 | 183 | 514 | 4.48x | 13.27x | 34.13x | 69.31x | 24.72x |
| full | newsletter-lf | 3070 | 632 | 114 | 287 | 251 | 352 | 4.86x | 27.02x | 10.70x | 12.22x | 8.71x |
Spread of the runs, (max - min) / median:
| workload | corpus | mail-parser-1.0 | mailparse | gmime | vmime | libetpan | dovecot |
|---|---|---:|---:|---:|---:|---:|---:|
| structure | testsuite-lf | 0.9% | 1.2% | 1.9% | 15.0% | 1.8% | 0.7% |
| structure | testsuite-crlf | 0.6% | 0.6% | 1.0% | 14.8% | 1.7% | 0.0% |
| structure | enron-crlf | 1.1% | 1.8% | 0.6% | 0.7% | 1.2% | 0.5% |
| structure | attachments-crlf | 1.5% | 0.6% | 1.2% | 0.6% | 1.1% | 0.9% |
| structure | newsletter-crlf | 0.6% | 1.0% | 1.0% | 0.4% | 1.9% | 3.4% |
| structure | modern-headers-crlf | 0.4% | 0.7% | 1.0% | 0.8% | 1.2% | 0.4% |
| structure | forwarded-crlf | 1.5% | 1.8% | 1.2% | 0.2% | 1.1% | 1.0% |
| structure | dashes-crlf | 0.9% | 4.7% | 4.2% | 0.9% | 0.2% | 0.5% |
| structure | plain-large-crlf | 0.5% | 7.9% | 1.2% | 1.0% | 1.1% | 1.1% |
| structure | attachments-lf | 1.1% | 0.4% | 0.5% | 0.3% | 1.4% | 0.8% |
| structure | newsletter-lf | 0.0% | 0.9% | 1.5% | 1.7% | 0.0% | 2.3% |
| headers | testsuite-lf | 1.0% | 0.2% | 1.3% | 4.0% | 1.4% | 0.6% |
| headers | testsuite-crlf | 0.5% | 0.4% | 1.8% | 9.2% | 1.4% | 0.3% |
| headers | enron-crlf | 0.8% | 1.7% | 0.8% | 0.6% | 0.7% | 0.3% |
| headers | attachments-crlf | 0.8% | 0.3% | 0.8% | 0.3% | 0.4% | 0.7% |
| headers | newsletter-crlf | 0.3% | 0.3% | 2.3% | 0.4% | 0.6% | 1.9% |
| headers | modern-headers-crlf | 0.2% | 1.2% | 1.0% | 1.3% | 1.1% | 0.4% |
| headers | forwarded-crlf | 0.2% | 0.9% | 1.0% | 1.3% | 1.1% | 1.0% |
| headers | dashes-crlf | 1.2% | 6.9% | 3.1% | 1.2% | 0.3% | 0.3% |
| headers | plain-large-crlf | 0.6% | 2.9% | 1.2% | 6.1% | 0.7% | 1.2% |
| headers | attachments-lf | 0.6% | 0.0% | 0.2% | 0.5% | 1.0% | 0.2% |
| headers | newsletter-lf | 0.2% | 1.2% | 1.1% | 0.5% | 0.2% | 1.0% |
| full | testsuite-lf | 0.8% | 2.9% | 0.4% | 3.8% | 3.2% | 1.6% |
| full | testsuite-crlf | 1.0% | 1.0% | 1.3% | 1.1% | 0.5% | 0.4% |
| full | enron-crlf | 0.6% | 0.6% | 0.6% | 0.9% | 1.1% | 2.0% |
| full | attachments-crlf | 0.6% | 0.2% | 0.4% | 1.6% | 1.7% | 0.5% |
| full | newsletter-crlf | 1.1% | 0.4% | 1.3% | 4.2% | 0.9% | 3.5% |
| full | modern-headers-crlf | 0.7% | 1.9% | 2.8% | 4.3% | 2.0% | 2.0% |
| full | forwarded-crlf | 0.5% | 2.2% | 0.5% | 1.1% | 0.3% | 5.9% |
| full | dashes-crlf | 0.7% | 3.6% | 0.3% | 2.8% | 0.6% | 1.0% |
| full | plain-large-crlf | 0.5% | 0.2% | 0.6% | 2.1% | 1.3% | 10.0% |
| full | attachments-lf | 0.3% | 0.4% | 0.2% | 2.2% | 1.5% | 0.1% |
| full | newsletter-lf | 1.4% | 0.1% | 0.3% | 4.3% | 1.2% | 3.8% |
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")"
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$(pwd)/target}"
TARGET=$CARGO_TARGET_DIR
RESULTS=${RESULTS_DIR:-$(pwd)/results}
RUNS=${RUNS:-3}
BUILD_TIME_LIMIT=${BUILD_TIME_LIMIT:-10800}
step() {
if [ -n "${BUILD_WRAP:-}" ]; then
"$BUILD_WRAP" perl -e 'alarm shift; exec @ARGV' "$BUILD_TIME_LIMIT" "$@"
else
"$@"
fi
}
excludes=
for implementation in ${EXCLUDE:-}; do
excludes="$excludes --exclude $implementation"
done
for archive in gmime/lib/libgmime-3.0.a vmime/lib/libvmime.a libetpan/lib/libetpan-mime.a \
dovecot/lib/libdovecot-mail.a; do
if [ ! -f "vendor/prefix/$archive" ]; then
vendor/build.sh
break
fi
done
mkdir -p "$TARGET" "$RESULTS"
step cargo build --release --bins
step cargo bench --no-run > "$TARGET/bench-build.log" 2>&1
step "$TARGET/release/check" --examples 5 $excludes --out "$RESULTS/check.md" > /dev/null
runs=
run=1
while [ "$run" -le "$RUNS" ]; do
./measure.sh "$run"
runs="$runs ${RUNS_DIR:-$TARGET/compare-runs}/r$run/criterion"
run=$((run + 1))
done
"$TARGET/release/summary" $excludes $runs --out "$RESULTS/summary.md"
+214
View File
@@ -0,0 +1,214 @@
#include "lib.h"
#include "buffer.h"
#include "istream.h"
#include "str.h"
#include "message-address.h"
#include "message-date.h"
#include "message-decoder.h"
#include "message-header-decode.h"
#include "message-id.h"
#include "message-parser.h"
#include "rfc822-parser.h"
#include "tally.h"
enum { SEEN_SUBJECT = 1, SEEN_FROM = 2, SEEN_DATE = 4, SEEN_MESSAGE_ID = 8 };
void cmp_dovecot_init(void)
{
lib_init();
}
static bool is_header(const struct message_header_line *hdr, const char *name, size_t len)
{
return hdr->name_len == len && strcasecmp(hdr->name, name) == 0;
}
static void content_type(const struct message_header_line *hdr, cmp_tally *tally)
{
struct rfc822_parser_context parser;
string_t *value = t_str_new(64);
const char *type;
const char *subtype;
rfc822_parser_init(&parser, hdr->full_value, hdr->full_value_len, NULL);
rfc822_skip_lwsp(&parser);
(void)rfc822_parse_content_type(&parser, value);
rfc822_parser_deinit(&parser);
type = str_c(value);
subtype = strchr(type, '/');
if (subtype != NULL) {
cmp_add(tally, (uint64_t)(subtype - type));
cmp_str(tally, subtype + 1);
} else {
cmp_str(tally, type);
}
}
static void decoded_text(const unsigned char *value, size_t len, cmp_tally *tally)
{
buffer_t *decoded = t_buffer_create(len + 16);
message_header_decode_utf8(value, len, decoded, NULL);
cmp_add(tally, decoded->used);
}
static void from(const struct message_header_line *hdr, cmp_tally *tally)
{
const struct message_address *address =
message_address_parse(pool_datastack_create(), hdr->full_value, hdr->full_value_len,
UINT_MAX, 0);
for (; address != NULL; address = address->next) {
if (address->domain == NULL)
continue;
tally->from++;
if (address->name != NULL)
decoded_text((const unsigned char *)address->name, strlen(address->name), tally);
cmp_add(tally, strlen(address->mailbox) + 1 + strlen(address->domain));
return;
}
}
static void root_header(const struct message_header_line *hdr, unsigned *seen, cmp_tally *tally)
{
time_t timestamp;
int timezone_offset;
const char *ids;
const char *id;
if (!(*seen & SEEN_SUBJECT) && is_header(hdr, "Subject", 7)) {
*seen |= SEEN_SUBJECT;
tally->subject++;
decoded_text(hdr->full_value, hdr->full_value_len, tally);
} else if (!(*seen & SEEN_FROM) && is_header(hdr, "From", 4)) {
*seen |= SEEN_FROM;
from(hdr, tally);
} else if (!(*seen & SEEN_DATE) && is_header(hdr, "Date", 4)) {
*seen |= SEEN_DATE;
if (message_date_parse(hdr->full_value, hdr->full_value_len, &timestamp,
&timezone_offset)) {
tally->date++;
cmp_add(tally, (uint64_t)timestamp);
}
} else if (!(*seen & SEEN_MESSAGE_ID) && is_header(hdr, "Message-ID", 10)) {
*seen |= SEEN_MESSAGE_ID;
ids = t_strndup(hdr->full_value, hdr->full_value_len);
id = message_id_get_next(&ids);
if (id != NULL) {
tally->message_id++;
cmp_str(tally, id);
}
}
}
static bool is_root_field(const struct message_header_line *hdr)
{
return is_header(hdr, "Subject", 7) || is_header(hdr, "From", 4) ||
is_header(hdr, "Date", 4) || is_header(hdr, "Message-ID", 10);
}
static bool is_decoder_field(const struct message_header_line *hdr)
{
return is_header(hdr, "Content-Type", 12) || is_header(hdr, "Content-Transfer-Encoding", 25);
}
static void header_block(struct message_block *block, const struct message_part *root,
enum cmp_mode mode, unsigned *seen, cmp_tally *tally)
{
struct message_header_line *hdr = block->hdr;
if (mode == CMP_STRUCTURE && !hdr->continues && is_header(hdr, "Content-Type", 12)) {
T_BEGIN {
content_type(hdr, tally);
} T_END;
} else if (mode == CMP_HEADERS && block->part == root && is_root_field(hdr)) {
if (hdr->continues) {
hdr->use_full_value = TRUE;
} else {
T_BEGIN {
root_header(hdr, seen, tally);
} T_END;
}
}
}
static void body_block(struct message_decoder_context *decoder, struct message_block *block,
cmp_tally *tally)
{
struct message_block decoded;
if (block->hdr != NULL && !is_decoder_field(block->hdr))
return;
if (!message_decoder_decode_next_block(decoder, block, &decoded) || decoded.hdr != NULL ||
decoded.size == 0)
return;
tally->decoded_bytes += decoded.size;
if ((decoded.part->flags & MESSAGE_PART_FLAG_TEXT) != 0)
tally->text_bytes += decoded.size;
cmp_add(tally, decoded.size);
}
static void walk_parts(const struct message_part *part, enum cmp_mode mode, cmp_tally *tally)
{
for (; part != NULL; part = part->next) {
tally->parts++;
if ((part->flags & MESSAGE_PART_FLAG_MESSAGE_RFC822) != 0) {
if (part->children != NULL)
tally->messages++;
} else if (mode == CMP_FULL && (part->flags & MESSAGE_PART_FLAG_MULTIPART) == 0) {
tally->leaves++;
if ((part->flags & MESSAGE_PART_FLAG_TEXT) != 0)
tally->text_leaves++;
}
walk_parts(part->children, mode, tally);
}
}
static int run(const uint8_t *raw, size_t len, enum cmp_mode mode, cmp_tally *tally)
{
const struct message_parser_settings settings = {
.flags = mode == CMP_FULL ? 0 : MESSAGE_PARSER_FLAG_SKIP_BODY_BLOCK,
};
pool_t pool = pool_alloconly_create("cmp_dovecot", 4096);
struct istream *input = i_stream_create_from_data(raw, len);
struct message_parser_ctx *parser = message_parser_init(pool, input, &settings);
struct message_decoder_context *decoder =
mode == CMP_FULL ? message_decoder_init(NULL, MESSAGE_DECODER_FLAG_RETURN_BINARY) : NULL;
const struct message_part *root = NULL;
struct message_part *parts = NULL;
struct message_block block;
unsigned seen = 0;
while (message_parser_parse_next_block(parser, &block) > 0) {
if (root == NULL)
root = block.part;
if (decoder != NULL)
body_block(decoder, &block, tally);
else if (block.hdr != NULL)
header_block(&block, root, mode, &seen, tally);
}
if (decoder != NULL)
message_decoder_deinit(&decoder);
message_parser_deinit(&parser, &parts);
tally->messages++;
walk_parts(parts, mode, tally);
i_stream_unref(&input);
pool_unref(&pool);
return 1;
}
int cmp_dovecot_structure(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_STRUCTURE, tally);
}
int cmp_dovecot_headers(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_HEADERS, tally);
}
int cmp_dovecot_full(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_FULL, tally);
}
+200
View File
@@ -0,0 +1,200 @@
#include <gmime/gmime.h>
#include "tally.h"
void cmp_gmime_init(void)
{
g_mime_init();
}
static GMimeMessage *parse_stream(GMimeStream *stream)
{
GMimeParser *parser = g_mime_parser_new_with_stream(stream);
GMimeMessage *message = g_mime_parser_construct_message(parser, NULL);
g_object_unref(parser);
return message;
}
static GMimeMessage *parse(const uint8_t *raw, size_t len)
{
GMimeStream *stream = g_mime_stream_mem_new_with_buffer((const char *)raw, len);
GMimeMessage *message = parse_stream(stream);
g_object_unref(stream);
return message;
}
static int is_nested(GMimeContentType *content_type)
{
return content_type != NULL &&
(g_mime_content_type_is_type(content_type, "message", "rfc822") ||
g_mime_content_type_is_type(content_type, "message", "global"));
}
static void walk_object(GMimeObject *object, enum cmp_mode mode, cmp_tally *tally, int depth);
static void walk_message(GMimeMessage *message, enum cmp_mode mode, cmp_tally *tally, int depth)
{
GMimeObject *root = g_mime_message_get_mime_part(message);
tally->messages++;
if (root != NULL)
walk_object(root, mode, tally, depth);
}
static void walk_nested_bytes(GMimeDataWrapper *content, enum cmp_mode mode, cmp_tally *tally,
int depth)
{
GMimeStream *decoded = g_mime_stream_mem_new();
GMimeMessage *nested;
g_mime_data_wrapper_write_to_stream(content, decoded);
g_mime_stream_reset(decoded);
nested = parse_stream(decoded);
if (nested != NULL) {
walk_message(nested, mode, tally, depth + 1);
g_object_unref(nested);
} else {
tally->failures++;
}
g_object_unref(decoded);
}
static void full_text(GMimeTextPart *part, GMimeContentType *content_type, cmp_tally *tally)
{
char *text = g_mime_text_part_get_text(part);
size_t len = text != NULL ? strlen(text) : 0;
if (text != NULL && g_mime_content_type_get_parameter(content_type, "charset") == NULL)
cmp_utf8_leaf(tally, text, len);
else
cmp_leaf(tally, len, 1);
g_free(text);
}
static void full_leaf(GMimePart *part, GMimeDataWrapper *content, GMimeContentType *content_type,
cmp_tally *tally)
{
if (GMIME_IS_TEXT_PART(part)) {
full_text((GMimeTextPart *)part, content_type, tally);
} else if (content != NULL) {
GMimeStream *decoded = g_mime_stream_mem_new();
GByteArray *bytes;
g_mime_data_wrapper_write_to_stream(content, decoded);
bytes = g_mime_stream_mem_get_byte_array((GMimeStreamMem *)decoded);
cmp_leaf(tally, bytes != NULL ? bytes->len : 0, 0);
g_object_unref(decoded);
} else {
cmp_leaf(tally, 0, 0);
}
}
static void walk_object(GMimeObject *object, enum cmp_mode mode, cmp_tally *tally, int depth)
{
GMimeContentType *content_type = g_mime_object_get_content_type(object);
tally->parts++;
if (mode == CMP_STRUCTURE && content_type != NULL) {
cmp_str(tally, g_mime_content_type_get_media_type(content_type));
cmp_str(tally, g_mime_content_type_get_media_subtype(content_type));
}
if (GMIME_IS_MULTIPART(object)) {
GMimeMultipart *multipart = (GMimeMultipart *)object;
int count = g_mime_multipart_get_count(multipart);
for (int i = 0; i < count; i++)
walk_object(g_mime_multipart_get_part(multipart, i), mode, tally, depth);
} else if (GMIME_IS_MESSAGE_PART(object)) {
GMimeMessage *nested = g_mime_message_part_get_message((GMimeMessagePart *)object);
if (nested != NULL)
walk_message(nested, mode, tally, depth);
} else if (GMIME_IS_PART(object)) {
GMimePart *part = (GMimePart *)object;
GMimeDataWrapper *content = g_mime_part_get_content(part);
if (content != NULL && depth < CMP_MAX_NESTING && is_nested(content_type))
walk_nested_bytes(content, mode, tally, depth);
else if (mode == CMP_FULL)
full_leaf(part, content, content_type, tally);
}
}
int cmp_gmime_structure(const uint8_t *raw, size_t len, cmp_tally *tally)
{
GMimeMessage *message = parse(raw, len);
if (message == NULL)
return 0;
walk_message(message, CMP_STRUCTURE, tally, 0);
g_object_unref(message);
return 1;
}
static InternetAddressMailbox *first_mailbox(InternetAddressList *list)
{
int count = list != NULL ? internet_address_list_length(list) : 0;
for (int i = 0; i < count; i++) {
InternetAddress *address = internet_address_list_get_address(list, i);
if (INTERNET_ADDRESS_IS_MAILBOX(address))
return (InternetAddressMailbox *)address;
if (INTERNET_ADDRESS_IS_GROUP(address)) {
InternetAddressList *members =
internet_address_group_get_members((InternetAddressGroup *)address);
InternetAddressMailbox *mailbox = first_mailbox(members);
if (mailbox != NULL)
return mailbox;
}
}
return NULL;
}
int cmp_gmime_headers(const uint8_t *raw, size_t len, cmp_tally *tally)
{
GMimeMessage *message = parse(raw, len);
const char *subject;
const char *message_id;
InternetAddressMailbox *mailbox;
GDateTime *date;
if (message == NULL)
return 0;
subject = g_mime_message_get_subject(message);
if (subject != NULL) {
tally->subject++;
cmp_str(tally, subject);
}
mailbox = first_mailbox(g_mime_message_get_from(message));
if (mailbox != NULL) {
tally->from++;
cmp_str(tally, internet_address_get_name((InternetAddress *)mailbox));
cmp_str(tally, internet_address_mailbox_get_addr(mailbox));
}
date = g_mime_message_get_date(message);
if (date != NULL) {
tally->date++;
cmp_add(tally, (uint64_t)g_date_time_to_unix(date));
}
message_id = g_mime_message_get_message_id(message);
if (message_id != NULL) {
tally->message_id++;
cmp_str(tally, message_id);
}
walk_message(message, CMP_HEADERS, tally, 0);
g_object_unref(message);
return 1;
}
int cmp_gmime_full(const uint8_t *raw, size_t len, cmp_tally *tally)
{
GMimeMessage *message = parse(raw, len);
if (message == NULL)
return 0;
walk_message(message, CMP_FULL, tally, 0);
g_object_unref(message);
return 1;
}
+270
View File
@@ -0,0 +1,270 @@
#include <stdlib.h>
#include <strings.h>
#include <libetpan/charconv.h>
#include <libetpan/mailimf.h>
#include <libetpan/mailmime.h>
#include <libetpan/mailmime_content.h>
#include <libetpan/mailmime_decode.h>
#include "tally.h"
static struct mailmime *parse(const uint8_t *raw, size_t len)
{
struct mailmime *mime = NULL;
size_t index = 0;
if (mailmime_parse((const char *)raw, len, &index, &mime) != MAILIMF_NO_ERROR)
return NULL;
return mime;
}
static const char *media_type(const struct mailmime_content *content)
{
const struct mailmime_type *type = content != NULL ? content->ct_type : NULL;
if (type == NULL)
return NULL;
if (type->tp_type == MAILMIME_TYPE_DISCRETE_TYPE) {
const struct mailmime_discrete_type *discrete = type->tp_data.tp_discrete_type;
switch (discrete->dt_type) {
case MAILMIME_DISCRETE_TYPE_TEXT:
return "text";
case MAILMIME_DISCRETE_TYPE_IMAGE:
return "image";
case MAILMIME_DISCRETE_TYPE_AUDIO:
return "audio";
case MAILMIME_DISCRETE_TYPE_VIDEO:
return "video";
case MAILMIME_DISCRETE_TYPE_APPLICATION:
return "application";
default:
return discrete->dt_extension;
}
}
switch (type->tp_data.tp_composite_type->ct_type) {
case MAILMIME_COMPOSITE_TYPE_MESSAGE:
return "message";
case MAILMIME_COMPOSITE_TYPE_MULTIPART:
return "multipart";
default:
return type->tp_data.tp_composite_type->ct_token;
}
}
static const char *media_subtype(const struct mailmime_content *content)
{
return content != NULL ? content->ct_subtype : NULL;
}
static int is_type(const struct mailmime_content *content, const char *type)
{
const char *name = media_type(content);
return name != NULL && strcasecmp(name, type) == 0;
}
static int is_nested(const struct mailmime_content *content)
{
const char *subtype = media_subtype(content);
return is_type(content, "message") && subtype != NULL &&
(strcasecmp(subtype, "rfc822") == 0 || strcasecmp(subtype, "global") == 0);
}
static void walk_mime(const struct mailmime *mime, enum cmp_mode mode, cmp_tally *tally, int depth);
static void walk_root(const struct mailmime *root, enum cmp_mode mode, cmp_tally *tally, int depth)
{
tally->messages++;
if (root->mm_type == MAILMIME_MESSAGE && root->mm_data.mm_message.mm_msg_mime != NULL)
walk_mime(root->mm_data.mm_message.mm_msg_mime, mode, tally, depth);
}
static void walk_nested_bytes(const char *bytes, size_t len, enum cmp_mode mode, cmp_tally *tally,
int depth)
{
struct mailmime *nested = parse((const uint8_t *)bytes, len);
if (nested == NULL) {
tally->failures++;
return;
}
walk_root(nested, mode, tally, depth + 1);
mailmime_free(nested);
}
static void full_text(const struct mailmime_content *content, const char *bytes, size_t len,
cmp_tally *tally)
{
const char *charset = content != NULL ? mailmime_content_charset_get((struct mailmime_content *)content) : NULL;
char *converted = NULL;
size_t converted_len = 0;
if (charset != NULL && strcasecmp(charset, "utf-8") != 0 && strcasecmp(charset, "utf8") != 0 &&
charconv_buffer("utf-8", charset, bytes, len, &converted, &converted_len) ==
MAIL_CHARCONV_NO_ERROR) {
cmp_leaf(tally, converted_len, 1);
charconv_buffer_free(converted);
} else {
cmp_utf8_leaf(tally, bytes, len);
}
}
static void walk_leaf(const struct mailmime *mime, enum cmp_mode mode, cmp_tally *tally, int depth)
{
const struct mailmime_data *data = mime->mm_data.mm_single;
int nested = depth < CMP_MAX_NESTING && is_nested(mime->mm_content_type);
char *decoded = NULL;
size_t decoded_len = 0;
size_t index = 0;
if (!nested && mode != CMP_FULL)
return;
if (data == NULL || data->dt_type != MAILMIME_DATA_TEXT) {
if (mode == CMP_FULL)
cmp_leaf(tally, 0, is_type(mime->mm_content_type, "text"));
return;
}
if (mailmime_part_parse(data->dt_data.dt_text.dt_data, data->dt_data.dt_text.dt_length,
&index, data->dt_encoded ? data->dt_encoding : MAILMIME_MECHANISM_8BIT,
&decoded, &decoded_len) != MAILIMF_NO_ERROR) {
tally->failures++;
return;
}
if (nested)
walk_nested_bytes(decoded, decoded_len, mode, tally, depth);
else if (is_type(mime->mm_content_type, "text"))
full_text(mime->mm_content_type, decoded, decoded_len, tally);
else
cmp_leaf(tally, decoded_len, 0);
mailmime_decoded_part_free(decoded);
}
static void walk_mime(const struct mailmime *mime, enum cmp_mode mode, cmp_tally *tally, int depth)
{
tally->parts++;
if (mode == CMP_STRUCTURE) {
cmp_str(tally, media_type(mime->mm_content_type));
cmp_str(tally, media_subtype(mime->mm_content_type));
}
switch (mime->mm_type) {
case MAILMIME_MULTIPLE:
for (clistiter *cur = clist_begin(mime->mm_data.mm_multipart.mm_mp_list); cur != NULL;
cur = clist_next(cur))
walk_mime(clist_content(cur), mode, tally, depth);
break;
case MAILMIME_MESSAGE:
if (mime->mm_data.mm_message.mm_msg_mime != NULL) {
tally->messages++;
walk_mime(mime->mm_data.mm_message.mm_msg_mime, mode, tally, depth);
}
break;
default:
walk_leaf(mime, mode, tally, depth);
break;
}
}
static int run(const uint8_t *raw, size_t len, enum cmp_mode mode, cmp_tally *tally)
{
struct mailmime *root = parse(raw, len);
if (root == NULL)
return 0;
walk_root(root, mode, tally, 0);
mailmime_free(root);
return 1;
}
int cmp_libetpan_structure(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_STRUCTURE, tally);
}
static int decode_phrase(const char *value, cmp_tally *tally)
{
char *decoded = NULL;
size_t index = 0;
if (mailmime_encoded_phrase_parse("utf-8", value, strlen(value), &index, "utf-8", &decoded) !=
MAILIMF_NO_ERROR)
return 0;
cmp_str(tally, decoded);
free(decoded);
return 1;
}
enum { SEEN_SUBJECT = 1, SEEN_FROM = 2, SEEN_DATE = 4, SEEN_MESSAGE_ID = 8 };
static void header_field(const struct mailimf_field *field, unsigned *seen, cmp_tally *tally)
{
switch (field->fld_type) {
case MAILIMF_FIELD_SUBJECT:
if (!(*seen & SEEN_SUBJECT)) {
*seen |= SEEN_SUBJECT;
if (decode_phrase(field->fld_data.fld_subject->sbj_value, tally))
tally->subject++;
}
break;
case MAILIMF_FIELD_FROM:
if (!(*seen & SEEN_FROM)) {
clistiter *first = clist_begin(field->fld_data.fld_from->frm_mb_list->mb_list);
const struct mailimf_mailbox *mailbox = first != NULL ? clist_content(first) : NULL;
*seen |= SEEN_FROM;
if (mailbox != NULL) {
tally->from++;
if (mailbox->mb_display_name != NULL)
decode_phrase(mailbox->mb_display_name, tally);
cmp_str(tally, mailbox->mb_addr_spec);
}
}
break;
case MAILIMF_FIELD_ORIG_DATE:
if (!(*seen & SEEN_DATE)) {
const struct mailimf_date_time *date = field->fld_data.fld_orig_date->dt_date_time;
int64_t offset = (date->dt_zone / 100) * 60 + date->dt_zone % 100;
*seen |= SEEN_DATE;
tally->date++;
cmp_add(tally, (uint64_t)cmp_timestamp(date->dt_year, date->dt_month, date->dt_day,
date->dt_hour, date->dt_min, date->dt_sec,
offset));
}
break;
case MAILIMF_FIELD_MESSAGE_ID:
if (!(*seen & SEEN_MESSAGE_ID)) {
*seen |= SEEN_MESSAGE_ID;
tally->message_id++;
cmp_str(tally, field->fld_data.fld_message_id->mid_value);
}
break;
default:
break;
}
}
int cmp_libetpan_headers(const uint8_t *raw, size_t len, cmp_tally *tally)
{
struct mailmime *root = parse(raw, len);
const struct mailimf_fields *fields;
unsigned seen = 0;
if (root == NULL)
return 0;
fields = root->mm_type == MAILMIME_MESSAGE ? root->mm_data.mm_message.mm_fields : NULL;
if (fields != NULL) {
for (clistiter *cur = clist_begin(fields->fld_list); cur != NULL; cur = clist_next(cur))
header_field(clist_content(cur), &seen, tally);
}
walk_root(root, CMP_HEADERS, tally, 0);
mailmime_free(root);
return 1;
}
int cmp_libetpan_full(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_FULL, tally);
}
+70
View File
@@ -0,0 +1,70 @@
#ifndef CMP_TALLY_H
#define CMP_TALLY_H
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#define CMP_MAX_NESTING 8
typedef struct cmp_tally {
uint64_t digest;
uint64_t messages;
uint64_t parts;
uint64_t leaves;
uint64_t text_leaves;
uint64_t decoded_bytes;
uint64_t text_bytes;
uint64_t failures;
uint64_t subject;
uint64_t from;
uint64_t date;
uint64_t message_id;
} cmp_tally;
enum cmp_mode { CMP_STRUCTURE, CMP_HEADERS, CMP_FULL };
#ifdef __cplusplus
extern "C" {
#endif
void cmp_utf8_leaf(cmp_tally *tally, const char *bytes, size_t len);
#ifdef __cplusplus
}
#endif
static inline void cmp_add(cmp_tally *tally, uint64_t value)
{
tally->digest = ((tally->digest << 5) | (tally->digest >> 59)) ^ value;
}
static inline void cmp_str(cmp_tally *tally, const char *value)
{
if (value != NULL)
cmp_add(tally, strlen(value));
}
static inline void cmp_leaf(cmp_tally *tally, size_t len, int text)
{
tally->leaves++;
tally->decoded_bytes += len;
if (text) {
tally->text_leaves++;
tally->text_bytes += len;
}
cmp_add(tally, len);
}
static inline int64_t cmp_timestamp(int64_t year, int64_t month, int64_t day, int64_t hour,
int64_t minute, int64_t second, int64_t offset_minutes)
{
int64_t y = month <= 2 ? year - 1 : year;
int64_t era = (y >= 0 ? y : y - 399) / 400;
int64_t yoe = y - era * 400;
int64_t mp = (month + 9) % 12;
int64_t doy = (153 * mp + 2) / 5 + day - 1;
int64_t doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
int64_t days = era * 146097 + doe - 719468;
return days * 86400 + hour * 3600 + minute * 60 + second - offset_minutes * 60;
}
#endif
+9
View File
@@ -0,0 +1,9 @@
#include <glib.h>
#include "tally.h"
void cmp_utf8_leaf(cmp_tally *tally, const char *bytes, size_t len)
{
cmp_add(tally, g_utf8_validate_len(bytes, len, NULL));
cmp_leaf(tally, len, 1);
}
+157
View File
@@ -0,0 +1,157 @@
#include <vmime/vmime.hpp>
#include "tally.h"
namespace {
const vmime::charset &utf8()
{
static const vmime::charset charset(vmime::charsets::UTF_8);
return charset;
}
std::shared_ptr<vmime::message> parse(const char *raw, size_t len)
{
auto message = std::make_shared<vmime::message>();
message->parse(vmime::string(raw, len));
return message;
}
bool is_nested(const vmime::mediaType &type)
{
return type.getType() == vmime::mediaTypes::MESSAGE &&
(type.getSubType() == vmime::mediaTypes::MESSAGE_RFC822 || type.getSubType() == "global");
}
void walk_part(const vmime::bodyPart &part, cmp_mode mode, cmp_tally *tally, int depth);
void walk_message(const std::string &bytes, cmp_mode mode, cmp_tally *tally, int depth)
{
auto nested = std::make_shared<vmime::message>();
nested->parse(bytes);
tally->messages++;
walk_part(*nested, mode, tally, depth);
}
void full_text(const vmime::body &body, const std::string &decoded, cmp_tally *tally)
{
const vmime::charset charset = body.getCharset();
if (charset == utf8()) {
cmp_utf8_leaf(tally, decoded.data(), decoded.size());
return;
}
try {
std::string converted;
vmime::charset::convert(decoded, converted, charset, utf8());
cmp_leaf(tally, converted.size(), 1);
} catch (const vmime::exception &) {
cmp_utf8_leaf(tally, decoded.data(), decoded.size());
}
}
void walk_leaf(const vmime::body &body, const vmime::mediaType &type, cmp_mode mode,
cmp_tally *tally, int depth)
{
const bool nested = depth < CMP_MAX_NESTING && is_nested(type);
std::string decoded;
if (!nested && mode != CMP_FULL)
return;
try {
vmime::utility::outputStreamStringAdapter out(decoded);
body.getContents()->extract(out);
} catch (const vmime::exception &) {
tally->failures++;
return;
}
if (nested)
walk_message(decoded, mode, tally, depth + 1);
else if (type.getType() == vmime::mediaTypes::TEXT)
full_text(body, decoded, tally);
else
cmp_leaf(tally, decoded.size(), 0);
}
void walk_part(const vmime::bodyPart &part, cmp_mode mode, cmp_tally *tally, int depth)
{
auto body = part.getBody();
const vmime::mediaType type = body->getContentType();
const size_t count = body->getPartCount();
tally->parts++;
if (mode == CMP_STRUCTURE) {
cmp_add(tally, type.getType().size());
cmp_add(tally, type.getSubType().size());
}
if (count > 0 || type.getType() == vmime::mediaTypes::MULTIPART) {
for (size_t i = 0; i < count; ++i)
walk_part(*body->getPartAt(i), mode, tally, depth);
return;
}
walk_leaf(*body, type, mode, tally, depth);
}
template <typename T> std::shared_ptr<T> field_value(const vmime::header &header, const char *name)
{
auto field = header.findField(name);
return field ? field->getValue<T>() : nullptr;
}
void headers(const vmime::message &message, cmp_tally *tally)
{
const vmime::header &header = *message.getHeader();
if (auto subject = field_value<vmime::text>(header, vmime::fields::SUBJECT)) {
tally->subject++;
cmp_add(tally, subject->getConvertedText(utf8()).size());
}
if (auto from = field_value<vmime::mailbox>(header, vmime::fields::FROM)) {
if (!from->isEmpty()) {
tally->from++;
cmp_add(tally, from->getName().getConvertedText(utf8()).size());
cmp_add(tally, from->getEmail().toString().size());
}
}
if (auto date = field_value<vmime::datetime>(header, vmime::fields::DATE)) {
tally->date++;
cmp_add(tally, (uint64_t)cmp_timestamp(date->getYear(), date->getMonth(), date->getDay(),
date->getHour(), date->getMinute(), date->getSecond(),
date->getZone()));
}
if (auto id = field_value<vmime::messageId>(header, vmime::fields::MESSAGE_ID)) {
tally->message_id++;
cmp_add(tally, id->getId().size());
}
}
int run(const uint8_t *raw, size_t len, cmp_mode mode, cmp_tally *tally)
{
try {
auto message = parse(reinterpret_cast<const char *>(raw), len);
if (mode == CMP_HEADERS)
headers(*message, tally);
tally->messages++;
walk_part(*message, mode, tally, 0);
return 1;
} catch (const std::exception &) {
return 0;
}
}
}
extern "C" int cmp_vmime_structure(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_STRUCTURE, tally);
}
extern "C" int cmp_vmime_headers(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_HEADERS, tally);
}
extern "C" int cmp_vmime_full(const uint8_t *raw, size_t len, cmp_tally *tally)
{
return run(raw, len, CMP_FULL, tally);
}
+121
View File
@@ -0,0 +1,121 @@
mod report;
mod runner;
mod worker;
use mail_parser_compare::{
bench_corpora,
corpus::{self, Corpus},
workload::{Implementation, Workload},
};
use runner::{BoxError, Job};
use std::{env, fs, path::PathBuf};
const DEFAULT_THREADS: usize = 4;
#[derive(Default)]
struct Options {
corpora: Vec<String>,
implementations: Vec<Implementation>,
excluded: Vec<Implementation>,
workloads: Vec<Workload>,
out: Option<PathBuf>,
examples: usize,
threads: Option<usize>,
}
impl Options {
fn parse(mut args: impl Iterator<Item = String>) -> Result<Options, BoxError> {
let mut options = Options::default();
while let Some(arg) = args.next() {
let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value"));
match arg.as_str() {
"--corpus" => options.corpora.push(value()?),
"--implementation" => options.implementations.push(implementation(&value()?)?),
"--exclude" => options.excluded.push(implementation(&value()?)?),
"--workload" => {
let name = value()?;
options.workloads.push(
Workload::from_name(&name)
.ok_or_else(|| format!("unknown workload {name}"))?,
);
}
"--out" => options.out = Some(PathBuf::from(value()?)),
"--examples" => options.examples = value()?.parse()?,
"--jobs" => options.threads = Some(value()?.parse()?),
_ => return Err(format!("unknown argument {arg}").into()),
}
}
Ok(options)
}
fn corpora(&self) -> Result<Vec<&'static Corpus>, BoxError> {
if self.corpora.is_empty() {
return Ok(bench_corpora());
}
self.corpora
.iter()
.map(|name| corpus::get(name).ok_or_else(|| format!("unknown corpus {name}").into()))
.collect()
}
fn implementations(&self) -> Vec<Implementation> {
let mut selected = if self.implementations.is_empty() {
Implementation::ALL.to_vec()
} else {
self.implementations.clone()
};
selected.retain(|implementation| !self.excluded.contains(implementation));
if !selected.contains(&Implementation::REFERENCE) {
selected.insert(0, Implementation::REFERENCE);
}
selected
}
fn workloads(&self) -> Vec<Workload> {
if self.workloads.is_empty() {
Workload::ALL.to_vec()
} else {
self.workloads.clone()
}
}
}
fn implementation(name: &str) -> Result<Implementation, BoxError> {
Implementation::from_name(name).ok_or_else(|| format!("unknown implementation {name}").into())
}
fn main() -> Result<(), BoxError> {
let args: Vec<String> = env::args().skip(1).collect();
if let Some(worker_args) = args.strip_prefix(&["--worker".to_string()]) {
return worker::main(worker_args).map_err(|error| error.to_string().into());
}
let options = Options::parse(args.into_iter())?;
let corpora = options.corpora()?;
let implementations = options.implementations();
let workloads = options.workloads();
let mut jobs = Vec::with_capacity(corpora.len() * implementations.len() * workloads.len());
for &workload in &workloads {
for &corpus in &corpora {
jobs.extend(implementations.iter().map(|&implementation| Job {
workload,
corpus,
implementation,
}));
}
}
let threads = options.threads.unwrap_or(DEFAULT_THREADS);
let runs = runner::run_all(jobs, threads)?;
let mut out = String::with_capacity(64 * 1024);
out.push_str("# Equivalence check\n\n");
report::corpora(&mut out, &corpora, options.corpora.is_empty());
for &workload in &workloads {
report::workload(&mut out, workload, &runs, &corpora);
}
report::examples(&mut out, &runs, options.examples);
print!("{out}");
if let Some(path) = options.out {
fs::write(&path, &out)?;
eprintln!("written to {}", path.display());
}
Ok(())
}
+225
View File
@@ -0,0 +1,225 @@
use crate::runner::{Outcome, Run};
use mail_parser_compare::{
corpus::{self, Corpus},
missing_bench_corpora,
tally::Tally,
workload::{Implementation, Workload},
};
use std::fmt::Write as _;
const MIB: f64 = 1_048_576.0;
#[derive(Default)]
struct Summary {
parsed: u64,
rejected: u64,
panics: u64,
crashes: u64,
differing: u64,
total: Tally,
}
impl Summary {
fn new(run: &Run, reference: Option<&Run>) -> Summary {
let mut summary = Summary::default();
for outcome in &run.outcomes {
match outcome {
Outcome::Parsed(tally) => {
summary.parsed += 1;
summary.total += *tally;
}
Outcome::Rejected => summary.rejected += 1,
Outcome::Panic => summary.panics += 1,
Outcome::Crash => summary.crashes += 1,
}
}
summary.differing =
reference.map_or(0, |reference| differences(run, reference).count() as u64);
summary
}
}
fn key(workload: Workload, outcome: &Outcome) -> Option<[u64; 4]> {
let tally = outcome.tally()?;
Some(match workload {
Workload::Structure => [tally.messages, tally.parts, 0, 0],
Workload::Headers => [tally.subject, tally.from, tally.date, tally.message_id],
Workload::Full => [tally.messages, tally.leaves, tally.decoded_bytes, 0],
})
}
fn differences<'a>(
run: &'a Run,
reference: &'a Run,
) -> impl Iterator<Item = (usize, &'a Outcome, &'a Outcome)> {
let workload = run.job.workload;
run.outcomes
.iter()
.zip(&reference.outcomes)
.enumerate()
.filter(move |(_, (outcome, expected))| key(workload, outcome) != key(workload, expected))
.map(|(index, (outcome, expected))| (index, outcome, expected))
}
fn delta(value: u64, reference: Option<u64>) -> String {
match reference {
Some(reference) if reference != value => {
format!("{value} ({:+})", value as i128 - reference as i128)
}
_ => value.to_string(),
}
}
fn percent(value: u64, reference: Option<u64>) -> String {
match reference {
Some(reference) if reference > 0 && reference != value => format!(
"{:+.2}%",
(value as f64 - reference as f64) / reference as f64 * 100.0
),
Some(_) => "=".to_string(),
None => String::new(),
}
}
fn describe(workload: Workload, outcome: &Outcome) -> String {
match (outcome, key(workload, outcome)) {
(_, Some([a, b, c, d])) => match workload {
Workload::Structure => format!("{a} messages, {b} parts"),
Workload::Headers => format!("subject {a}, from {b}, date {c}, message-id {d}"),
Workload::Full => format!("{a} messages, {b} leaves, {c} bytes"),
},
(Outcome::Rejected, None) => "rejected".to_string(),
(Outcome::Panic, None) => "panic".to_string(),
(Outcome::Crash, None) => "crash".to_string(),
(Outcome::Parsed(_), None) => "parsed".to_string(),
}
}
pub fn corpora(out: &mut String, corpora: &[&Corpus], full_set: bool) {
if full_set {
for name in missing_bench_corpora(corpora) {
let _ = writeln!(
out,
"**Missing corpus: {name}** (run `scripts/fetch-corpora.sh` or point `{}` at the corpora directory).\n",
corpus::CORPORA_ENV
);
}
}
out.push_str("| corpus | messages | bytes | MiB | FNV-1a digest |\n|---|---:|---:|---:|---|\n");
for corpus in corpora {
let _ = writeln!(
out,
"| {} | {} | {} | {:.2} | `{:016x}` |",
corpus.name,
corpus.samples.len(),
corpus.total_bytes(),
corpus.mib(),
corpus.digest()
);
}
out.push('\n');
}
pub fn workload(out: &mut String, workload: Workload, runs: &[Run], corpora: &[&Corpus]) {
let _ = writeln!(out, "## {}\n", workload.name());
out.push_str("| corpus | implementation | parsed | rejected | panics | crashes |");
match workload {
Workload::Structure => out.push_str(" messages | parts | differing messages |\n|---|---|---:|---:|---:|---:|---:|---:|---:|\n"),
Workload::Headers => out.push_str(" subject | from | date | message-id | differing messages |\n|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|\n"),
Workload::Full => out.push_str(" messages | leaves | text leaves | decoded MiB | decoded vs 1.0 | failures | differing messages |\n|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|\n"),
}
for corpus in corpora {
let selected: Vec<&Run> = runs
.iter()
.filter(|run| run.job.workload == workload && run.job.corpus.name == corpus.name)
.collect();
let reference = selected
.iter()
.find(|run| run.job.implementation == Implementation::REFERENCE)
.copied();
let reference_summary = reference.map(|run| Summary::new(run, None));
let base = |field: fn(&Summary) -> u64| reference_summary.as_ref().map(field);
for run in &selected {
let summary = Summary::new(run, reference);
let _ = write!(
out,
"| {} | {} | {} | {} | {} | {} |",
corpus.name,
run.job.implementation.name(),
summary.parsed,
summary.rejected,
summary.panics,
summary.crashes
);
let total = &summary.total;
let _ = match workload {
Workload::Structure => writeln!(
out,
" {} | {} | {} |",
delta(total.messages, base(|s| s.total.messages)),
delta(total.parts, base(|s| s.total.parts)),
summary.differing
),
Workload::Headers => writeln!(
out,
" {} | {} | {} | {} | {} |",
delta(total.subject, base(|s| s.total.subject)),
delta(total.from, base(|s| s.total.from)),
delta(total.date, base(|s| s.total.date)),
delta(total.message_id, base(|s| s.total.message_id)),
summary.differing
),
Workload::Full => writeln!(
out,
" {} | {} | {} | {:.2} | {} | {} | {} |",
delta(total.messages, base(|s| s.total.messages)),
delta(total.leaves, base(|s| s.total.leaves)),
delta(total.text_leaves, base(|s| s.total.text_leaves)),
total.decoded_bytes as f64 / MIB,
percent(total.decoded_bytes, base(|s| s.total.decoded_bytes)),
total.failures,
summary.differing
),
};
}
}
out.push('\n');
}
pub fn examples(out: &mut String, runs: &[Run], limit: usize) {
if limit == 0 {
return;
}
let _ = writeln!(out, "## Differing messages (first {limit} per cell)\n");
for run in runs {
if run.job.implementation == Implementation::REFERENCE {
continue;
}
let Some(reference) = runs.iter().find(|candidate| {
candidate.job.implementation == Implementation::REFERENCE
&& candidate.job.workload == run.job.workload
&& candidate.job.corpus.name == run.job.corpus.name
}) else {
continue;
};
let workload = run.job.workload;
for (index, outcome, expected) in differences(run, reference).take(limit) {
let name = run
.job
.corpus
.samples
.get(index)
.map_or("?", |sample| sample.name.as_str());
let _ = writeln!(
out,
"- {} {} {} `{name}`: {} (1.0: {})",
workload.name(),
run.job.corpus.name,
run.job.implementation.name(),
describe(workload, outcome),
describe(workload, expected)
);
}
}
out.push('\n');
}
+156
View File
@@ -0,0 +1,156 @@
use crate::worker::{PANIC, PARSED, REJECTED};
use mail_parser_compare::{
corpus::Corpus,
tally::Tally,
workload::{Implementation, Workload},
};
use std::{
env,
error::Error,
os::unix::process::ExitStatusExt,
process::{Command, Stdio},
sync::{
Mutex,
atomic::{AtomicUsize, Ordering},
},
thread,
};
pub type BoxError = Box<dyn Error + Send + Sync>;
type JobResult = Result<Vec<Outcome>, BoxError>;
#[derive(Debug, Clone, Copy)]
pub enum Outcome {
Parsed(Tally),
Rejected,
Panic,
Crash,
}
impl Outcome {
pub fn tally(&self) -> Option<&Tally> {
match self {
Outcome::Parsed(tally) => Some(tally),
Outcome::Rejected | Outcome::Panic | Outcome::Crash => None,
}
}
}
pub struct Job {
pub workload: Workload,
pub corpus: &'static Corpus,
pub implementation: Implementation,
}
pub struct Run {
pub job: Job,
pub outcomes: Vec<Outcome>,
}
impl Job {
fn run(&self) -> JobResult {
let total = self.corpus.samples.len();
let executable = env::current_exe()?;
let mut outcomes = Vec::with_capacity(total);
while outcomes.len() < total {
let output = Command::new(&executable)
.arg("--worker")
.arg(self.implementation.name())
.arg(self.workload.name())
.arg(&self.corpus.name)
.arg(outcomes.len().to_string())
.stdin(Stdio::null())
.stderr(Stdio::inherit())
.output()?;
for line in String::from_utf8(output.stdout)?.lines() {
let (index, outcome) = parse_line(line)?;
if index != outcomes.len() {
return Err(format!("worker skipped to message {index}").into());
}
outcomes.push(outcome);
}
if output.status.success() {
if outcomes.len() < total {
return Err(format!(
"worker for {} {} {} stopped after {} of {total} messages",
self.implementation.name(),
self.workload.name(),
self.corpus.name,
outcomes.len()
)
.into());
}
} else if output.status.signal().is_some() {
if outcomes.len() < total {
outcomes.push(Outcome::Crash);
}
} else {
return Err(format!(
"worker for {} {} {} failed: {}",
self.implementation.name(),
self.workload.name(),
self.corpus.name,
output.status
)
.into());
}
}
Ok(outcomes)
}
}
fn parse_line(line: &str) -> Result<(usize, Outcome), BoxError> {
let mut columns = line.split('\t');
let index = columns.next().ok_or("empty worker line")?.parse()?;
let outcome = match columns.next() {
Some(PARSED) => {
let mut fields = [0u64; 12];
let mut values = columns.next().ok_or("missing tally")?.split(' ');
for field in &mut fields {
*field = values.next().ok_or("short tally")?.parse()?;
}
Outcome::Parsed(Tally::from_fields(fields))
}
Some(REJECTED) => Outcome::Rejected,
Some(PANIC) => Outcome::Panic,
_ => return Err(format!("bad worker line {line}").into()),
};
Ok((index, outcome))
}
pub fn run_all(jobs: Vec<Job>, threads: usize) -> Result<Vec<Run>, BoxError> {
let next = AtomicUsize::new(0);
let results: Mutex<Vec<Option<JobResult>>> = Mutex::new(jobs.iter().map(|_| None).collect());
thread::scope(|scope| {
for _ in 0..threads.max(1) {
scope.spawn(|| {
loop {
let index = next.fetch_add(1, Ordering::Relaxed);
let Some(job) = jobs.get(index) else {
break;
};
let result = job.run();
eprintln!(
"checked {} {} {}",
job.workload.name(),
job.corpus.name,
job.implementation.name()
);
if let Ok(mut results) = results.lock()
&& let Some(slot) = results.get_mut(index)
{
*slot = Some(result);
}
}
});
}
});
let results = results.into_inner().map_err(|_| "result lock poisoned")?;
jobs.into_iter()
.zip(results)
.map(|(job, result)| {
let outcomes = result.ok_or("job did not run")??;
Ok(Run { job, outcomes })
})
.collect()
}
+49
View File
@@ -0,0 +1,49 @@
use mail_parser_compare::{
corpus,
tally::Tally,
workload::{Implementation, Parsers, Workload},
};
use std::{
error::Error,
io::{self, Write},
panic::{self, AssertUnwindSafe},
};
pub const REJECTED: &str = "rejected";
pub const PANIC: &str = "panic";
pub const PARSED: &str = "parsed";
pub fn main(args: &[String]) -> Result<(), Box<dyn Error>> {
let [implementation, workload, corpus_name, start] = args else {
return Err("usage: check --worker <implementation> <workload> <corpus> <start>".into());
};
let implementation = Implementation::from_name(implementation)
.ok_or_else(|| format!("unknown implementation {implementation}"))?;
let workload =
Workload::from_name(workload).ok_or_else(|| format!("unknown workload {workload}"))?;
let corpus = corpus::get(corpus_name).ok_or_else(|| format!("unknown corpus {corpus_name}"))?;
let start: usize = start.parse()?;
let parsers = Parsers::default();
panic::set_hook(Box::new(|_| {}));
let mut out = io::stdout().lock();
for (index, sample) in corpus.samples.iter().enumerate().skip(start) {
let mut tally = Tally::default();
let outcome = panic::catch_unwind(AssertUnwindSafe(|| {
parsers.run(implementation, workload, &sample.bytes, &mut tally)
}));
match outcome {
Ok(true) => {
write!(out, "{index}\t{PARSED}\t")?;
for (position, field) in tally.fields().iter().enumerate() {
let separator = if position == 0 { "" } else { " " };
write!(out, "{separator}{field}")?;
}
writeln!(out)?;
}
Ok(false) => writeln!(out, "{index}\t{REJECTED}")?,
Err(_) => writeln!(out, "{index}\t{PANIC}")?,
}
out.flush()?;
}
Ok(())
}
+274
View File
@@ -0,0 +1,274 @@
use mail_parser_compare::{
corpus,
workload::{Implementation, Workload},
};
use serde_json::Value;
use std::{
env,
error::Error,
fmt::Write as _,
fs,
path::{Path, PathBuf},
};
struct Entry {
workload: String,
corpus: String,
implementation: String,
median_ns: f64,
bytes: f64,
}
impl Entry {
fn mib_per_second(&self) -> f64 {
self.bytes / self.median_ns * 1e9 / f64::from(1u32 << 20)
}
fn read(dir: &Path) -> Option<Entry> {
let benchmark: Value =
serde_json::from_slice(&fs::read(dir.join("benchmark.json")).ok()?).ok()?;
let estimates: Value =
serde_json::from_slice(&fs::read(dir.join("estimates.json")).ok()?).ok()?;
let (workload, corpus) = benchmark.get("group_id")?.as_str()?.split_once('/')?;
Workload::from_name(workload)?;
let throughput = benchmark.get("throughput")?;
let bytes = throughput
.get("Bytes")
.or_else(|| throughput.get("BytesDecimal"))?
.as_f64()?;
Some(Entry {
workload: workload.to_string(),
corpus: corpus.to_string(),
implementation: benchmark.get("function_id")?.as_str()?.to_string(),
median_ns: estimates.get("median")?.get("point_estimate")?.as_f64()?,
bytes,
})
}
}
fn criterion_dir() -> PathBuf {
env::var_os("CARGO_TARGET_DIR")
.map_or_else(
|| Path::new(env!("CARGO_MANIFEST_DIR")).join("target"),
PathBuf::from,
)
.join("criterion")
}
fn collect(root: &Path) -> Vec<Entry> {
let mut entries = Vec::new();
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(children) = fs::read_dir(&dir) else {
continue;
};
for child in children.flatten().map(|child| child.path()) {
if !child.is_dir() {
continue;
}
if child.file_name().is_some_and(|name| name == "new") {
entries.extend(Entry::read(&child));
} else {
stack.push(child);
}
}
}
entries
}
fn position<T: PartialEq>(items: &[T], item: &T) -> usize {
items
.iter()
.position(|candidate| candidate == item)
.unwrap_or(items.len())
}
struct Cell<'a> {
workload: &'a str,
corpus: &'a str,
speeds: Vec<(&'a str, Vec<f64>)>,
}
impl Cell<'_> {
fn speeds(&self, implementation: &str) -> Option<&[f64]> {
self.speeds
.iter()
.find(|(name, _)| *name == implementation)
.map(|(_, speeds)| speeds.as_slice())
}
fn median(&self, implementation: &str) -> Option<f64> {
self.speeds(implementation).and_then(median)
}
fn spread(&self, implementation: &str) -> Option<f64> {
let speeds = self.speeds(implementation)?;
let median = median(speeds)?;
let (min, max) = speeds
.iter()
.fold((f64::MAX, f64::MIN), |(min, max), &speed| {
(min.min(speed), max.max(speed))
});
Some((max - min) / median * 100.0)
}
}
fn median(speeds: &[f64]) -> Option<f64> {
let mut sorted = speeds.to_vec();
sorted.sort_by(f64::total_cmp);
let middle = sorted.len() / 2;
match sorted.len() {
0 => None,
len if len % 2 == 1 => sorted.get(middle).copied(),
_ => Some((sorted.get(middle - 1)? + sorted.get(middle)?) / 2.0),
}
}
fn cells<'a>(entries: &'a [Entry], implementations: &[&'a str]) -> Vec<Cell<'a>> {
let mut cells: Vec<Cell<'a>> = Vec::new();
for entry in entries {
if !cells
.iter()
.any(|cell| cell.workload == entry.workload && cell.corpus == entry.corpus)
{
cells.push(Cell {
workload: &entry.workload,
corpus: &entry.corpus,
speeds: implementations
.iter()
.map(|name| (*name, Vec::new()))
.collect(),
});
}
}
for entry in entries {
let speeds = cells
.iter_mut()
.find(|cell| cell.workload == entry.workload && cell.corpus == entry.corpus)
.and_then(|cell| {
cell.speeds
.iter_mut()
.find(|(name, _)| *name == entry.implementation)
});
if let Some((_, speeds)) = speeds {
speeds.push(entry.mib_per_second());
}
}
cells
}
fn header(table: &mut String, columns: impl Iterator<Item = String>) {
table.push_str("| workload | corpus |");
let mut count = 0;
for column in columns {
let _ = write!(table, " {column} |");
count += 1;
}
table.push_str("\n|---|---|");
table.push_str(&"---:|".repeat(count));
table.push('\n');
}
fn format_value(value: Option<f64>, format: impl Fn(f64) -> String) -> String {
value.map_or_else(String::new, format)
}
fn main() -> Result<(), Box<dyn Error>> {
let mut args = env::args().skip(1);
let mut out = None;
let mut roots = Vec::new();
let mut excluded = Vec::new();
while let Some(arg) = args.next() {
match arg.as_str() {
"--out" => out = args.next().map(PathBuf::from),
"--exclude" => {
let name = args.next().ok_or("--exclude needs an implementation")?;
excluded.push(
Implementation::from_name(&name)
.ok_or_else(|| format!("unknown implementation {name}"))?,
);
}
_ => roots.push(PathBuf::from(arg)),
}
}
if roots.is_empty() {
roots.push(criterion_dir());
}
let mut entries: Vec<Entry> = roots.iter().flat_map(|root| collect(root)).collect();
if entries.is_empty() {
return Err("no criterion results found".into());
}
let workloads = Workload::ALL.map(Workload::name);
let order = |entry: &Entry| {
(
position(&workloads, &entry.workload.as_str()),
position(corpus::BENCH, &entry.corpus.as_str()),
entry.corpus.clone(),
)
};
entries.sort_by_cached_key(order);
let implementations: Vec<&str> = Implementation::ALL
.iter()
.filter(|implementation| !excluded.contains(implementation))
.map(|implementation| implementation.name())
.filter(|name| entries.iter().any(|entry| entry.implementation == *name))
.collect();
let reference = Implementation::REFERENCE.name();
let others: Vec<&str> = implementations
.iter()
.copied()
.filter(|name| *name != reference)
.collect();
let cells = cells(&entries, &implementations);
let mut table = String::with_capacity(16384);
if roots.len() > 1 {
let _ = writeln!(
table,
"Median of {} runs: MiB/s, and mail-parser 1.0 divided by each other implementation.\n",
roots.len()
);
}
header(
&mut table,
implementations
.iter()
.map(|name| format!("{name} MiB/s"))
.chain(others.iter().map(|name| format!("1.0 / {name}"))),
);
for cell in &cells {
let _ = write!(table, "| {} | {} |", cell.workload, cell.corpus);
for name in &implementations {
let value = format_value(cell.median(name), |value| format!("{value:.0}"));
let _ = write!(table, " {value} |");
}
let base = cell.median(reference);
for name in &others {
let ratio = format_value(base.zip(cell.median(name)).map(|(a, b)| a / b), |ratio| {
format!("{ratio:.2}x")
});
let _ = write!(table, " {ratio} |");
}
table.push('\n');
}
if roots.len() > 1 {
table.push_str("\nSpread of the runs, (max - min) / median:\n\n");
header(
&mut table,
implementations.iter().map(|name| (*name).to_string()),
);
for cell in &cells {
let _ = write!(table, "| {} | {} |", cell.workload, cell.corpus);
for name in &implementations {
let spread = format_value(cell.spread(name), |spread| format!("{spread:.1}%"));
let _ = write!(table, " {spread} |");
}
table.push('\n');
}
}
print!("{table}");
if let Some(out) = out {
fs::write(&out, &table)?;
eprintln!("written to {}", out.display());
}
Ok(())
}
+279
View File
@@ -0,0 +1,279 @@
mod synthetic;
use std::{
env, fs,
path::{Path, PathBuf},
sync::OnceLock,
};
pub const CORPORA_ENV: &str = "MAIL_PARSER_CORPORA";
pub const ENRON_MAILDIR: &str = "enron/maildir";
pub const STALWART_SMTP: &str = "stalwart-smtp";
const SIEVE_LABEL: &str = "sieve";
const ENRON_PER_USER: usize = 20;
const TESTSUITE_SUITES: [&str; 4] = ["rfc", "legacy", "thirdparty", "malformed"];
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
pub const BENCH: &[&str] = &[
"testsuite-lf",
"testsuite-crlf",
"enron-crlf",
"attachments-crlf",
"newsletter-crlf",
"modern-headers-crlf",
"forwarded-crlf",
"dashes-crlf",
"plain-large-crlf",
"attachments-lf",
"newsletter-lf",
];
static TESTSUITE: OnceLock<Vec<Corpus>> = OnceLock::new();
static ENRON: OnceLock<Vec<Corpus>> = OnceLock::new();
static SYNTHETIC: OnceLock<Vec<Corpus>> = OnceLock::new();
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineEnding {
Lf,
Crlf,
}
impl LineEnding {
pub const ALL: [LineEnding; 2] = [LineEnding::Lf, LineEnding::Crlf];
pub fn suffix(self) -> &'static str {
match self {
LineEnding::Lf => "lf",
LineEnding::Crlf => "crlf",
}
}
pub fn apply(self, bytes: &[u8]) -> Vec<u8> {
let mut result = Vec::with_capacity(bytes.len() + bytes.len() / 32);
match self {
LineEnding::Lf => result.extend(bytes.iter().filter(|&&byte| byte != b'\r')),
LineEnding::Crlf => {
let mut last = 0;
for &byte in bytes {
if byte == b'\n' && last != b'\r' {
result.push(b'\r');
}
result.push(byte);
last = byte;
}
}
}
result
}
}
#[derive(Debug, Clone)]
pub struct Sample {
pub name: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct Corpus {
pub name: String,
pub samples: Vec<Sample>,
}
impl Corpus {
pub fn total_bytes(&self) -> u64 {
self.samples.iter().map(|s| s.bytes.len() as u64).sum()
}
pub fn mib(&self) -> f64 {
self.total_bytes() as f64 / f64::from(1u32 << 20)
}
pub fn digest(&self) -> u64 {
self.samples.iter().fold(FNV_OFFSET, |hash, sample| {
sample
.bytes
.iter()
.copied()
.chain((sample.bytes.len() as u64).to_le_bytes())
.fold(hash, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(FNV_PRIME)
})
})
}
fn with_line_ending(name: &str, line_ending: LineEnding, samples: &[Sample]) -> Self {
Corpus {
name: format!("{name}-{}", line_ending.suffix()),
samples: samples
.iter()
.map(|sample| Sample {
name: sample.name.clone(),
bytes: line_ending.apply(&sample.bytes),
})
.collect(),
}
}
fn both_line_endings(name: &str, samples: &[Sample]) -> impl Iterator<Item = Corpus> {
LineEnding::ALL
.into_iter()
.map(move |line_ending| Corpus::with_line_ending(name, line_ending, samples))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Family {
Testsuite,
Enron,
Synthetic,
}
impl Family {
fn of(name: &str) -> Option<Family> {
let (base, ending) = name.rsplit_once('-')?;
if !LineEnding::ALL.iter().any(|le| le.suffix() == ending) {
return None;
}
match base {
"testsuite" => Some(Family::Testsuite),
"enron" => Some(Family::Enron),
_ if synthetic::NAMES.contains(&base) => Some(Family::Synthetic),
_ => None,
}
}
fn corpora(self) -> &'static [Corpus] {
match self {
Family::Testsuite => TESTSUITE.get_or_init(load_testsuite),
Family::Enron => ENRON.get_or_init(load_enron),
Family::Synthetic => SYNTHETIC.get_or_init(load_synthetic),
}
}
}
pub fn get(name: &str) -> Option<&'static Corpus> {
Family::of(name)?
.corpora()
.iter()
.find(|corpus| corpus.name == name)
}
pub fn select(names: &[&str]) -> Vec<&'static Corpus> {
names.iter().filter_map(|name| get(name)).collect()
}
pub fn repository_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..")
}
pub fn corpora_root() -> PathBuf {
env::var_os(CORPORA_ENV).map_or_else(
|| repository_root().join("target").join("corpora"),
PathBuf::from,
)
}
pub fn corpus_dir(name: &str) -> PathBuf {
let dir = corpora_root().join(name);
if !dir.is_dir() {
eprintln!(
"corpus {name} not found in {}: skipped (run scripts/fetch-corpora.sh or set {CORPORA_ENV})",
dir.display()
);
}
dir
}
fn resources_dir() -> PathBuf {
repository_root().join("resources")
}
fn load_testsuite() -> Vec<Corpus> {
let samples = testsuite_samples();
Corpus::both_line_endings("testsuite", &samples).collect()
}
fn load_enron() -> Vec<Corpus> {
let samples = enron_samples(&corpus_dir(ENRON_MAILDIR), ENRON_PER_USER);
if samples.is_empty() {
return Vec::new();
}
vec![Corpus {
name: "enron-crlf".to_string(),
samples,
}]
}
fn load_synthetic() -> Vec<Corpus> {
let mut corpora = Vec::with_capacity(synthetic::NAMES.len() * LineEnding::ALL.len());
for (name, samples) in synthetic::NAMES.into_iter().zip(synthetic::generate()) {
corpora.extend(Corpus::both_line_endings(name, &samples));
}
corpora
}
fn read_dir_sorted(dir: &Path) -> Vec<PathBuf> {
let mut paths: Vec<_> = fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.path())
.collect();
paths.sort();
paths
}
fn load_sample(path: &Path, root: &Path, prefix: &str) -> Option<Sample> {
let relative = path.strip_prefix(root).unwrap_or(path).display();
let name = if prefix.is_empty() {
relative.to_string()
} else {
format!("{prefix}/{relative}")
};
fs::read(path).ok().map(|bytes| Sample { name, bytes })
}
fn testsuite_samples() -> Vec<Sample> {
let resources = resources_dir();
let eml = resources.join("eml");
let suites = TESTSUITE_SUITES
.iter()
.flat_map(|suite| read_dir_sorted(&eml.join(suite)))
.filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "eml"))
.filter_map(|path| load_sample(&path, &eml, ""));
let extra = [
(STALWART_SMTP, corpus_dir(STALWART_SMTP)),
(SIEVE_LABEL, resources.join(SIEVE_LABEL)),
]
.into_iter()
.flat_map(|(label, root)| {
read_dir_sorted(&root)
.into_iter()
.filter(|path| path.is_file())
.filter_map(move |path| load_sample(&path, &root, label))
});
suites.chain(extra).collect()
}
fn enron_samples(root: &Path, per_user: usize) -> Vec<Sample> {
let mut samples = Vec::with_capacity(per_user * 160);
for user in read_dir_sorted(root) {
let mut stack = vec![user];
let mut taken = 0;
while let Some(dir) = stack.pop() {
for entry in read_dir_sorted(&dir) {
if entry.is_dir() {
stack.push(entry);
} else if taken < per_user {
samples.extend(load_sample(&entry, root, ""));
taken += 1;
}
}
if taken >= per_user {
break;
}
}
}
samples
}
+463
View File
@@ -0,0 +1,463 @@
use super::Sample;
use std::{fmt::Write as _, ops::RangeInclusive};
pub(super) const NAMES: [&str; 6] = [
"attachments",
"newsletter",
"modern-headers",
"forwarded",
"dashes",
"plain-large",
];
const SEED: u64 = 0x9e37_79b9_7f4a_7c15;
const LINE_WIDTH: usize = 72;
const QP_WIDTH: usize = 75;
const BASE64_WIDTH: usize = 76;
const BASE64_ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const ATTACHMENT_SIZES: [(usize, usize); 3] =
[(400_000, 150_000), (60_000, 20_000), (2_000_000, 300_000)];
const FORWARD_DEPTHS: RangeInclusive<usize> = 1..=6;
const DASH_BOUNDARY: &str = "==dash-boundary==";
const DASH_PART_SIZE: usize = 200_000;
const PLAIN_LARGE_SIZE: usize = 1_000_000;
const HTML_HEAD: &str = "<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\">\n<style>\n:root { --brand-color: #0a66c2; --gap: 12px; }\n.button { color: var(--brand-color); margin: var(--gap); }\n</style>\n</head><body>\n";
const WORDS: &[&str] = &[
"the",
"quarterly",
"report",
"attached",
"please",
"review",
"meeting",
"tomorrow",
"budget",
"forecast",
"café",
"naïve",
"déjà",
"vu",
"résumé",
"日本語",
"über",
"schedule",
"project",
"deadline",
"update",
"customer",
"invoice",
"shipping",
"order",
"account",
"security",
"password",
"reset",
"team",
"lunch",
"Friday",
"regards",
"thanks",
"server",
"deploy",
"release",
"notes",
"feature",
"bug",
"fix",
"issue",
];
pub(super) fn generate() -> [Vec<Sample>; 6] {
let mut rng = Rng(SEED);
[
attachments(&mut rng),
newsletters(&mut rng),
modern_headers(&mut rng),
forwarded(&mut rng),
dashes(&mut rng),
plain_large(&mut rng),
]
}
struct Rng(u64);
impl Rng {
fn next_u64(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, limit: usize) -> usize {
(self.next_u64() % limit as u64) as usize
}
fn pick(&mut self, items: &[&'static str]) -> &'static str {
items
.get(self.below(items.len()))
.copied()
.unwrap_or_default()
}
fn bytes(&mut self, len: usize) -> Vec<u8> {
(0..len).map(|_| self.next_u64() as u8).collect()
}
}
fn push_sentence(out: &mut String, rng: &mut Rng, words: usize) {
for index in 0..words {
if index > 0 {
out.push(' ');
}
out.push_str(rng.pick(WORDS));
}
out.push('.');
}
fn wrapped_text(rng: &mut Rng, target: usize) -> String {
let mut out = String::with_capacity(target + 128);
let mut line = String::with_capacity(LINE_WIDTH + 16);
while out.len() < target {
let word = rng.pick(WORDS);
if line.len() + word.len() + 1 > LINE_WIDTH {
out.push_str(&line);
out.push('\n');
line.clear();
if rng.below(12) == 0 {
out.push('\n');
}
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
out.push_str(&line);
out.push('\n');
out
}
fn base64(bytes: &[u8]) -> String {
let mut encoded = Vec::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let word = chunk
.iter()
.zip([16u32, 8, 0])
.fold(0u32, |acc, (&byte, shift)| acc | u32::from(byte) << shift);
let symbols = chunk.len() + 1;
encoded.extend(
[18u32, 12, 6, 0]
.into_iter()
.enumerate()
.map(|(index, shift)| {
if index < symbols {
BASE64_ALPHABET
.get(((word >> shift) & 0x3f) as usize)
.copied()
.unwrap_or(b'=')
} else {
b'='
}
}),
);
}
let mut out = String::with_capacity(encoded.len() + encoded.len() / BASE64_WIDTH + 1);
for line in encoded.chunks(BASE64_WIDTH) {
out.extend(line.iter().copied().map(char::from));
out.push('\n');
}
out
}
fn quoted_printable(text: &str) -> String {
let mut out = String::with_capacity(text.len() * 5 / 4);
for line in text.split('\n') {
let mut column = 0;
for byte in line.bytes() {
let escaped = byte == b'=' || byte >= 0x80 || byte == b'\t';
let width = if escaped { 3 } else { 1 };
if column + width > QP_WIDTH {
out.push_str("=\n");
column = 0;
}
column += width;
if escaped {
let _ = write!(out, "={byte:02X}");
} else {
out.push(char::from(byte));
}
}
out.push('\n');
}
out
}
fn html(rng: &mut Rng, target: usize) -> String {
let mut out = String::with_capacity(target + 512);
out.push_str(HTML_HEAD);
while out.len() < target {
match rng.below(6) {
0 => {
let section = rng.below(1000);
let _ = writeln!(out, "<!-- section {section} -->");
}
1 => {
out.push_str("<table role=\"presentation\" style=\"width:100%;border-top:1px solid #eee\"><tr><td class=\"cell\">");
push_sentence(&mut out, rng, 12);
out.push_str("</td></tr></table>\n");
}
2 => {
let id = rng.next_u64();
let user = rng.next_u64();
let _ = write!(
out,
"<a class=\"button\" href=\"https://example.com/track?id={id}&amp;u={user}\">"
);
push_sentence(&mut out, rng, 3);
out.push_str("</a>\n");
}
3 => out.push_str("<hr style=\"border:0;border-top:1px dashed #ccc\">\n-----\n"),
_ => {
out.push_str("<p>");
push_sentence(&mut out, rng, 20);
out.push_str("</p>\n");
}
}
}
out.push_str("</body></html>\n");
out
}
fn envelope(rng: &mut Rng, subject: &str, received: usize, extra: &str) -> String {
let mut out = String::with_capacity(1024 + received * 256);
for hop in 0..received {
let ip = rng.below(255);
let id = rng.next_u64();
let minute = rng.below(60);
let second = rng.below(60);
let _ = write!(
out,
"Received: from mx{hop}.example.net (mx{hop}.example.net [192.0.2.{ip}])\n\tby relay{hop}.example.org (Postfix) with ESMTPS id {id:X}\n\tfor <user@example.org>; Tue, 3 Sep 2024 10:{minute:02}:{second:02} +0000\n"
);
}
let sender_name = rng.below(100);
let sender = rng.below(100);
let minute = rng.below(60);
let second = rng.below(60);
let id = rng.next_u64();
let _ = write!(
out,
"From: \"Sender {sender_name}\" <sender{sender}@example.com>\nTo: Recipient <user@example.org>, \"Another Person\" <another@example.org>\nSubject: {subject}\nDate: Tue, 3 Sep 2024 10:{minute:02}:{second:02} +0000\nMessage-ID: <{id:x}@example.com>\nMIME-Version: 1.0\n{extra}"
);
out
}
fn attachments(rng: &mut Rng) -> Vec<Sample> {
ATTACHMENT_SIZES
.into_iter()
.enumerate()
.map(|(index, (pdf_size, png_size))| {
let outer = format!("----=_Part_{index}_1634.1725357934");
let inner = format!("----=_Part_{}_1634.1725357934", index + 10);
let text = quoted_printable(&wrapped_text(rng, 4_000));
let page = quoted_printable(&html(rng, 30_000));
let mut out = envelope(
rng,
"Quarterly report",
4,
&format!("Content-Type: multipart/mixed; boundary=\"{outer}\"\n\nThis is a multi-part message in MIME format.\n\n"),
);
let _ = write!(
out,
"--{outer}\nContent-Type: multipart/alternative; boundary=\"{inner}\"\n\n--{inner}\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: quoted-printable\n\n{text}--{inner}\nContent-Type: text/html; charset=utf-8\nContent-Transfer-Encoding: quoted-printable\n\n{page}--{inner}--\n\n"
);
let pdf = base64(&rng.bytes(pdf_size));
let png = base64(&rng.bytes(png_size));
let _ = write!(
out,
"--{outer}\nContent-Type: application/pdf; name=\"report.pdf\"\nContent-Disposition: attachment; filename=\"report.pdf\"\nContent-Transfer-Encoding: base64\n\n{pdf}--{outer}\nContent-Type: image/png; name=\"photo.png\"\nContent-Disposition: inline; filename=\"photo.png\"\nContent-ID: <photo{index}@example.com>\nContent-Transfer-Encoding: base64\n\n{png}--{outer}--\n"
);
Sample {
name: format!("attachments-{index}"),
bytes: out.into_bytes(),
}
})
.collect()
}
fn newsletters(rng: &mut Rng) -> Vec<Sample> {
(0..6)
.map(|index| {
let boundary = format!("b1_{:x}", rng.next_u64());
let related = format!("b2_{:x}", rng.next_u64());
let mut text = wrapped_text(rng, 8_000 + index * 2_000);
text.push_str("-----\nUnsubscribe: https://example.com/u\n-- \nThe Newsletter Team\n");
let page = quoted_printable(&html(rng, 60_000 + index * 10_000));
let mut out = envelope(
rng,
"Your weekly digest",
3,
&format!("Content-Type: multipart/alternative; boundary=\"{boundary}\"\n\n"),
);
let logo = base64(&rng.bytes(12_000));
let _ = write!(
out,
"--{boundary}\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\n\n{text}\n--{boundary}\nContent-Type: multipart/related; boundary=\"{related}\"\n\n--{related}\nContent-Type: text/html; charset=utf-8\nContent-Transfer-Encoding: quoted-printable\n\n{page}\n--{related}\nContent-Type: image/gif; name=\"logo.gif\"\nContent-ID: <logo@example.com>\nContent-Transfer-Encoding: base64\n\n{logo}--{related}--\n\n--{boundary}--\n"
);
Sample {
name: format!("newsletter-{index}"),
bytes: out.into_bytes(),
}
})
.collect()
}
fn signature_block(rng: &mut Rng) -> String {
let mut out = String::with_capacity(6 * 68);
for _ in 0..6 {
let line = base64(&rng.bytes(48));
let _ = writeln!(out, "\t {}", line.trim_end());
}
out
}
fn modern_headers(rng: &mut Rng) -> Vec<Sample> {
(0..20)
.map(|index| {
let boundary = format!("000000000000{:x}", rng.next_u64());
let signature = signature_block(rng);
let arc_hash = base64(&rng.bytes(32));
let dkim_hash = base64(&rng.bytes(32));
let smtp_source = base64(&rng.bytes(40));
let smtp_id = rng.below(1_000_000);
let unsubscribe = rng.next_u64();
let extra = format!(
"ARC-Seal: i=1; a=rsa-sha256; t=1725357934; cv=none; d=example.com; s=arc-20240605;\n{signature}ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=example.com;\n\ts=arc-20240605; h=to:subject:message-id:date:from:mime-version:dkim-signature;\n\tbh={}=;\n{signature}ARC-Authentication-Results: i=1; mx.example.com;\n\tdkim=pass header.i=@example.com header.s=20230601 header.b=abc;\n\tspf=pass (example.com: domain of sender@example.com designates 192.0.2.1 as permitted sender) smtp.mailfrom=sender@example.com;\n\tdmarc=pass (p=NONE sp=QUARANTINE dis=NONE) header.from=example.com\nDKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=example.com; s=20230601; t=1725357934; x=1725962734;\n\th=to:subject:message-id:date:from:mime-version:from:to:cc:subject:date:message-id:reply-to;\n\tbh={}=;\n{signature}X-Google-Smtp-Source: {}\nX-Received: by 2002:a05:6512:3b0a with SMTP id f10mr{smtp_id} ; Tue, 03 Sep 2024 03:05:34 -0700 (PDT)\nList-Unsubscribe: <mailto:unsubscribe@example.com?subject=unsub>, <https://example.com/unsub/{unsubscribe:x}>\nList-Unsubscribe-Post: List-Unsubscribe=One-Click\nAuthentication-Results: mx.example.org; dkim=pass; spf=pass; dmarc=pass\nContent-Type: multipart/alternative; boundary=\"{boundary}\"\n\n",
arc_hash.trim_end(),
dkim_hash.trim_end(),
smtp_source.trim_end(),
);
let text = quoted_printable(&wrapped_text(rng, 1_500));
let page = quoted_printable(&html(rng, 6_000));
let mut subject = String::with_capacity(96);
push_sentence(&mut subject, rng, 6);
let mut out = envelope(rng, &subject, 6 + index % 4, &extra);
let _ = write!(
out,
"--{boundary}\nContent-Type: text/plain; charset=\"UTF-8\"\nContent-Transfer-Encoding: quoted-printable\n\n{text}\n--{boundary}\nContent-Type: text/html; charset=\"UTF-8\"\nContent-Transfer-Encoding: quoted-printable\n\n{page}\n--{boundary}--\n"
);
Sample {
name: format!("modern-headers-{index}"),
bytes: out.into_bytes(),
}
})
.collect()
}
fn nested_message(rng: &mut Rng, depth: usize) -> String {
let mut out = String::new();
let mut boundaries = Vec::with_capacity(depth + 1);
for level in (0..=depth).rev() {
let boundary = format!("fwd-{level}-{:x}", rng.next_u64());
out.push_str(&envelope(
rng,
&format!("Fwd: level {level}"),
2,
&format!("Content-Type: multipart/mixed; boundary=\"{boundary}\"\n\n"),
));
let text = wrapped_text(rng, 1_500);
let _ = write!(
out,
"--{boundary}\nContent-Type: text/plain; charset=utf-8\n\n{text}\n"
);
if level == 0 {
let alternative = format!("alt-{:x}", rng.next_u64());
let plain = wrapped_text(rng, 2_000);
let page = html(rng, 5_000);
let _ = write!(
out,
"--{boundary}\nContent-Type: multipart/alternative; boundary=\"{alternative}\"\n\n--{alternative}\nContent-Type: text/plain; charset=utf-8\n\n{plain}\n--{alternative}\nContent-Type: text/html; charset=utf-8\n\n{page}\n--{alternative}--\n\n"
);
} else {
let _ = write!(
out,
"--{boundary}\nContent-Type: message/rfc822\nContent-Disposition: inline\n\n"
);
}
boundaries.push(boundary);
}
for (index, boundary) in boundaries.iter().rev().enumerate() {
if index > 0 {
out.push('\n');
}
let _ = writeln!(out, "--{boundary}--");
}
out
}
fn forwarded(rng: &mut Rng) -> Vec<Sample> {
FORWARD_DEPTHS
.map(|depth| Sample {
name: format!("forwarded-{depth}"),
bytes: nested_message(rng, depth).into_bytes(),
})
.collect()
}
fn dashes(rng: &mut Rng) -> Vec<Sample> {
let mut out = envelope(
rng,
"Patch review",
2,
&format!("Content-Type: multipart/mixed; boundary=\"{DASH_BOUNDARY}\"\n\n"),
);
for part in 0..3 {
let _ = write!(
out,
"--{DASH_BOUNDARY}\nContent-Type: text/plain; charset=utf-8\nContent-Disposition: attachment; filename=\"part{part}.diff\"\n\n"
);
let start = out.len();
while out.len() - start < DASH_PART_SIZE {
match rng.below(10) {
0 => out.push_str("-- SELECT * FROM accounts WHERE id = 42;\n"),
1 => out.push_str("--- a/src/lib.rs\n+++ b/src/lib.rs\n"),
2 => {
let _ = writeln!(out, "--{DASH_BOUNDARY}x not a delimiter");
}
3 => out.push_str("-----\n"),
_ => {
push_sentence(&mut out, rng, 10);
out.push('\n');
}
}
}
}
let _ = writeln!(out, "--{DASH_BOUNDARY}--");
vec![Sample {
name: "dashes".to_string(),
bytes: out.into_bytes(),
}]
}
fn plain_large(rng: &mut Rng) -> Vec<Sample> {
let mut body = String::with_capacity(PLAIN_LARGE_SIZE + 4_096);
while body.len() < PLAIN_LARGE_SIZE {
body.push_str(&wrapped_text(rng, 2_000));
body.push_str("-----Original Message-----\n-- \nSent from my phone\n");
}
let mut out = envelope(
rng,
"Long thread",
3,
"Content-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\n\n",
);
out.push_str(&body);
vec![Sample {
name: "plain-large".to_string(),
bytes: out.into_bytes(),
}]
}
+68
View File
@@ -0,0 +1,68 @@
#![allow(unsafe_code)]
use crate::{tally::Tally, workload::Workload};
use std::{hint::black_box, sync::Once};
type Entry = unsafe extern "C" fn(*const u8, usize, *mut Tally) -> i32;
unsafe extern "C" {
fn cmp_gmime_init();
fn cmp_gmime_structure(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_gmime_headers(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_gmime_full(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_vmime_structure(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_vmime_headers(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_vmime_full(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_libetpan_structure(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_libetpan_headers(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_libetpan_full(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_dovecot_init();
fn cmp_dovecot_structure(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_dovecot_headers(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
fn cmp_dovecot_full(raw: *const u8, len: usize, tally: *mut Tally) -> i32;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Native {
Gmime,
Vmime,
Libetpan,
Dovecot,
}
static GMIME_INIT: Once = Once::new();
static DOVECOT_INIT: Once = Once::new();
impl Native {
fn entry(self, workload: Workload) -> Entry {
match (self, workload) {
(Native::Gmime, Workload::Structure) => cmp_gmime_structure,
(Native::Gmime, Workload::Headers) => cmp_gmime_headers,
(Native::Gmime, Workload::Full) => cmp_gmime_full,
(Native::Vmime, Workload::Structure) => cmp_vmime_structure,
(Native::Vmime, Workload::Headers) => cmp_vmime_headers,
(Native::Vmime, Workload::Full) => cmp_vmime_full,
(Native::Libetpan, Workload::Structure) => cmp_libetpan_structure,
(Native::Libetpan, Workload::Headers) => cmp_libetpan_headers,
(Native::Libetpan, Workload::Full) => cmp_libetpan_full,
(Native::Dovecot, Workload::Structure) => cmp_dovecot_structure,
(Native::Dovecot, Workload::Headers) => cmp_dovecot_headers,
(Native::Dovecot, Workload::Full) => cmp_dovecot_full,
}
}
fn init(self) {
match self {
Native::Gmime => GMIME_INIT.call_once(|| unsafe { cmp_gmime_init() }),
Native::Dovecot => DOVECOT_INIT.call_once(|| unsafe { cmp_dovecot_init() }),
Native::Vmime | Native::Libetpan => {}
}
}
}
pub fn run(native: Native, workload: Workload, raw: &[u8], tally: &mut Tally) -> bool {
native.init();
let entry = native.entry(workload);
let raw = black_box(raw);
unsafe { entry(raw.as_ptr(), raw.len(), tally) != 0 }
}
+121
View File
@@ -0,0 +1,121 @@
use crate::{tally::Tally, workload::Workload};
use ::mailparse::{
MailAddr, MailHeaderMap, ParsedMail, addrparse_header, dateparse, msgidparse, parse_mail,
};
use std::hint::black_box;
const MAX_NESTING: usize = 8;
pub fn run(workload: Workload, raw: &[u8], tally: &mut Tally) -> bool {
let Ok(mail) = parse_mail(black_box(raw)) else {
return false;
};
if workload == Workload::Headers {
headers(&mail, tally);
}
walk(&mail, workload, tally);
true
}
fn media_type<'a>(mail: &'a ParsedMail<'_>) -> (&'a str, Option<&'a str>) {
mail.ctype
.mimetype
.split_once('/')
.map_or((mail.ctype.mimetype.as_str(), None), |(ctype, subtype)| {
(ctype, Some(subtype))
})
}
fn headers(mail: &ParsedMail<'_>, tally: &mut Tally) {
let headers = &mail.headers;
if let Some(subject) = headers.get_first_value("Subject") {
tally.subject += 1;
tally.text(&subject);
}
if let Some(from) = headers
.get_first_header("From")
.and_then(|header| addrparse_header(header).ok())
&& let Some(mailbox) = from.iter().find_map(|addr| match addr {
MailAddr::Single(info) => Some(info),
MailAddr::Group(group) => group.addrs.first(),
})
{
tally.from += 1;
tally.maybe_text(mailbox.display_name.as_deref());
tally.text(&mailbox.addr);
}
if let Some(date) = headers
.get_first_value("Date")
.and_then(|date| dateparse(&date).ok())
{
tally.date += 1;
tally.add(date as u64);
}
if let Some(ids) = headers
.get_first_value("Message-ID")
.and_then(|value| msgidparse(&value).ok())
&& let Some(id) = ids.first()
{
tally.message_id += 1;
tally.text(id);
}
}
fn walk(mail: &ParsedMail<'_>, workload: Workload, tally: &mut Tally) {
tally.messages += 1;
let mut nested = Vec::new();
walk_tree(mail, workload, 0, tally, &mut nested);
while let Some((bytes, depth)) = nested.pop() {
match parse_mail(&bytes) {
Ok(mail) => {
tally.messages += 1;
walk_tree(&mail, workload, depth, tally, &mut nested);
}
Err(_) => tally.failures += 1,
}
}
}
fn walk_tree(
mail: &ParsedMail<'_>,
workload: Workload,
depth: usize,
tally: &mut Tally,
nested: &mut Vec<(Vec<u8>, usize)>,
) {
let mut stack = vec![mail];
while let Some(part) = stack.pop() {
tally.parts += 1;
let (ctype, subtype) = media_type(part);
if workload == Workload::Structure {
tally.content_type(ctype, subtype);
}
if !part.subparts.is_empty() || ctype == "multipart" {
stack.extend(part.subparts.iter().rev());
} else if ctype == "message"
&& matches!(subtype, Some("rfc822" | "global"))
&& depth < MAX_NESTING
{
match part.get_body_raw() {
Ok(bytes) => nested.push((bytes, depth + 1)),
Err(_) => tally.failures += 1,
}
} else if workload == Workload::Full {
leaf(part, ctype, tally);
}
}
}
fn leaf(part: &ParsedMail<'_>, ctype: &str, tally: &mut Tally) {
if ctype == "text" {
match part.get_body() {
Ok(text) => tally.leaf(text.as_bytes(), true),
Err(_) => tally.failures += 1,
}
} else {
match part.get_body_raw() {
Ok(bytes) => tally.leaf(&bytes, false),
Err(_) => tally.failures += 1,
}
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod mailparse;
pub mod v011;
pub mod v1;
+66
View File
@@ -0,0 +1,66 @@
use crate::{tally::Tally, workload::Workload};
use mail_parser_011::{Message, MessageParser, MimeHeaders, PartType};
use std::hint::black_box;
pub fn run(parser: &MessageParser, workload: Workload, raw: &[u8], tally: &mut Tally) -> bool {
let Some(message) = parser.parse(black_box(raw)) else {
return false;
};
match workload {
Workload::Structure => for_each_message(&message, tally, structure),
Workload::Headers => headers(&message, tally),
Workload::Full => for_each_message(&message, tally, full),
}
true
}
fn for_each_message(message: &Message<'_>, tally: &mut Tally, visit: fn(&Message<'_>, &mut Tally)) {
tally.messages += 1;
visit(message, tally);
for part in &message.parts {
if let PartType::Message(nested) = &part.body {
for_each_message(nested, tally, visit);
}
}
}
fn structure(message: &Message<'_>, tally: &mut Tally) {
for part in &message.parts {
tally.parts += 1;
if let Some(content_type) = part.content_type() {
tally.content_type(content_type.ctype(), content_type.subtype());
}
}
}
fn headers(message: &Message<'_>, tally: &mut Tally) {
tally.messages += 1;
if let Some(subject) = message.subject() {
tally.subject += 1;
tally.text(subject);
}
if let Some(addr) = message.from().and_then(|from| from.first()) {
tally.from += 1;
tally.maybe_text(addr.name.as_deref());
tally.maybe_text(addr.address.as_deref());
}
if let Some(date) = message.date() {
tally.date += 1;
tally.add(date.to_timestamp() as u64);
}
if let Some(id) = message.message_id() {
tally.message_id += 1;
tally.text(id);
}
}
fn full(message: &Message<'_>, tally: &mut Tally) {
for part in &message.parts {
tally.parts += 1;
match &part.body {
PartType::Text(text) | PartType::Html(text) => tally.leaf(text.as_bytes(), true),
PartType::Binary(bytes) | PartType::InlineBinary(bytes) => tally.leaf(bytes, false),
PartType::Message(_) | PartType::Multipart(_) => {}
}
}
}
+61
View File
@@ -0,0 +1,61 @@
use crate::{tally::Tally, workload::Workload};
use mail_parser::{Message, MessageParser, PartKind};
use std::hint::black_box;
pub fn run(parser: &MessageParser, workload: Workload, raw: &[u8], tally: &mut Tally) -> bool {
let Some(message) = parser.parse(black_box(raw)) else {
return false;
};
match workload {
Workload::Structure => structure(&message, tally),
Workload::Headers => headers(&message, tally),
Workload::Full => full(&message, tally),
}
true
}
fn structure(message: &Message<'_>, tally: &mut Tally) {
tally.messages += message.messages().len() as u64;
for part in message.parts() {
tally.parts += 1;
if let Some(content_type) = part.content_type() {
tally.content_type(content_type.ctype(), content_type.subtype());
}
}
}
fn headers(message: &Message<'_>, tally: &mut Tally) {
tally.messages += 1;
if let Some(subject) = message.subject() {
tally.subject += 1;
tally.text(subject);
}
if let Some(mailbox) = message.from().and_then(|from| from.first()) {
tally.from += 1;
tally.maybe_text(mailbox.name());
tally.maybe_text(mailbox.address());
}
if let Some(date) = message.date() {
tally.date += 1;
tally.add(date.to_timestamp() as u64);
}
if let Some(id) = message.message_id() {
tally.message_id += 1;
tally.text(id);
}
}
fn full(message: &Message<'_>, tally: &mut Tally) {
tally.messages += message.messages().len() as u64;
for part in message.parts() {
tally.parts += 1;
match part.kind() {
PartKind::Text | PartKind::Html => match part.text() {
Some(text) => tally.leaf(text.as_bytes(), true),
None => tally.failures += 1,
},
PartKind::Binary | PartKind::InlineBinary => tally.leaf(&part.decoded(), false),
PartKind::Multipart | PartKind::Message(_) => {}
}
}
}
+25
View File
@@ -0,0 +1,25 @@
pub mod corpus;
pub mod ffi;
pub mod impls;
pub mod tally;
pub mod workload;
use corpus::Corpus;
pub fn bench_corpora() -> Vec<&'static Corpus> {
let corpora = corpus::select(corpus::BENCH);
for name in missing_bench_corpora(&corpora) {
eprintln!(
"warning: corpus {name} is not available (run scripts/fetch-corpora.sh or set {})",
corpus::CORPORA_ENV
);
}
corpora
}
pub fn missing_bench_corpora(corpora: &[&Corpus]) -> impl Iterator<Item = &'static str> {
corpus::BENCH
.iter()
.copied()
.filter(|name| !corpora.iter().any(|corpus| corpus.name == *name))
}
+129
View File
@@ -0,0 +1,129 @@
use std::{hint::black_box, ops::AddAssign};
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Tally {
pub digest: u64,
pub messages: u64,
pub parts: u64,
pub leaves: u64,
pub text_leaves: u64,
pub decoded_bytes: u64,
pub text_bytes: u64,
pub failures: u64,
pub subject: u64,
pub from: u64,
pub date: u64,
pub message_id: u64,
}
impl Tally {
pub fn add(&mut self, value: u64) {
self.digest = self.digest.rotate_left(5) ^ value;
}
pub fn bytes(&mut self, bytes: &[u8]) {
self.add(black_box(bytes).len() as u64);
}
pub fn text(&mut self, text: &str) {
self.bytes(text.as_bytes());
}
pub fn maybe_text(&mut self, text: Option<&str>) {
if let Some(text) = text {
self.text(text);
}
}
pub fn content_type(&mut self, ctype: &str, subtype: Option<&str>) {
self.text(ctype);
self.maybe_text(subtype);
}
pub fn leaf(&mut self, bytes: &[u8], text: bool) {
let len = black_box(bytes).len() as u64;
self.leaves += 1;
self.decoded_bytes += len;
if text {
self.text_leaves += 1;
self.text_bytes += len;
}
self.add(len);
}
pub fn fields(&self) -> [u64; 12] {
[
self.digest,
self.messages,
self.parts,
self.leaves,
self.text_leaves,
self.decoded_bytes,
self.text_bytes,
self.failures,
self.subject,
self.from,
self.date,
self.message_id,
]
}
pub fn from_fields(fields: [u64; 12]) -> Tally {
let [
digest,
messages,
parts,
leaves,
text_leaves,
decoded_bytes,
text_bytes,
failures,
subject,
from,
date,
message_id,
] = fields;
Tally {
digest,
messages,
parts,
leaves,
text_leaves,
decoded_bytes,
text_bytes,
failures,
subject,
from,
date,
message_id,
}
}
pub fn finish(&self) -> u64 {
black_box(
self.digest
^ self.parts.rotate_left(8)
^ self.leaves.rotate_left(16)
^ self.decoded_bytes.rotate_left(24)
^ self.messages.rotate_left(40),
)
}
}
impl AddAssign for Tally {
fn add_assign(&mut self, other: Tally) {
self.digest = self.digest.wrapping_add(other.digest);
self.messages += other.messages;
self.parts += other.parts;
self.leaves += other.leaves;
self.text_leaves += other.text_leaves;
self.decoded_bytes += other.decoded_bytes;
self.text_bytes += other.text_bytes;
self.failures += other.failures;
self.subject += other.subject;
self.from += other.from;
self.date += other.date;
self.message_id += other.message_id;
}
}
+135
View File
@@ -0,0 +1,135 @@
use crate::{
corpus::Corpus,
ffi::{self, Native},
impls,
tally::Tally,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Workload {
Structure,
Headers,
Full,
}
impl Workload {
pub const ALL: [Workload; 3] = [Workload::Structure, Workload::Headers, Workload::Full];
pub fn name(self) -> &'static str {
match self {
Workload::Structure => "structure",
Workload::Headers => "headers",
Workload::Full => "full",
}
}
pub fn from_name(name: &str) -> Option<Workload> {
Workload::ALL
.into_iter()
.find(|workload| workload.name() == name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Implementation {
MailParser,
MailParser011,
Mailparse,
Gmime,
Vmime,
Libetpan,
Dovecot,
}
impl Implementation {
pub const ALL: [Implementation; 7] = [
Implementation::MailParser,
Implementation::MailParser011,
Implementation::Mailparse,
Implementation::Gmime,
Implementation::Vmime,
Implementation::Libetpan,
Implementation::Dovecot,
];
pub const REFERENCE: Implementation = Implementation::MailParser;
pub fn name(self) -> &'static str {
match self {
Implementation::MailParser => "mail-parser-1.0",
Implementation::MailParser011 => "mail-parser-0.11",
Implementation::Mailparse => "mailparse",
Implementation::Gmime => "gmime",
Implementation::Vmime => "vmime",
Implementation::Libetpan => "libetpan",
Implementation::Dovecot => "dovecot",
}
}
pub fn from_name(name: &str) -> Option<Implementation> {
Implementation::ALL
.into_iter()
.find(|implementation| implementation.name() == name)
}
pub fn is_native(self) -> bool {
self.native().is_some()
}
fn native(self) -> Option<Native> {
match self {
Implementation::Gmime => Some(Native::Gmime),
Implementation::Vmime => Some(Native::Vmime),
Implementation::Libetpan => Some(Native::Libetpan),
Implementation::Dovecot => Some(Native::Dovecot),
Implementation::MailParser
| Implementation::MailParser011
| Implementation::Mailparse => None,
}
}
}
#[derive(Default)]
pub struct Parsers {
v1: mail_parser::MessageParser,
v011: mail_parser_011::MessageParser,
}
impl Parsers {
pub fn run(
&self,
implementation: Implementation,
workload: Workload,
raw: &[u8],
tally: &mut Tally,
) -> bool {
match implementation {
Implementation::MailParser => impls::v1::run(&self.v1, workload, raw, tally),
Implementation::MailParser011 => impls::v011::run(&self.v011, workload, raw, tally),
Implementation::Mailparse => impls::mailparse::run(workload, raw, tally),
Implementation::Gmime
| Implementation::Vmime
| Implementation::Libetpan
| Implementation::Dovecot => implementation
.native()
.is_some_and(|native| ffi::run(native, workload, raw, tally)),
}
}
pub fn digest(&self, implementation: Implementation, workload: Workload, raw: &[u8]) -> u64 {
let mut tally = Tally::default();
self.run(implementation, workload, raw, &mut tally);
tally.finish()
}
pub fn run_corpus(
&self,
implementation: Implementation,
workload: Workload,
corpus: &Corpus,
) -> u64 {
corpus.samples.iter().fold(0u64, |digest, sample| {
digest.wrapping_add(self.digest(implementation, workload, &sample.bytes))
})
}
}
+254
View File
@@ -0,0 +1,254 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")"
VENDOR=$(pwd)
BUILD="$VENDOR/build"
PREFIX="$VENDOR/prefix"
LOGS="$VENDOR/logs"
DOWNLOADS="$VENDOR/downloads"
OPT=-O3
JOBS=${JOBS:-8}
BUILD_TIME_LIMIT=${BUILD_TIME_LIMIT:-10800}
case "$(uname -s)" in
Darwin)
CC=${CC:-/usr/bin/clang}
CXX=${CXX:-/usr/bin/clang++}
if [ -z "${HOMEBREW_PREFIX:-}" ]; then
HOMEBREW_PREFIX=/opt/homebrew
if [ ! -d "$HOMEBREW_PREFIX/opt/glib" ] && [ -d /usr/local/opt/glib ]; then
HOMEBREW_PREFIX=/usr/local
fi
fi
GLIB=${GLIB_PREFIX:-$HOMEBREW_PREFIX/opt/glib}
GETTEXT=${GETTEXT_PREFIX:-$HOMEBREW_PREFIX/opt/gettext}
OPENSSL_PREFIX=${OPENSSL_PREFIX:-$HOMEBREW_PREFIX/opt/openssl@3}
GLIB_CFLAGS="-I$GLIB/include/glib-2.0 -I$GLIB/lib/glib-2.0/include -I$GETTEXT/include"
GLIB_LIBS="-L$GLIB/lib -lgio-2.0 -lgobject-2.0 -lgmodule-2.0 -lglib-2.0 -L$GETTEXT/lib -lintl"
;;
*)
CC=${CC:-cc}
CXX=${CXX:-c++}
OPENSSL_PREFIX=${OPENSSL_PREFIX:-}
GLIB_CFLAGS=$(pkg-config --cflags gio-2.0 gmodule-2.0)
GLIB_LIBS=$(pkg-config --libs gio-2.0 gmodule-2.0)
;;
esac
GMIME_VERSION=3.2.15
GMIME_TARBALL=gmime-$GMIME_VERSION.tar.xz
GMIME_URL=https://github.com/jstedfast/gmime/releases/download/$GMIME_VERSION/$GMIME_TARBALL
GMIME_SHA256=84cd2a481a27970ec39b5c95f72db026722904a2ccf3fdbd57b280cf2d02b5c4
VMIME_COMMIT=5b0191136f84c177b737c9cf9aa7cf59d1c65ef1
VMIME_TARBALL=vmime-5b0191136f84.tar.gz
VMIME_URL=https://github.com/kisli/vmime/archive/$VMIME_COMMIT.tar.gz
VMIME_SHA256=41d31b91f436d3ffbb4c5bc339770dadb35a53425bf22f36b593d196f02c0c56
LIBETPAN_VERSION=1.10.1
LIBETPAN_TARBALL=libetpan-$LIBETPAN_VERSION.tar.gz
LIBETPAN_URL=https://github.com/dinhvh/libetpan/archive/refs/tags/$LIBETPAN_VERSION.tar.gz
LIBETPAN_SHA256=87bacdc62661a2a7aa5fe9f1f28d2f7c7a53256633ac5129903916c59f80c4c2
DOVECOT_VERSION=2.4.5
DOVECOT_TARBALL=dovecot-$DOVECOT_VERSION.tar.gz
DOVECOT_URL=https://dovecot.org/releases/2.4/$DOVECOT_TARBALL
DOVECOT_SHA256=868c2686a61b5f8e00a3e4721789b1ab46e6528fd773a5fbed07a6ecba7731e6
step() {
if [ -n "${BUILD_WRAP:-}" ]; then
"$BUILD_WRAP" perl -e 'alarm shift; exec @ARGV' "$BUILD_TIME_LIMIT" "$@"
else
"$@"
fi
}
sha256() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$1"
else
shasum -a 256 "$1"
fi | cut -d ' ' -f 1
}
fetch() {
file="$DOWNLOADS/$1"
if [ ! -f "$file" ]; then
curl -fsSL -m 300 -o "$file.part" "$2"
mv "$file.part" "$file"
fi
actual=$(sha256 "$file")
if [ "$actual" != "$3" ]; then
echo "checksum mismatch for $1: expected $3, got $actual" >&2
exit 1
fi
echo "verified $1"
}
only=${1:-all}
case "$only" in
all | gmime | vmime | libetpan | dovecot) ;;
*)
echo "usage: $0 [all|gmime|vmime|libetpan|dovecot]" >&2
exit 2
;;
esac
mkdir -p "$DOWNLOADS" "$BUILD" "$PREFIX" "$LOGS"
fetch "$GMIME_TARBALL" "$GMIME_URL" "$GMIME_SHA256"
fetch "$VMIME_TARBALL" "$VMIME_URL" "$VMIME_SHA256"
fetch "$LIBETPAN_TARBALL" "$LIBETPAN_URL" "$LIBETPAN_SHA256"
fetch "$DOVECOT_TARBALL" "$DOVECOT_URL" "$DOVECOT_SHA256"
build_gmime() {
src="$BUILD/gmime-$GMIME_VERSION"
rm -rf "$src" "$PREFIX/gmime"
step tar -xJf "$DOWNLOADS/$GMIME_TARBALL" -C "$BUILD"
cd "$src"
step ./configure --prefix="$PREFIX/gmime" \
CC="$CC" CFLAGS="$OPT" \
GLIB_CFLAGS="$GLIB_CFLAGS" GLIB_LIBS="$GLIB_LIBS" \
ZLIB_CFLAGS=" " ZLIB_LIBS="-lz" \
--disable-crypto --without-libidn --enable-introspection=no --enable-vala=no \
--disable-gtk-doc --enable-static --disable-shared --disable-dependency-tracking \
> "$LOGS/gmime-configure.log" 2>&1
step make -j"$JOBS" -C util > "$LOGS/gmime-make.log" 2>&1
step make -j"$JOBS" -C gmime >> "$LOGS/gmime-make.log" 2>&1
step make -C gmime install >> "$LOGS/gmime-make.log" 2>&1
cd "$VENDOR"
echo "gmime $GMIME_VERSION: $PREFIX/gmime"
}
build_vmime() {
src="$BUILD/vmime-$VMIME_COMMIT"
out="$BUILD/vmime-build"
rm -rf "$src" "$out" "$PREFIX/vmime"
step tar -xzf "$DOWNLOADS/$VMIME_TARBALL" -C "$BUILD"
mkdir -p "$out"
step cmake -S "$src" -B "$out" -G "Unix Makefiles" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_C_COMPILER="$CC" -DCMAKE_CXX_COMPILER="$CXX" \
-DCMAKE_CXX_FLAGS_RELEASE="$OPT -DNDEBUG" \
-DCMAKE_INSTALL_PREFIX="$PREFIX/vmime" \
-DCMAKE_INSTALL_LIBDIR=lib \
-DVMIME_BUILD_SHARED_LIBRARY=OFF -DVMIME_BUILD_STATIC_LIBRARY=ON \
-DVMIME_HAVE_MESSAGING_FEATURES=OFF -DVMIME_HAVE_SASL_SUPPORT=OFF \
-DVMIME_HAVE_TLS_SUPPORT=OFF -DVMIME_CHARSETCONV_LIB=iconv \
-DVMIME_BUILD_SAMPLES=OFF -DVMIME_BUILD_TESTS=OFF -DVMIME_BUILD_DOCUMENTATION=OFF \
> "$LOGS/vmime-cmake.log" 2>&1
step make -j"$JOBS" -C "$out" install > "$LOGS/vmime-make.log" 2>&1
echo "vmime $VMIME_COMMIT: $PREFIX/vmime"
}
LIBETPAN_SOURCES="
src/low-level/imf/mailimf.c
src/low-level/imf/mailimf_types.c
src/low-level/imf/mailimf_types_helper.c
src/low-level/imf/mailimf_write_file.c
src/low-level/imf/mailimf_write_generic.c
src/low-level/imf/mailimf_write_mem.c
src/low-level/mime/mailmime.c
src/low-level/mime/mailmime_content.c
src/low-level/mime/mailmime_decode.c
src/low-level/mime/mailmime_disposition.c
src/low-level/mime/mailmime_types.c
src/low-level/mime/mailmime_types_helper.c
src/low-level/mime/mailmime_write_file.c
src/low-level/mime/mailmime_write_generic.c
src/low-level/mime/mailmime_write_mem.c
src/data-types/base64.c
src/data-types/carray.c
src/data-types/charconv.c
src/data-types/chash.c
src/data-types/clist.c
src/data-types/mmapstring.c
src/data-types/timeutils.c
"
build_libetpan() {
src="$BUILD/libetpan-$LIBETPAN_VERSION"
include="$PREFIX/libetpan/include/libetpan"
objects="$BUILD/libetpan-objects"
rm -rf "$src" "$objects" "$PREFIX/libetpan"
step tar -xzf "$DOWNLOADS/$LIBETPAN_TARBALL" -C "$BUILD"
cd "$src"
step tar -xzf build-mac/autogen-result.tar.gz
step ./configure CC="$CC" CFLAGS="$OPT" \
--disable-db --without-openssl --without-gnutls --without-sasl \
--with-curl=no --with-expat=no --without-zlib --disable-lockfile \
--disable-dependency-tracking \
> "$LOGS/libetpan-configure.log" 2>&1 || true
test -f config.h
mkdir -p "$include" "$PREFIX/libetpan/lib" "$objects"
step sh -c '"$1" -E -I. - < libetpan-config.h.in' sh "$CC" \
| sed -e '/^#/d;/^[ \t]*$/d;s/^@/#/' > "$include/libetpan-config.h"
cp src/low-level/imf/*.h src/low-level/mime/*.h src/data-types/*.h "$include/"
step sh -c '
set -e
src=$1 objects=$2 include=$3 cc=$4 opt=$5
shift 5
cd "$src"
for file in "$@"; do
"$cc" $opt -DHAVE_CONFIG_H -I. -iquote "$include" -I"$include/.." \
-Isrc/low-level/imf -Isrc/low-level/mime -Isrc/data-types \
-c "$file" -o "$objects/$(basename "$file" .c).o"
done
' sh "$src" "$objects" "$include" "$CC" "$OPT" $LIBETPAN_SOURCES \
> "$LOGS/libetpan-make.log" 2>&1
step ar rcs "$PREFIX/libetpan/lib/libetpan-mime.a" "$objects"/*.o
cd "$VENDOR"
echo "libetpan $LIBETPAN_VERSION: $PREFIX/libetpan"
}
DOVECOT_LIBS="lib:lib charset:lib-charset mail:lib-mail"
build_dovecot() {
src="$BUILD/dovecot-$DOVECOT_VERSION"
include="$PREFIX/dovecot/include"
rm -rf "$src" "$PREFIX/dovecot"
step tar -xzf "$DOWNLOADS/$DOVECOT_TARBALL" -C "$BUILD"
cd "$src"
openssl_cppflags=
openssl_ldflags=
if [ -n "$OPENSSL_PREFIX" ]; then
openssl_cppflags="-I$OPENSSL_PREFIX/include"
openssl_ldflags="-L$OPENSSL_PREFIX/lib"
fi
step ./configure CC="$CC" CFLAGS="$OPT" \
CPPFLAGS="$openssl_cppflags" LDFLAGS="$openssl_ldflags" \
ZLIB_CFLAGS=" " ZLIB_LIBS=-lz am_cv_func_iconv_works=yes \
--enable-static --disable-shared --without-shared-libs \
--without-pam --without-bsdauth --without-gssapi --without-ldap --without-libunwind \
--without-cdb --without-sql --without-pgsql --without-mysql --without-sqlite \
--without-cassandra --without-stemmer --without-textcat --without-icu \
--without-pcre2 --without-solr --without-flatcurve --without-sodium --without-bzlib \
--without-lz4 --without-zstd --without-libcap --without-lua \
--disable-dependency-tracking \
> "$LOGS/dovecot-configure.log" 2>&1
: > "$LOGS/dovecot-make.log"
mkdir -p "$include" "$PREFIX/dovecot/lib"
cp config.h "$include/"
for entry in $DOVECOT_LIBS; do
name=${entry%%:*}
dir=src/${entry#*:}
step make -j"$JOBS" -C "$dir" "lib$name.la" >> "$LOGS/dovecot-make.log" 2>&1
cp "$dir/.libs/lib$name.a" "$PREFIX/dovecot/lib/libdovecot-$name.a"
cp "$dir"/*.h "$include/"
done
cd "$VENDOR"
echo "dovecot $DOVECOT_VERSION: $PREFIX/dovecot"
}
case "$only" in
gmime) build_gmime ;;
vmime) build_vmime ;;
libetpan) build_libetpan ;;
dovecot) build_dovecot ;;
all)
build_gmime
build_vmime
build_libetpan
build_dovecot
;;
esac
+74
View File
@@ -0,0 +1,74 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use mail_parser::html_to_text;
use std::{hint::black_box, time::Duration};
const SIZES: [(&str, usize); 3] = [("4k", 4 << 10), ("64k", 64 << 10), ("1m", 1 << 20)];
const HEAD: &str = "<html><head><meta charset=\"utf-8\"><title>Weekly</title>\
<style type=\"text/css\">body{margin:0}td{padding:0 8px;font-family:Arial,sans-serif}</style>\
</head><body class=\"main\">";
const TAIL: &str = "</body></html>";
const NEWSLETTER: &[&str] = &[
"<table role=\"presentation\" width=\"100%\" cellpadding=\"0\"><tr>\
<td style=\"padding:0 8px;color:#333\" class=\"c1\"><a href=\"https://example.com/item?id=42&amp;src=mail\" \
title='Open item'><b>New</b> arrivals this week</a> for you &amp; your team</td></tr></table>\n",
"<p class=\"intro\" style=\"margin:0 0 12px 0\">Hello <b>Jane</b>, here is what changed since \
your last visit.<br>See <a href=\"https://example.com/a\">the full list</a> online.</p>\n",
"<img src=\"https://example.com/logo.png\" alt=\"Logo > brand\" width=\"120\" height=\"40\">\n",
"<div><span style=\"font-size:14px\">Prices start at 10&euro; and ship in 2&ndash;3 days.</span></div>\n",
"<!--[if mso]><table><tr><td><![endif]--><p>Questions? Reply to this message.</p>\n",
];
const PLAIN: &[&str] = &[
"<p>The quick brown fox jumps over the lazy dog, and then keeps running down the road.</p>\n",
"<p>Plain paragraphs with few tags and no attributes at all, mostly text.<br>Second line.</p>\n",
];
fn document(blocks: &[&str], size: usize) -> String {
let mut html = String::with_capacity(size + HEAD.len() + TAIL.len() + 512);
html.push_str(HEAD);
for block in blocks.iter().cycle() {
if html.len() >= size {
break;
}
html.push_str(block);
}
html.push_str(TAIL);
html
}
fn html(c: &mut Criterion) {
let mut group = c.benchmark_group("html_to_text");
for (kind, blocks) in [("newsletter", NEWSLETTER), ("plain", PLAIN)] {
for (size_name, size) in SIZES {
let input = document(blocks, size);
group.throughput(Throughput::Bytes(input.len() as u64));
group.bench_function(BenchmarkId::new(kind, size_name), |b| {
b.iter(|| html_to_text(black_box(&input)))
});
}
}
group.finish();
}
fn config() -> Criterion {
Criterion::default()
.warm_up_time(Duration::from_secs(1))
.measurement_time(Duration::from_secs(3))
.sample_size(50)
.noise_threshold(0.02)
}
criterion_group! {
name = benches;
config = config();
targets = html
}
criterion_main!(benches);
+303
View File
@@ -0,0 +1,303 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
#[path = "support/corpus.rs"]
mod corpus;
use corpus::{LineEnding, Sample};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use mail_parser::{HeaderValue, Message, MessageParser, scan::Kernel};
use memchr::{memchr_iter, memmem};
use std::{fmt::Write, hint::black_box, time::Duration};
fn body_of(sample: &Sample) -> &[u8] {
memmem::find(&sample.bytes, b"\n\n")
.or_else(|| memmem::find(&sample.bytes, b"\r\n\r\n"))
.and_then(|pos| sample.bytes.get(pos..))
.unwrap_or(&sample.bytes)
}
fn count(hay: &[u8], find: impl Fn(&[u8], usize) -> Option<usize>) -> usize {
let mut total = 0;
let mut from = 0;
while let Some(hit) = find(hay, from) {
total += 1;
from = hit + 1;
}
total
}
fn dash_by_memchr_dash(hay: &[u8]) -> usize {
memchr_iter(b'-', hay)
.filter(|&pos| {
pos > 0 && hay.get(pos - 1) == Some(&b'\n') && hay.get(pos + 1) == Some(&b'-')
})
.count()
}
fn dash_by_memchr_newline(hay: &[u8]) -> usize {
memchr_iter(b'\n', hay)
.filter(|&pos| hay.get(pos + 1..pos + 3) == Some(b"--"))
.count()
}
fn inputs() -> Vec<(String, Vec<u8>)> {
let synthetic = corpus::synthetic(LineEnding::Crlf);
let find = |name: &str, sample: &str| {
synthetic
.iter()
.find(|c| c.name.starts_with(name))
.and_then(|c| c.samples.iter().find(|s| s.name == sample))
.map(|s| body_of(s).to_vec())
.unwrap_or_default()
};
vec![
(
"base64-attachment".to_string(),
find("attachments", "attachments-2"),
),
(
"html-newsletter".to_string(),
find("newsletter", "newsletter-5"),
),
("text-8bit".to_string(), find("plain-large", "plain-large")),
("dash-heavy".to_string(), find("dashes", "dashes")),
]
}
fn delimiter_scan(c: &mut Criterion) {
let mut group = c.benchmark_group("delimiter_scan");
for (name, hay) in inputs() {
group.throughput(Throughput::Bytes(hay.len() as u64));
for kernel in Kernel::available() {
let label = match kernel {
Kernel::MEMCHR => "memchr-memmem",
kernel => kernel.name(),
};
group.bench_with_input(BenchmarkId::new(label, &name), &hay, |b, h| {
b.iter(|| count(black_box(h), |hay, from| kernel.dash_line(hay, from)))
});
}
group.bench_with_input(BenchmarkId::new("memchr-dash", &name), &hay, |b, h| {
b.iter(|| dash_by_memchr_dash(black_box(h)))
});
group.bench_with_input(BenchmarkId::new("memchr-newline", &name), &hay, |b, h| {
b.iter(|| dash_by_memchr_newline(black_box(h)))
});
}
group.finish();
}
fn header_messages(line_ending: LineEnding) -> Vec<Vec<u8>> {
corpus::synthetic(line_ending)
.into_iter()
.find(|c| c.name.starts_with("modern-headers"))
.map(|c| c.samples.into_iter().map(|s| s.bytes).collect())
.unwrap_or_default()
}
fn crlf_then_lf(hay: &[u8]) -> Option<usize> {
memmem::find(hay, b"\r\n\r\n").or_else(|| memmem::find(hay, b"\n\n"))
}
fn fused_blank_line(kernel: Kernel, hay: &[u8]) -> Option<usize> {
let mut line = 0;
loop {
match hay.get(line..)? {
[b'\n', ..] | [b'\r', b'\n', ..] => return Some(line),
[] => return None,
_ => line = kernel.field_end(hay, line)? + 1,
}
}
}
const ENRON_BLANK_LINE_SAMPLES: usize = 2;
fn blank_line(c: &mut Criterion) {
let mut group = c.benchmark_group("blank_line");
let enron: Vec<Vec<u8>> = corpus::enron(ENRON_BLANK_LINE_SAMPLES)
.map(|c| c.samples.into_iter().map(|s| s.bytes).collect())
.unwrap_or_default();
let inputs = [
("modern-lf", header_messages(LineEnding::Lf)),
("modern-crlf", header_messages(LineEnding::Crlf)),
("enron-crlf", enron),
];
for (name, messages) in inputs {
if messages.is_empty() {
continue;
}
group.throughput(Throughput::Elements(messages.len() as u64));
let messages = &messages;
group.bench_function(BenchmarkId::new("memmem-crlf-then-lf", name), |b| {
b.iter(|| {
messages
.iter()
.filter_map(|m| crlf_then_lf(black_box(m)))
.sum::<usize>()
})
});
for kernel in Kernel::available() {
group.bench_function(
BenchmarkId::new(format!("fused-{}", kernel.name()), name),
|b| {
b.iter(|| {
messages
.iter()
.filter_map(|m| fused_blank_line(kernel, black_box(m)))
.sum::<usize>()
})
},
);
}
}
group.finish();
}
fn field_split(c: &mut Criterion) {
let mut group = c.benchmark_group("field_split");
let blocks: Vec<Vec<u8>> = header_messages(LineEnding::Crlf)
.into_iter()
.filter_map(|m| {
let end = fused_blank_line(Kernel::SCALAR, &m)?;
m.get(..end).map(<[u8]>::to_vec)
})
.collect();
let bytes: usize = blocks.iter().map(Vec::len).sum();
group.throughput(Throughput::Bytes(bytes as u64));
for kernel in Kernel::available() {
let blocks = &blocks;
group.bench_function(kernel.name(), |b| {
b.iter(|| {
blocks
.iter()
.map(|block| count(black_box(block), |hay, from| kernel.field_end(hay, from)))
.sum::<usize>()
})
});
}
group.finish();
}
const ADDRESS_LIST_SIZES: [usize; 3] = [8, 64, 512];
type WriteMailbox = fn(&mut String, usize, usize);
const ADDRESS_LIST_SHAPES: [(&str, WriteMailbox); 2] = [
("address-list", display_name_mailbox),
("quoted-address-list", quoted_mailbox),
];
fn display_name_mailbox(out: &mut String, index: usize, offset: usize) {
let _ = write!(
out,
"\"Recipient {index} (team {})\" <user{index}@sub{}.example.org>",
index % 5,
(index + offset) % 7
);
}
fn quoted_mailbox(out: &mut String, index: usize, offset: usize) {
let _ = if index.is_multiple_of(2) {
write!(
out,
"\"Recipient {index}\" (team {}) <user{index}@sub{}.example.org>",
index % 5,
(index + offset) % 7
)
} else {
write!(
out,
"\"user {index}\"@sub{}.example.org (team {})",
(index + offset) % 7,
index % 5
)
};
}
fn address_list(mailboxes: usize, write_mailbox: WriteMailbox) -> Vec<u8> {
let mut out = String::from("From: \"Release Bot (automated)\" <bot@example.com>\r\n");
for (header, offset) in [("To", 0), ("Cc", 1)] {
let _ = write!(out, "{header}: ");
for index in 0..mailboxes {
if index > 0 {
out.push_str(",\r\n ");
}
write_mailbox(&mut out, index, offset);
}
out.push_str("\r\n");
}
out.push_str("Subject: Weekly release\r\nDate: Tue, 3 Sep 2024 10:00:00 +0000\r\n\r\nbody\r\n");
out.into_bytes()
}
fn addresses_of(message: &Message<'_>) -> usize {
let mut total = 0;
for part in message.parts() {
for header in part.headers().iter() {
if let HeaderValue::Address(list) = header.value() {
total += list
.mailboxes()
.map(|mailbox| {
mailbox.name().map_or(0, str::len) + mailbox.address().map_or(0, str::len)
})
.sum::<usize>();
}
}
}
total
}
fn header_values(c: &mut Criterion) {
let parser = MessageParser::new();
let mut group = c.benchmark_group("header_values");
let mut inputs: Vec<(String, Vec<Vec<u8>>)> = ADDRESS_LIST_SHAPES
.iter()
.flat_map(|&(shape, write_mailbox)| {
ADDRESS_LIST_SIZES.iter().map(move |&size| {
(
format!("{shape}-{size}"),
vec![address_list(size, write_mailbox)],
)
})
})
.collect();
inputs.push((
"modern-headers".to_string(),
header_messages(LineEnding::Crlf),
));
for (name, messages) in inputs {
if messages.is_empty() {
continue;
}
let bytes: usize = messages.iter().map(Vec::len).sum();
group.throughput(Throughput::Bytes(bytes as u64));
group.bench_function(BenchmarkId::new(Kernel::best().name(), name), |b| {
b.iter(|| {
messages
.iter()
.filter_map(|raw| parser.parse_headers(black_box(raw)))
.map(|message| addresses_of(&message))
.sum::<usize>()
})
});
}
group.finish();
}
fn config() -> Criterion {
Criterion::default()
.warm_up_time(Duration::from_millis(500))
.measurement_time(Duration::from_secs(2))
.sample_size(30)
}
criterion_group! {
name = benches;
config = config();
targets = delimiter_scan, blank_line, field_split, header_values
}
criterion_main!(benches);
-121
View File
@@ -1,121 +0,0 @@
/*
* Copyright Stalwart Labs Ltd. See the COPYING
* file at the top-level directory of this distribution.
*
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/
#![feature(test)]
extern crate test;
use std::{fs, path::PathBuf};
use test::Bencher;
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);
let mut test_data = Vec::new();
for test_suite in ["rfc", "legacy", "thirdparty", "malformed"] {
let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
test_dir.push("tests");
test_dir.push(test_suite);
let mut bench_count = 0;
for file_name in fs::read_dir(&test_dir).unwrap() {
let file_name = file_name.as_ref().unwrap().path();
if file_name.extension().map_or(false, |e| e == "txt") {
let input = fs::read(&file_name).unwrap();
let mut pos = 0;
for sep_pos in 0..input.len() {
if input[sep_pos..sep_pos + SEPARATOR.len()].eq(SEPARATOR) {
pos = sep_pos;
break;
}
}
assert!(
pos > 0,
"Failed to find separator in test file '{}'.",
file_name.display()
);
test_data.push(Vec::from(&input[0..pos]));
bench_count += 1;
}
}
assert!(
bench_count > 0,
"Did not find any benchmarks to run in folder {}.",
test_dir.display()
);
}
b.iter(|| {
for test_msg in &test_data {
fnc(test_msg, String::from_utf8_lossy(&test_msg).as_ref());
}
});
}
#[bench]
fn bench_stalwart(b: &mut Bencher) {
bench_all_samples(b, "stalwart_mail_parser", |bytes, _str| {
mail_parser::Message::parse(bytes);
});
}
// These libraries do not support all RFCs and might be faster
// 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 = { version = "0.5.0", features=["headers", "mime"] }
// mailparse = "0.13"
/*
#[bench]
fn bench_email_parser(b: &mut Bencher) {
bench_all_samples(b, "email_parser", |bytes, _str| {
email_parser::prelude::parse_message(bytes).unwrap();
});
}
#[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| {
email::rfc5322::Rfc5322Parser::new(str).consume_message();
});
}
#[bench]
fn bench_email_format(b: &mut Bencher) {
use email_format::rfc5322::Parsable;
bench_all_samples(b, "email_format", |bytes, _str| {
email_format::Email::parse(bytes).unwrap();
});
}
*/
+113
View File
@@ -0,0 +1,113 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
#[path = "support/corpus.rs"]
mod corpus;
use corpus::{Corpus, LineEnding};
use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use mail_parser::{HeaderValue, Message, MessageParser};
use std::{hint::black_box, time::Duration};
const ENRON_PER_USER: usize = 2;
fn resolver_name() -> &'static str {
if cfg!(mail_parser_checked_str) {
"checked"
} else {
"unchecked"
}
}
fn touch(message: &Message<'_>) -> usize {
let mut total = 0;
for part in message.parts() {
for header in part.headers().iter() {
total += header.raw_name().len();
total += match header.value() {
HeaderValue::Text(text) => text.len(),
HeaderValue::TextList(list) => list.iter().map(str::len).sum(),
HeaderValue::Address(list) => list
.mailboxes()
.map(|mailbox| {
mailbox.name().map_or(0, str::len) + mailbox.address().map_or(0, str::len)
})
.sum(),
HeaderValue::ContentType(content_type) => {
content_type.ctype().len()
+ content_type
.attributes()
.map(|(name, value)| name.len() + value.len())
.sum::<usize>()
}
HeaderValue::Empty | HeaderValue::DateTime(_) | HeaderValue::Received(_) => 0,
};
}
}
total
}
fn corpora() -> Vec<Corpus> {
let mut corpora = vec![corpus::testsuite(LineEnding::Crlf)];
corpora.extend(corpus::enron(ENRON_PER_USER));
corpora.extend(
corpus::synthetic(LineEnding::Crlf)
.into_iter()
.filter(|corpus| corpus.name.starts_with("modern-headers")),
);
corpora
}
fn resolve(c: &mut Criterion) {
let parser = MessageParser::new();
let mut group = c.benchmark_group(format!("resolve-{}", resolver_name()));
for corpus in corpora() {
let messages: Vec<Message<'_>> = corpus
.samples
.iter()
.filter_map(|sample| parser.parse(&sample.bytes))
.collect();
let headers: usize = messages
.iter()
.flat_map(|message| message.parts())
.map(|part| part.headers().len())
.sum();
group.throughput(Throughput::Elements(headers as u64));
group.bench_function(BenchmarkId::new("touch", &corpus.name), |b| {
b.iter(|| {
messages
.iter()
.map(|message| touch(black_box(message)))
.sum::<usize>()
})
});
group.bench_function(BenchmarkId::new("parse-and-touch", &corpus.name), |b| {
b.iter(|| {
corpus
.samples
.iter()
.filter_map(|sample| parser.parse(black_box(&sample.bytes)))
.map(|message| touch(&message))
.sum::<usize>()
})
});
}
group.finish();
}
fn config() -> Criterion {
Criterion::default()
.warm_up_time(Duration::from_millis(500))
.measurement_time(Duration::from_secs(3))
.sample_size(30)
}
criterion_group! {
name = benches;
config = config();
targets = resolve
}
criterion_main!(benches);
+647
View File
@@ -0,0 +1,647 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
#![allow(dead_code)]
use std::{
env,
fmt::Write as _,
fs,
path::{Path, PathBuf},
};
pub const CORPORA_ENV: &str = "MAIL_PARSER_CORPORA";
const ENRON_MAILDIR: &str = "enron/maildir";
const STALWART_SMTP: &str = "stalwart-smtp";
const SIEVE_MESSAGES: &str = "sieve";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineEnding {
Lf,
Crlf,
}
impl LineEnding {
pub fn suffix(self) -> &'static str {
match self {
LineEnding::Lf => "lf",
LineEnding::Crlf => "crlf",
}
}
pub fn apply(self, bytes: &[u8]) -> Vec<u8> {
let mut result = Vec::with_capacity(bytes.len() + bytes.len() / 32);
match self {
LineEnding::Lf => result.extend(bytes.iter().filter(|&&byte| byte != b'\r')),
LineEnding::Crlf => {
let mut last = 0;
for &byte in bytes {
if byte == b'\n' && last != b'\r' {
result.push(b'\r');
}
result.push(byte);
last = byte;
}
}
}
result
}
}
#[derive(Debug, Clone)]
pub struct Sample {
pub name: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct Corpus {
pub name: String,
pub samples: Vec<Sample>,
}
impl Corpus {
pub fn total_bytes(&self) -> u64 {
self.samples.iter().map(|s| s.bytes.len() as u64).sum()
}
fn with_line_ending(name: &str, line_ending: LineEnding, samples: Vec<Sample>) -> Self {
Corpus {
name: format!("{name}-{}", line_ending.suffix()),
samples: samples
.into_iter()
.map(|sample| Sample {
bytes: line_ending.apply(&sample.bytes),
name: sample.name,
})
.collect(),
}
}
}
pub fn mail_parser_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf()
}
pub fn corpora_root() -> PathBuf {
env::var_os(CORPORA_ENV).map_or_else(
|| mail_parser_root().join("target").join("corpora"),
PathBuf::from,
)
}
fn corpus_dir(name: &str) -> Option<PathBuf> {
let dir = corpora_root().join(name);
if dir.is_dir() {
return Some(dir);
}
eprintln!(
"corpus {name} not found in {}: skipped (run scripts/fetch-corpora.sh or set {CORPORA_ENV})",
dir.display()
);
None
}
fn read_dir_sorted(dir: &Path) -> Vec<PathBuf> {
let mut paths: Vec<_> = fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.path())
.filter(|path| path.is_file())
.collect();
paths.sort();
paths
}
fn load(paths: impl IntoIterator<Item = PathBuf>) -> Vec<Sample> {
paths
.into_iter()
.filter_map(|path| {
fs::read(&path).ok().map(|bytes| Sample {
name: path.display().to_string(),
bytes,
})
})
.collect()
}
pub fn testsuite_samples() -> Vec<Sample> {
let resources = mail_parser_root().join("resources");
let eml = resources.join("eml");
let suites = ["rfc", "legacy", "thirdparty", "malformed"]
.iter()
.flat_map(|suite| read_dir_sorted(&eml.join(suite)))
.filter(|path| path.extension().is_some_and(|ext| ext == "eml"));
let sieve = read_dir_sorted(&resources.join(SIEVE_MESSAGES));
let smtp = corpus_dir(STALWART_SMTP)
.map(|dir| read_dir_sorted(&dir))
.unwrap_or_default();
load(suites.chain(smtp).chain(sieve))
}
pub fn testsuite(line_ending: LineEnding) -> Corpus {
Corpus::with_line_ending("testsuite", line_ending, testsuite_samples())
}
pub fn enron(per_user: usize) -> Option<Corpus> {
let users = fs::read_dir(corpus_dir(ENRON_MAILDIR)?).ok()?;
let mut users: Vec<_> = users.flatten().map(|entry| entry.path()).collect();
users.sort();
let mut paths = Vec::new();
for user in users {
let mut stack = vec![user];
let mut taken = 0;
while let Some(dir) = stack.pop() {
let mut entries: Vec<_> = fs::read_dir(&dir)
.into_iter()
.flatten()
.flatten()
.map(|entry| entry.path())
.collect();
entries.sort();
for entry in entries {
if entry.is_dir() {
stack.push(entry);
} else if taken < per_user {
paths.push(entry);
taken += 1;
}
}
if taken >= per_user {
break;
}
}
}
let samples = load(paths);
(!samples.is_empty()).then(|| Corpus {
name: "enron-crlf".to_string(),
samples,
})
}
pub fn synthetic(line_ending: LineEnding) -> Vec<Corpus> {
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
vec![
Corpus::with_line_ending("attachments", line_ending, attachments(&mut rng)),
Corpus::with_line_ending("newsletter", line_ending, newsletters(&mut rng)),
Corpus::with_line_ending("modern-headers", line_ending, modern_headers(&mut rng)),
Corpus::with_line_ending("forwarded", line_ending, forwarded(&mut rng)),
Corpus::with_line_ending("dashes", line_ending, dashes(&mut rng)),
Corpus::with_line_ending("plain-large", line_ending, plain_large(&mut rng)),
]
}
pub fn malformed(line_ending: LineEnding) -> Corpus {
Corpus::with_line_ending("malformed-synthetic", line_ending, malformed_samples())
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, limit: usize) -> usize {
(self.next() % limit as u64) as usize
}
fn pick<'a>(&mut self, items: &[&'a str]) -> &'a str {
items[self.below(items.len())]
}
fn bytes(&mut self, len: usize) -> Vec<u8> {
(0..len).map(|_| self.next() as u8).collect()
}
}
const WORDS: &[&str] = &[
"the",
"quarterly",
"report",
"attached",
"please",
"review",
"meeting",
"tomorrow",
"budget",
"forecast",
"café",
"naïve",
"déjà",
"vu",
"résumé",
"日本語",
"über",
"schedule",
"project",
"deadline",
"update",
"customer",
"invoice",
"shipping",
"order",
"account",
"security",
"password",
"reset",
"team",
"lunch",
"Friday",
"regards",
"thanks",
"server",
"deploy",
"release",
"notes",
"feature",
"bug",
"fix",
"issue",
];
fn sentence(rng: &mut Rng, words: usize) -> String {
let mut out = String::new();
for index in 0..words {
if index > 0 {
out.push(' ');
}
out.push_str(rng.pick(WORDS));
}
out.push('.');
out
}
fn wrapped_text(rng: &mut Rng, target: usize) -> String {
let mut out = String::with_capacity(target + 128);
let mut line = String::new();
while out.len() < target {
let word = rng.pick(WORDS);
if line.len() + word.len() + 1 > 72 {
out.push_str(&line);
out.push('\n');
line.clear();
if rng.below(12) == 0 {
out.push('\n');
}
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
out.push_str(&line);
out.push('\n');
out
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut encoded = Vec::with_capacity(bytes.len() * 4 / 3 + 4);
for chunk in bytes.chunks(3) {
let word = chunk
.iter()
.enumerate()
.fold(0u32, |acc, (i, &b)| acc | (b as u32) << (16 - 8 * i));
let symbols = chunk.len() + 1;
for index in 0..4 {
encoded.push(if index < symbols {
ALPHABET[((word >> (18 - 6 * index)) & 0x3f) as usize]
} else {
b'='
});
}
}
let mut out = String::with_capacity(encoded.len() + encoded.len() / 76 + 2);
for line in encoded.chunks(76) {
out.push_str(std::str::from_utf8(line).unwrap_or_default());
out.push('\n');
}
out
}
fn quoted_printable(text: &str) -> String {
let mut out = String::with_capacity(text.len() * 5 / 4);
for line in text.split('\n') {
let mut column = 0;
for &byte in line.as_bytes() {
let encoded = if byte == b'=' || byte >= 0x80 || byte == b'\t' {
format!("={byte:02X}")
} else {
(byte as char).to_string()
};
if column + encoded.len() > 75 {
out.push_str("=\n");
column = 0;
}
column += encoded.len();
out.push_str(&encoded);
}
out.push('\n');
}
out
}
fn html(rng: &mut Rng, target: usize) -> String {
let mut out = String::with_capacity(target + 512);
out.push_str(
"<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\">\n<style>\n:root { --brand-color: #0a66c2; --gap: 12px; }\n.button { color: var(--brand-color); margin: var(--gap); }\n</style>\n</head><body>\n",
);
while out.len() < target {
match rng.below(6) {
0 => {
let _ = writeln!(out, "<!-- section {} -->", rng.below(1000));
}
1 => {
let _ = writeln!(
out,
"<table role=\"presentation\" style=\"width:100%;border-top:1px solid #eee\"><tr><td class=\"cell\">{}</td></tr></table>",
sentence(rng, 12)
);
}
2 => {
let _ = writeln!(
out,
"<a class=\"button\" href=\"https://example.com/track?id={}&amp;u={}\">{}</a>",
rng.next(),
rng.next(),
sentence(rng, 3)
);
}
3 => out.push_str("<hr style=\"border:0;border-top:1px dashed #ccc\">\n-----\n"),
_ => {
let _ = writeln!(out, "<p>{}</p>", sentence(rng, 20));
}
}
}
out.push_str("</body></html>\n");
out
}
fn envelope(rng: &mut Rng, subject: &str, received: usize, extra: &str) -> String {
let mut out = String::with_capacity(1024 + received * 256);
for hop in 0..received {
let _ = write!(
out,
"Received: from mx{hop}.example.net (mx{hop}.example.net [192.0.2.{}])\n\tby relay{hop}.example.org (Postfix) with ESMTPS id {:X}\n\tfor <user@example.org>; Tue, 3 Sep 2024 10:{:02}:{:02} +0000\n",
rng.below(255),
rng.next(),
rng.below(60),
rng.below(60)
);
}
let _ = write!(
out,
"From: \"Sender {}\" <sender{}@example.com>\nTo: Recipient <user@example.org>, \"Another Person\" <another@example.org>\nSubject: {subject}\nDate: Tue, 3 Sep 2024 10:{:02}:{:02} +0000\nMessage-ID: <{:x}@example.com>\nMIME-Version: 1.0\n{extra}",
rng.below(100),
rng.below(100),
rng.below(60),
rng.below(60),
rng.next()
);
out
}
fn attachments(rng: &mut Rng) -> Vec<Sample> {
[(400_000usize, 150_000usize), (60_000, 20_000), (2_000_000, 300_000)]
.into_iter()
.enumerate()
.map(|(index, (pdf, png))| {
let outer = format!("----=_Part_{index}_1634.1725357934");
let inner = format!("----=_Part_{}_1634.1725357934", index + 10);
let text = wrapped_text(rng, 4_000);
let page = html(rng, 30_000);
let mut out = envelope(
rng,
"Quarterly report",
4,
&format!("Content-Type: multipart/mixed; boundary=\"{outer}\"\n\nThis is a multi-part message in MIME format.\n\n"),
);
let _ = write!(
out,
"--{outer}\nContent-Type: multipart/alternative; boundary=\"{inner}\"\n\n--{inner}\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: quoted-printable\n\n{}--{inner}\nContent-Type: text/html; charset=utf-8\nContent-Transfer-Encoding: quoted-printable\n\n{}--{inner}--\n\n",
quoted_printable(&text),
quoted_printable(&page)
);
let _ = write!(
out,
"--{outer}\nContent-Type: application/pdf; name=\"report.pdf\"\nContent-Disposition: attachment; filename=\"report.pdf\"\nContent-Transfer-Encoding: base64\n\n{}--{outer}\nContent-Type: image/png; name=\"photo.png\"\nContent-Disposition: inline; filename=\"photo.png\"\nContent-ID: <photo{index}@example.com>\nContent-Transfer-Encoding: base64\n\n{}--{outer}--\n",
base64(&rng.bytes(pdf)),
base64(&rng.bytes(png))
);
Sample {
name: format!("attachments-{index}"),
bytes: out.into_bytes(),
}
})
.collect()
}
fn newsletters(rng: &mut Rng) -> Vec<Sample> {
(0..6)
.map(|index| {
let boundary = format!("b1_{:x}", rng.next());
let related = format!("b2_{:x}", rng.next());
let mut text = wrapped_text(rng, 8_000 + index * 2_000);
text.push_str("-----\nUnsubscribe: https://example.com/u\n-- \nThe Newsletter Team\n");
let page = html(rng, 60_000 + index * 10_000);
let mut out = envelope(
rng,
"Your weekly digest",
3,
&format!("Content-Type: multipart/alternative; boundary=\"{boundary}\"\n\n"),
);
let _ = write!(
out,
"--{boundary}\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\n\n{text}\n--{boundary}\nContent-Type: multipart/related; boundary=\"{related}\"\n\n--{related}\nContent-Type: text/html; charset=utf-8\nContent-Transfer-Encoding: quoted-printable\n\n{}\n--{related}\nContent-Type: image/gif; name=\"logo.gif\"\nContent-ID: <logo@example.com>\nContent-Transfer-Encoding: base64\n\n{}--{related}--\n\n--{boundary}--\n",
quoted_printable(&page),
base64(&rng.bytes(12_000))
);
Sample {
name: format!("newsletter-{index}"),
bytes: out.into_bytes(),
}
})
.collect()
}
fn modern_headers(rng: &mut Rng) -> Vec<Sample> {
(0..20)
.map(|index| {
let boundary = format!("000000000000{:x}", rng.next());
let signature: String = (0..6)
.map(|_| format!("\t {}\n", base64(&rng.bytes(48)).trim_end()))
.collect();
let extra = format!(
"ARC-Seal: i=1; a=rsa-sha256; t=1725357934; cv=none; d=example.com; s=arc-20240605;\n{signature}ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=example.com;\n\ts=arc-20240605; h=to:subject:message-id:date:from:mime-version:dkim-signature;\n\tbh={}=;\n{signature}ARC-Authentication-Results: i=1; mx.example.com;\n\tdkim=pass header.i=@example.com header.s=20230601 header.b=abc;\n\tspf=pass (example.com: domain of sender@example.com designates 192.0.2.1 as permitted sender) smtp.mailfrom=sender@example.com;\n\tdmarc=pass (p=NONE sp=QUARANTINE dis=NONE) header.from=example.com\nDKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=example.com; s=20230601; t=1725357934; x=1725962734;\n\th=to:subject:message-id:date:from:mime-version:from:to:cc:subject:date:message-id:reply-to;\n\tbh={}=;\n{signature}X-Google-Smtp-Source: {}\nX-Received: by 2002:a05:6512:3b0a with SMTP id f10mr{} ; Tue, 03 Sep 2024 03:05:34 -0700 (PDT)\nList-Unsubscribe: <mailto:unsubscribe@example.com?subject=unsub>, <https://example.com/unsub/{:x}>\nList-Unsubscribe-Post: List-Unsubscribe=One-Click\nAuthentication-Results: mx.example.org; dkim=pass; spf=pass; dmarc=pass\nContent-Type: multipart/alternative; boundary=\"{boundary}\"\n\n",
base64(&rng.bytes(32)).trim_end(),
base64(&rng.bytes(32)).trim_end(),
base64(&rng.bytes(40)).trim_end(),
rng.below(1_000_000),
rng.next()
);
let text = wrapped_text(rng, 1_500);
let page = html(rng, 6_000);
let subject = sentence(rng, 6);
let mut out = envelope(rng, &subject, 6 + index % 4, &extra);
let _ = write!(
out,
"--{boundary}\nContent-Type: text/plain; charset=\"UTF-8\"\nContent-Transfer-Encoding: quoted-printable\n\n{}\n--{boundary}\nContent-Type: text/html; charset=\"UTF-8\"\nContent-Transfer-Encoding: quoted-printable\n\n{}\n--{boundary}--\n",
quoted_printable(&text),
quoted_printable(&page)
);
Sample {
name: format!("modern-headers-{index}"),
bytes: out.into_bytes(),
}
})
.collect()
}
fn nested_message(rng: &mut Rng, depth: usize) -> String {
let boundary = format!("fwd-{depth}-{:x}", rng.next());
let mut out = envelope(
rng,
&format!("Fwd: level {depth}"),
2,
&format!("Content-Type: multipart/mixed; boundary=\"{boundary}\"\n\n"),
);
let _ = write!(
out,
"--{boundary}\nContent-Type: text/plain; charset=utf-8\n\n{}\n",
wrapped_text(rng, 1_500)
);
if depth == 0 {
let alternative = format!("alt-{:x}", rng.next());
let _ = write!(
out,
"--{boundary}\nContent-Type: multipart/alternative; boundary=\"{alternative}\"\n\n--{alternative}\nContent-Type: text/plain; charset=utf-8\n\n{}\n--{alternative}\nContent-Type: text/html; charset=utf-8\n\n{}\n--{alternative}--\n\n",
wrapped_text(rng, 2_000),
html(rng, 5_000)
);
} else {
let _ = write!(
out,
"--{boundary}\nContent-Type: message/rfc822\nContent-Disposition: inline\n\n{}\n",
nested_message(rng, depth - 1)
);
}
let _ = writeln!(out, "--{boundary}--");
out
}
fn forwarded(rng: &mut Rng) -> Vec<Sample> {
(1..=6)
.map(|depth| Sample {
name: format!("forwarded-{depth}"),
bytes: nested_message(rng, depth).into_bytes(),
})
.collect()
}
fn dashes(rng: &mut Rng) -> Vec<Sample> {
let boundary = "==dash-boundary==";
let mut out = envelope(
rng,
"Patch review",
2,
&format!("Content-Type: multipart/mixed; boundary=\"{boundary}\"\n\n"),
);
for part in 0..3 {
let mut body = String::with_capacity(200_000);
while body.len() < 200_000 {
match rng.below(10) {
0 => body.push_str("-- SELECT * FROM accounts WHERE id = 42;\n"),
1 => body.push_str("--- a/src/lib.rs\n+++ b/src/lib.rs\n"),
2 => {
let _ = writeln!(body, "--{boundary}x not a delimiter");
}
3 => body.push_str("-----\n"),
_ => {
body.push_str(&sentence(rng, 10));
body.push('\n');
}
}
}
let _ = write!(
out,
"--{boundary}\nContent-Type: text/plain; charset=utf-8\nContent-Disposition: attachment; filename=\"part{part}.diff\"\n\n{body}"
);
}
let _ = writeln!(out, "--{boundary}--");
vec![Sample {
name: "dashes".to_string(),
bytes: out.into_bytes(),
}]
}
fn plain_large(rng: &mut Rng) -> Vec<Sample> {
let mut body = String::with_capacity(1_000_000);
while body.len() < 1_000_000 {
body.push_str(&wrapped_text(rng, 2_000));
body.push_str("-----Original Message-----\n-- \nSent from my phone\n");
}
let mut out = envelope(
rng,
"Long thread",
3,
"Content-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8bit\n\n",
);
out.push_str(&body);
vec![Sample {
name: "plain-large".to_string(),
bytes: out.into_bytes(),
}]
}
fn malformed_samples() -> Vec<Sample> {
let cases: &[(&str, &str)] = &[
(
"inner-missing-close",
"Subject: a\nContent-Type: multipart/mixed; boundary=\"outer\"\n\n--outer\nContent-Type: multipart/alternative; boundary=\"inner\"\n\n--inner\nContent-Type: text/plain\n\nplain\n--inner\nContent-Type: text/html\n\n<p>html</p>\n--outer\nContent-Type: text/plain\n\nafter the unterminated alternative\n--outer--\n",
),
(
"prefix-collision",
"Subject: b\nContent-Type: multipart/mixed; boundary=\"abc\"\n\n--abc\nContent-Type: multipart/alternative; boundary=\"abc-1\"\n\n--abc-1\nContent-Type: text/plain\n\none\n--abc-1\nContent-Type: text/html\n\n<b>two</b>\n--abc-1--\n--abc\nContent-Type: text/plain\n\nthree\n--abc--\n",
),
(
"part-without-blank-line",
"Subject: c\nContent-Type: multipart/mixed; boundary=\"x\"\n\n--x\nContent-Type: text/plain\n--x\nContent-Type: text/plain\n\nsecond\n--x--\n",
),
(
"truncated-base64",
"Subject: d\nContent-Type: multipart/mixed; boundary=\"t\"\n\n--t\nContent-Type: text/plain\n\nhello\n--t\nContent-Type: application/octet-stream\nContent-Transfer-Encoding: base64\n\nSGVsbG8gd29ybGQ=\nSGVsbG8g",
),
(
"mid-line-boundary",
"Subject: e\nContent-Type: multipart/mixed; boundary=\"1\"\n\n--1\nContent-Type: text/plain\n\nfirst\n--1\nContent-Type: text/plain\n\nlast part--1--\n",
),
(
"empty-rfc822",
"Subject: f\nContent-Type: multipart/mixed; boundary=\"m\"\n\n--m\nContent-Type: message/rfc822\n\n--m\nContent-Type: text/plain\n\nafter\n--m--\n",
),
(
"boundary-never-appears",
"Subject: g\nContent-Type: multipart/mixed; boundary=\"missing\"\n\njust some text\nwithout delimiters\n",
),
("headers-only", "Subject: h\nFrom: a@example.com"),
(
"nested-unterminated-rfc822",
"Subject: i\nContent-Type: multipart/mixed; boundary=\"o\"\n\n--o\nContent-Type: message/rfc822\n\nSubject: inner\nContent-Type: multipart/mixed; boundary=\"n\"\n\n--n\nContent-Type: text/plain\n\ninner text\n--o\nContent-Type: text/plain\n\nouter again\n--o--\n",
),
];
cases
.iter()
.map(|(name, text)| Sample {
name: (*name).to_string(),
bytes: text.as_bytes().to_vec(),
})
.collect()
}
+417
View File
@@ -0,0 +1,417 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use mail_parser::{Message, MessageParser, MessagePart};
use std::{
borrow::Cow,
fs,
hint::black_box,
io::Write,
path::{Path, PathBuf},
time::Duration,
};
const SIZES: [(&str, usize); 6] = [
("4k", 4 << 10),
("64k", 64 << 10),
("80k", 80 << 10),
("128k", 128 << 10),
("256k", 256 << 10),
("4m", 4 << 20),
];
const PREFIX_CHARS: usize = 65_536;
const PREVIEW_BYTES: usize = 256;
const ATTACHMENT_LIMIT: usize = 65_537;
const BODY_LIMIT: usize = 262_145;
const ATTACHMENT_PROBE: usize = 65_536 + char::MAX_LEN_UTF8;
const BODY_PROBE: usize = 262_144 + char::MAX_LEN_UTF8;
const TEXT_LINE: usize = 72;
const QP_LINE: usize = 76;
const BASE64_LINE_BYTES: usize = 57;
const ASCII_WORDS: &[&str] = &[
"the",
"quarterly",
"report",
"attached",
"please",
"review",
"meeting",
"tomorrow",
"budget",
"forecast",
"schedule",
"project",
"deadline",
"customer",
"invoice",
"shipping",
"account",
"security",
"regards",
"release",
];
const UTF8_WORDS: &[&str] = &[
"the",
"quarterly",
"report",
"attached",
"please",
"review",
"meeting",
"budget",
"café",
"naïve",
"déjà",
"résumé",
"über",
"Grüße",
"año",
"日本語",
"テキスト",
"привет",
"\u{1f600}",
"regards",
];
const LATIN1_WORDS: &[&str] = &[
"the",
"quarterly",
"report",
"attached",
"please",
"review",
"meeting",
"budget",
"café",
"naïve",
"déjà",
"résumé",
"über",
"Grüße",
"año",
"façade",
"smørrebrød",
"regards",
];
const DENSE_WORDS: &[&str] = &[
"привет",
"письмо",
"сообщение",
"Москва",
"日本語",
"テキスト",
"中文",
"отчёт",
];
struct Rng(u64);
impl Rng {
fn pick<'a>(&mut self, items: &[&'a str]) -> &'a str {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
let index = usize::try_from(self.0 % items.len() as u64).unwrap_or_default();
items.get(index).copied().unwrap_or_default()
}
}
fn wrapped_text(words: &[&str], size: usize) -> String {
let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
let mut text = String::with_capacity(size + TEXT_LINE);
let mut column = 0;
while text.len() < size {
let word = rng.pick(words);
if column > 0 && column + word.len() + 1 > TEXT_LINE {
text.push_str("\r\n");
column = 0;
} else if column > 0 {
text.push(' ');
column += 1;
}
text.push_str(word);
column += word.len();
}
text.truncate(text.floor_char_boundary(size));
text
}
fn base64(bytes: &[u8]) -> Vec<u8> {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = Vec::with_capacity(bytes.len() / 3 * 4 + bytes.len() / 28 + 8);
for line in bytes.chunks(BASE64_LINE_BYTES) {
for chunk in line.chunks(3) {
let word = chunk.iter().enumerate().fold(0u32, |acc, (index, &byte)| {
acc | u32::from(byte) << (16 - 8 * index)
});
for index in 0..4 {
out.push(if index <= chunk.len() {
ALPHABET[((word >> (18 - 6 * index)) & 0x3f) as usize]
} else {
b'='
});
}
}
out.extend_from_slice(b"\r\n");
}
out
}
fn quoted_printable(text: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(text.len() * 3);
for (index, line) in text.split("\r\n").enumerate() {
if index > 0 {
out.extend_from_slice(b"\r\n");
}
let mut column = 0;
for &byte in line.as_bytes() {
let escaped = byte == b'=' || !byte.is_ascii();
let width = if escaped { 3 } else { 1 };
if column + width > QP_LINE - 1 {
out.extend_from_slice(b"=\r\n");
column = 0;
}
if escaped {
write!(out, "={byte:02X}").expect("write to a Vec");
} else {
out.push(byte);
}
column += width;
}
}
out
}
fn utf16le(text: &str) -> Vec<u8> {
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
}
fn latin1(text: &str) -> Vec<u8> {
text.chars()
.map(|ch| u8::try_from(u32::from(ch)).expect("a Latin-1 character"))
.collect()
}
fn message(charset: &str, encoding: &str, body: &[u8]) -> Vec<u8> {
let mut raw = format!(
"From: sender@example.com\r\nTo: rcpt@example.com\r\nSubject: text prefix\r\nContent-Type: text/plain; charset={charset}\r\nContent-Transfer-Encoding: {encoding}\r\n\r\n"
)
.into_bytes();
raw.extend_from_slice(body);
raw
}
#[derive(Clone, Copy)]
enum Body {
Ascii,
Utf8,
Base64,
Base64Utf16,
QuotedPrintable,
QuotedPrintableDense,
Latin1,
}
impl Body {
const ALL: [Body; 7] = [
Body::Ascii,
Body::Utf8,
Body::Base64,
Body::Base64Utf16,
Body::QuotedPrintable,
Body::QuotedPrintableDense,
Body::Latin1,
];
fn name(self) -> &'static str {
match self {
Body::Ascii => "7bit-ascii",
Body::Utf8 => "8bit-utf8",
Body::Base64 => "base64-utf8",
Body::Base64Utf16 => "base64-utf16",
Body::QuotedPrintable => "qp-utf8",
Body::QuotedPrintableDense => "qp-dense-utf8",
Body::Latin1 => "8bit-latin1",
}
}
fn message(self, size: usize) -> Vec<u8> {
match self {
Body::Ascii => message(
"us-ascii",
"7bit",
wrapped_text(ASCII_WORDS, size).as_bytes(),
),
Body::Utf8 => message("utf-8", "8bit", wrapped_text(UTF8_WORDS, size).as_bytes()),
Body::Base64 => message(
"utf-8",
"base64",
&base64(wrapped_text(UTF8_WORDS, size).as_bytes()),
),
Body::Base64Utf16 => message(
"utf-16le",
"base64",
&base64(&utf16le(&wrapped_text(ASCII_WORDS, size))),
),
Body::QuotedPrintable => message(
"utf-8",
"quoted-printable",
&quoted_printable(&wrapped_text(UTF8_WORDS, size)),
),
Body::QuotedPrintableDense => message(
"utf-8",
"quoted-printable",
&quoted_printable(&wrapped_text(DENSE_WORDS, size)),
),
Body::Latin1 => message(
"iso-8859-1",
"8bit",
&latin1(&wrapped_text(LATIN1_WORDS, size)),
),
}
}
}
fn eml_files(dir: &Path, found: &mut Vec<PathBuf>) {
for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() {
eml_files(&path, found);
} else if path.extension().is_some_and(|ext| ext == "eml") {
found.push(path);
}
}
}
fn fixtures() -> Vec<Vec<u8>> {
let mut paths = Vec::new();
eml_files(
&Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/eml"),
&mut paths,
);
paths.sort();
paths
.iter()
.filter_map(|path| fs::read(path).ok())
.collect()
}
fn text_len(text: Option<Cow<'_, str>>) -> usize {
text.map_or(0, |text| text.len())
}
fn text(part: MessagePart<'_>) -> usize {
text_len(part.text())
}
fn text_prefix(part: MessagePart<'_>) -> usize {
text_len(part.text_prefix(PREFIX_CHARS))
}
fn text_prefix_bytes_attachment(part: MessagePart<'_>) -> usize {
text_len(part.text_prefix_bytes(ATTACHMENT_LIMIT))
}
fn text_prefix_bytes_body(part: MessagePart<'_>) -> usize {
text_len(part.text_prefix_bytes(BODY_LIMIT))
}
fn text_prefix_bytes_attachment_probe(part: MessagePart<'_>) -> usize {
text_len(part.text_prefix_bytes(ATTACHMENT_PROBE))
}
fn text_prefix_bytes_body_probe(part: MessagePart<'_>) -> usize {
text_len(part.text_prefix_bytes(BODY_PROBE))
}
type PartCase = fn(MessagePart<'_>) -> usize;
const PART_CASES: &[(&str, PartCase)] = &[
("text", text),
("text_prefix_65536", text_prefix),
("text_prefix_bytes_65537", text_prefix_bytes_attachment),
("text_prefix_bytes_262145", text_prefix_bytes_body),
(
"text_prefix_bytes_65540",
text_prefix_bytes_attachment_probe,
),
("text_prefix_bytes_262148", text_prefix_bytes_body_probe),
];
fn body_preview(message: &Message<'_>) -> usize {
text_len(message.body_preview(PREVIEW_BYTES))
}
fn text_parts(c: &mut Criterion) {
let mut group = c.benchmark_group("text_prefix");
for body in Body::ALL {
for (size_name, size) in SIZES {
let raw = body.message(size);
let message = MessageParser::new().parse(&raw).expect("parses");
let part = message.root_part();
let input = format!("{}-{size_name}", body.name());
eprintln!(
"{input}: raw body {} bytes, text {} bytes",
part.raw_body().len(),
text(part)
);
for &(name, case) in PART_CASES {
group.bench_function(BenchmarkId::new(name, &input), |b| {
b.iter(|| case(black_box(part)))
});
}
group.bench_function(BenchmarkId::new("body_preview_256", &input), |b| {
b.iter(|| body_preview(black_box(&message)))
});
}
}
let raws = fixtures();
let messages: Vec<Message<'_>> = raws
.iter()
.filter_map(|raw| MessageParser::new().parse(raw))
.collect();
eprintln!(
"eml-fixtures: {} messages, {} text parts",
messages.len(),
messages
.iter()
.flat_map(|message| message.parts())
.filter(|part| part.is_text())
.count()
);
for &(name, case) in PART_CASES {
group.bench_function(BenchmarkId::new(name, "eml-fixtures"), |b| {
b.iter(|| {
black_box(&messages)
.iter()
.flat_map(|message| message.parts())
.filter(|part| part.is_text())
.map(case)
.sum::<usize>()
})
});
}
group.bench_function(BenchmarkId::new("body_preview_256", "eml-fixtures"), |b| {
b.iter(|| black_box(&messages).iter().map(body_preview).sum::<usize>())
});
group.finish();
}
fn config() -> Criterion {
Criterion::default()
.warm_up_time(Duration::from_secs(1))
.measurement_time(Duration::from_secs(3))
.sample_size(50)
.noise_threshold(0.02)
}
criterion_group! {
name = benches;
config = config();
targets = text_parts
}
criterion_main!(benches);
+84
View File
@@ -0,0 +1,84 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*/
use mail_parser::{HeaderForm, HeaderName, MessageParser};
const MESSAGE: &[u8] = b"Received: from mx.example.com (mx.example.com [192.0.2.1])\r\n\
\tby mail.example.org with ESMTPS id 4F2A1; Sat, 20 Nov 2021 14:22:05 -0800\r\n\
From: Art Vandelay <art@vandelay.com>\r\n\
To: jane@example.com\r\n\
Subject: Latex imports\r\n\
X-Sender: Kel Varnsen <kel@vandelay.com>\r\n\
X-Tags: latex, import, export\r\n\
X-Mailer: Vandelay Mail 1.0\r\n\
X-Internal-Note: kept, but not parsed\r\n\
\r\n\
Please see the attached catalog.\r\n";
fn main() {
let parser = MessageParser::new()
.header(HeaderName::Received, HeaderForm::Raw)
.header("X-Sender", HeaderForm::Addresses)
.header("X-Tags", HeaderForm::CommaList)
.unknown_headers(HeaderForm::Ignore)
.max_depth(16)
.max_parts(100);
let message = parser.parse(MESSAGE).expect("the message parses");
println!("Header fields with the configured forms:");
for header in message.headers().iter() {
println!(" {}: {:?}", header.raw_name(), header.value());
}
let received = message
.headers()
.get(HeaderName::Received)
.expect("a Received field");
let parsed = received.parse_as(HeaderForm::Received);
if let Some(trace) = parsed.value().as_received() {
println!(
"\nReceived, parsed on demand: from {:?} by {:?} with {:?}, id {:?}",
trace.from(),
trace.by(),
trace.with(),
trace.id()
);
}
let headers_only = MessageParser::new()
.parse_headers(MESSAGE)
.expect("the header block parses");
println!(
"\nparse_headers: {} header fields, body at byte {}",
headers_only.headers().len(),
headers_only.root_part().offset_body()
);
println!("\nHeader values parsed on their own:");
let addresses =
HeaderForm::Addresses.parse(b" Ann <ann@example.com>, team: bob@example.com;\r\n");
if let Some(list) = addresses.value().as_address() {
for mailbox in list.mailboxes() {
println!(
" mailbox {:?} {:?}",
mailbox.name().unwrap_or_default(),
mailbox.address().unwrap_or_default()
);
}
}
let date = HeaderForm::Date.parse(b" Sat, 20 Nov 2021 14:22:01 -0800\r\n");
if let Some(date) = date.value().as_datetime() {
println!(" date {} ({})", date.to_rfc3339(), date.to_timestamp());
}
let ids = HeaderForm::MessageIds.parse(b" <first@example.com>\r\n <second@example.com>\r\n");
if let Some(ids) = ids.value().as_text_list() {
for id in ids.iter() {
println!(" message id {id}");
}
}
let subject = HeaderForm::Text.parse(b" =?utf-8?q?caf=C3=A9?= au lait\r\n");
println!(" text {:?}", subject.value().as_text().unwrap_or_default());
}
+29 -27
View File
@@ -1,36 +1,38 @@
/* /*
* Copyright Stalwart Labs Ltd. See the COPYING * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
* file at the top-level directory of this distribution.
* *
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * SPDX-License-Identifier: Apache-2.0 OR MIT
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/ */
use std::path::PathBuf; use mail_parser::{MessageBuffers, MessageParser, mailbox::maildir::FolderIterator};
use std::{env, io, path::PathBuf};
use mail_parser::mailbox::maildir::FolderIterator; fn main() -> io::Result<()> {
let maildir = env::args_os().nth(1).map_or_else(
fn main() { || PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/maildir"),
// Iterates a Maildir++ structure printing the results to stdout. PathBuf::from,
let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); );
test_dir.push("tests"); let parser = MessageParser::new();
test_dir.push("maildir"); let mut buffers = MessageBuffers::new();
for folder in FolderIterator::new(maildir, Some("."))? {
for folder in FolderIterator::new(test_dir, ".".into()).unwrap() { let folder = folder?;
let folder = folder.unwrap(); println!("Folder {}", folder.name().unwrap_or("INBOX"));
println!("------\nMailbox: {:?}", folder.name().unwrap_or("INBOX")); for entry in folder {
let entry = entry?;
for message in folder { print!(
let message = message.unwrap(); " {}, flags {:?}, {} bytes: ",
println!( entry.path().display(),
"Message with internal date {}, flags {:?} and content {:?}.", entry.flags(),
message.internal_date(), entry.contents().len()
message.flags(),
String::from_utf8_lossy(message.contents())
); );
match parser.parse_with(entry.contents(), &mut buffers) {
Some(message) => {
println!("{:?}", message.subject().unwrap_or_default());
buffers = message.into_buffers();
}
None => println!("not a message"),
}
} }
} }
Ok(())
} }
+51 -14
View File
@@ -1,22 +1,59 @@
/* /*
* Copyright Stalwart Labs Ltd. See the COPYING * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
* file at the top-level directory of this distribution.
* *
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * SPDX-License-Identifier: Apache-2.0 OR MIT
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/ */
use mail_parser::{mailbox::mbox::MessageIterator, Message}; use mail_parser::{MessageBuffers, MessageParser, mailbox::mbox::MessageIterator};
use std::{
env,
fs::File,
io::{self, BufRead, BufReader},
};
fn main() { const SAMPLE: &[u8] = b"From ann@example.com Sat Jan 3 01:05:34 1996\n\
// Reads an MBox mailbox from stdin and prints each message as YAML. From: Ann <ann@example.com>\n\
for raw_message in MessageIterator::new(std::io::stdin()) { Subject: First message\n\
let raw_message = raw_message.unwrap(); \n\
let message = Message::parse(raw_message.contents()).unwrap(); >From the mbox point of view, this line was quoted.\n\
\n\
From bob@example.com Sun Jan 4 10:00:00 1996\n\
From: Bob <bob@example.com>\n\
Subject: Second message\n\
\n\
Hello.\n";
println!("{}", serde_yaml::to_string(&message).unwrap()); fn main() -> io::Result<()> {
match env::args_os().nth(1) {
None => list(SAMPLE),
Some(path) if path == "-" => list(io::stdin().lock()),
Some(path) => list(BufReader::new(File::open(path)?)),
} }
} }
fn list(mbox: impl BufRead) -> io::Result<()> {
let parser = MessageParser::new();
let mut buffers = MessageBuffers::new();
for entry in MessageIterator::new(mbox) {
let entry = entry?;
match parser.parse_with(entry.contents(), &mut buffers) {
Some(message) => {
println!(
"{} from {}: {:?}, {} parts, preview {:?}",
entry.internal_date(),
entry.from(),
message.subject().unwrap_or_default(),
message.parts().len(),
message.body_preview(60).unwrap_or_default()
);
buffers = message.into_buffers();
}
None => println!(
"{} from {}: not a message",
entry.internal_date(),
entry.from()
),
}
}
Ok(())
}
+116 -90
View File
@@ -1,18 +1,12 @@
/* /*
* Copyright Stalwart Labs Ltd. See the COPYING * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
* file at the top-level directory of this distribution.
* *
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * SPDX-License-Identifier: Apache-2.0 OR MIT
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/ */
use mail_parser::*; use mail_parser::{Address, Mailbox, MessageParser, MessagePart, PartKind};
fn main() { const MESSAGE: &[u8] = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)
let input = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)
To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends: To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends:
jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>; jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;
Date: Sat, 20 Nov 2021 14:22:01 -0800 Date: Sat, 20 Nov 2021 14:22:01 -0800
@@ -53,93 +47,125 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
--festivus-- --festivus--
"#; "#;
let message = Message::parse(input).unwrap(); fn main() {
let message = MessageParser::new()
.parse(MESSAGE)
.expect("the message parses");
// Parses addresses (including comments), lists and groups println!("Subject: {}", message.subject().unwrap_or_default());
assert_eq!( if let Some(date) = message.date() {
message.from(), println!("Date: {}", date.to_rfc3339());
&HeaderValue::Address(Addr::new( }
"Art Vandelay (Vandelay Industries)".into(), for sender in message.from().into_iter().flat_map(|from| from.mailboxes()) {
"art@vandelay.com" println!("From: {}", display(sender));
)) }
); for recipient in message.to().into_iter().flat_map(|to| to.iter()) {
match recipient {
Address::Mailbox(mailbox) => println!("To: {}", display(mailbox)),
Address::Group(group) => {
println!("To group {}:", group.name().unwrap_or_default());
for member in group.mailboxes() {
println!(" {}", display(member));
}
}
}
}
assert_eq!( println!("\nHeader fields as written, with their parsed values:");
message.to(), for header in message.headers().iter() {
&HeaderValue::GroupList(vec![ println!(" {}: {:?}", header.raw_name(), header.value());
Group::new( }
"Colleagues",
vec![Addr::new("James Smythe".into(), "james@vandelay.com")]
),
Group::new(
"Friends",
vec![
Addr::new(None, "jane@example.com"),
Addr::new("John Smîth".into(), "john@example.com"),
]
)
])
);
assert_eq!( println!("\nText body (HTML converted to text):");
message.date().unwrap().to_rfc3339(), for text in message.text_bodies() {
"2021-11-20T14:22:01-08:00" println!("{text}");
); }
println!("\nHTML body:");
for html in message.html_bodies() {
println!("{html}");
}
// RFC2047 support for encoded text in message readers println!("\nEvery part of every message, in document order:");
assert_eq!( for part in message.parts() {
message.subject().unwrap(), describe(part);
"Why not both importing AND exporting? ☺" }
);
// HTML and text body parts are returned conforming to RFC8621, Section 4.1.4 if let Some(multipart) = message.part_by_boundary("giddyup") {
assert_eq!( println!(
message.body_html(0).unwrap(), "\nThe boundary \"giddyup\" belongs to part {}, which has {} children",
concat!( multipart.id(),
"<html><p>I was thinking about quitting the &ldquo;exporting&rdquo; to ", multipart.children().len()
"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 for attachment in message.attachments() {
assert_eq!( let PartKind::Message(nested) = attachment.kind() else {
message.body_text(0).unwrap(), continue;
concat!( };
"I was thinking about quitting the “exporting” to focus just on the", println!(
" “importing”,\nbut then I thought, why not do both? ☺\n" "\nNested message {}: {}",
) nested.id(),
); nested.subject().unwrap_or_default()
);
// Supports nested messages as well as multipart/digest for text in nested.text_bodies() {
let nested_message = message.attachment(0).unwrap().message().unwrap(); println!(" text: {text}");
}
for file in nested.attachments() {
println!(
" attachment {:?}: {} bytes",
file.attachment_name().unwrap_or_default(),
file.decoded_len()
);
}
}
}
assert_eq!( fn display(mailbox: Mailbox<'_>) -> String {
nested_message.subject().unwrap(), let address = mailbox.address().unwrap_or_default();
"Exporting my book about coffee tables" match mailbox.name() {
); Some(name) => format!("{name} <{address}>"),
None => address.to_string(),
}
}
// Handles UTF-* as well as many legacy encodings fn describe(part: MessagePart<'_>) {
assert_eq!( let content_type = part
nested_message.body_text(0).unwrap(), .content_type()
"ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!" .map(|content_type| {
format!(
"{}/{}",
content_type.ctype(),
content_type.subtype().unwrap_or_default()
)
})
.unwrap_or_else(|| "text/plain".to_string());
let summary = match part.kind() {
PartKind::Multipart => format!(
"boundary {:?}, {} children",
part.boundary().unwrap_or_default(),
part.children().len()
),
PartKind::Message(nested) => format!("holds message {}", nested.id()),
PartKind::Text | PartKind::Html => match part.text_checked() {
Some((text, problems)) if problems.is_empty() => {
format!("{} characters", text.chars().count())
}
Some((text, problems)) => format!(
"{} characters, decoding problems: {problems:?}",
text.chars().count()
),
None => String::new(),
},
PartKind::Binary | PartKind::InlineBinary => format!(
"{} bytes as written, {} decoded",
part.raw_body().len(),
part.decoded_len()
),
};
println!(
" part {} of message {} ({content_type}, {:?}): {summary}",
part.id(),
part.message().id(),
part.role()
); );
assert_eq!(
nested_message.body_html(0).unwrap(),
"<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>"
);
let nested_attachment = nested_message.attachment(0).unwrap();
assert_eq!(nested_attachment.len(), 42);
// Full RFC2231 support for continuations and character sets
assert_eq!(
nested_attachment.attachment_name().unwrap(),
"Book about ☕ tables.gif"
);
// Integrates with Serde
println!("{}", serde_json::to_string_pretty(&message).unwrap());
println!("{}", serde_yaml::to_string(&message).unwrap());
} }
+44 -24
View File
@@ -1,18 +1,16 @@
/* /*
* Copyright Stalwart Labs Ltd. See the COPYING * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
* file at the top-level directory of this distribution.
* *
* Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * SPDX-License-Identifier: Apache-2.0 OR MIT
* https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
* <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
* option. This file may not be copied, modified, or distributed
* except according to those terms.
*/ */
use mail_parser::*; use mail_parser::{MessageParser, MessagePart};
use std::{
env, fs, io,
path::{Path, PathBuf},
};
fn main() { const MESSAGE: &[u8] = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)
let input = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries)
To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends: To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends:
jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>; jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>;
Date: Sat, 20 Nov 2021 14:22:01 -0800 Date: Sat, 20 Nov 2021 14:22:01 -0800
@@ -29,7 +27,7 @@ cmcmRxdW87LDwvcD48cD5idXQgdGhlbiBJIHRob3VnaHQsIHdoeSBub3QgZG8gYm90aD8
gJiN4MjYzQTs8L3A+PC9odG1sPg== gJiN4MjYzQTs8L3A+PC9odG1sPg==
--festivus --festivus
Content-Type: message/rfc822; name="Exporting my book about coffee tables.eml" Content-Type: message/rfc822; name="Exporting my book about coffee tables.eml"
Content-Disposition: inline; filename="Exporting my book about coffee tables.eml" Content-Disposition: inline; filename="Exporting my book about coffee tables.eml"
Content-Transfer-Encoding: 7bit Content-Transfer-Encoding: 7bit
From: "Cosmo Kramer" <kramer@kramerica.com> From: "Cosmo Kramer" <kramer@kramerica.com>
@@ -55,19 +53,41 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
--festivus-- --festivus--
"#; "#;
write_attachments(&Message::parse(input).unwrap()); fn main() -> io::Result<()> {
let directory = env::args_os().nth(1).map_or_else(
|| env::temp_dir().join("mail-parser-attachments"),
PathBuf::from,
);
fs::create_dir_all(&directory)?;
let message = MessageParser::new()
.parse(MESSAGE)
.expect("the message parses");
for part in message.parts().filter(|part| part.is_attachment()) {
let path = directory.join(file_name(part));
fs::write(&path, part.decoded())?;
println!(
"{} ({} bytes, attachment of message {})",
path.display(),
part.decoded_len(),
part.message().id()
);
}
Ok(())
} }
fn write_attachments(message: &Message) { fn file_name(part: MessagePart<'_>) -> PathBuf {
for attachment in message.attachments() { let name = part
if !attachment.is_message() { .attachment_name()
std::fs::write( .map(str::to_string)
attachment.attachment_name().unwrap_or("Untitled"), .or_else(|| {
attachment.contents(), part.nested()
) .and_then(|nested| nested.subject())
.unwrap(); .map(|subject| format!("{subject}.eml"))
} else { })
write_attachments(attachment.message().unwrap()); .unwrap_or_default();
} Path::new(&name).file_name().map_or_else(
} || PathBuf::from(format!("part-{}", part.id())),
PathBuf::from,
)
} }
-4
View File
@@ -1,4 +0,0 @@
#!/bin/sh
perf record -F max --call-graph dwarf target/release/mail-parser
perf script | inferno-collapse-perf | inferno-flamegraph > flamegraph.svg
+230 -26
View File
@@ -1,62 +1,266 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3 version = 4
[[package]] [[package]]
name = "arbitrary" name = "arbitrary"
version = "1.0.2" version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "577b08a4acd7b99869f863c50011b01eb73424ccc798ecd996f2e24817adfca7" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.0.71" version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "79c2681d6594606957bbb8631c4b90a7fcaaa72cdb714743a437b156d6a7eedd" checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040"
[[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 = [ dependencies = [
"cfg-if", "find-msvc-tools",
"jobserver",
"libc",
"shlex",
] ]
[[package]] [[package]]
name = "libfuzzer-sys" name = "cfg-if"
version = "0.4.2" version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36a9a84a6e8b55dfefb04235e55edb2b9a2a18488fcae777a6bdaa6f06f1deb3" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "encodify"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fda1e5c788c2b59096e152ad1a76ce72a2ab80c75985eb94ca82de0b6555db7"
dependencies = [
"memchr",
"simdutf8",
]
[[package]]
name = "encoding_rs"
version = "0.8.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679"
dependencies = [
"cfg-if",
"core_detect",
"multiversion_no_op",
"rustversion",
"scopeguard",
"simdutf8",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "hashify"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66f5a65bf7824ada2de4a2cf9fa0981dabffc5392bb8550767c3c3d71ed52e4d"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom",
"libc",
]
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "libfuzzer-sys"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
dependencies = [ dependencies = [
"arbitrary", "arbitrary",
"cc", "cc",
"once_cell",
] ]
[[package]] [[package]]
name = "mail-parser" name = "mail-parser"
version = "0.8.0" version = "1.0.2"
dependencies = [ dependencies = [
"encodify",
"encoding_rs", "encoding_rs",
"hashify",
"memchr",
"serde",
"simdutf8",
] ]
[[package]] [[package]]
name = "mail-parser-fuzz" name = "mail-parser-fuzz"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"encodify",
"libfuzzer-sys", "libfuzzer-sys",
"mail-parser", "mail-parser",
"memchr",
"serde_json",
] ]
[[package]] [[package]]
name = "once_cell" name = "memchr"
version = "1.8.0" version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "syn"
version = "3.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+61 -8
View File
@@ -1,25 +1,78 @@
[package] [package]
name = "mail-parser-fuzz" name = "mail-parser-fuzz"
version = "0.0.0" version = "0.0.0"
authors = ["Automatically generated"]
publish = false publish = false
edition = "2018" edition = "2024"
[package.metadata] [package.metadata]
cargo-fuzz = true cargo-fuzz = true
[dependencies] [dependencies]
libfuzzer-sys = "0.4" libfuzzer-sys = "0.4"
memchr = "2.8"
serde_json = "1.0"
encodify = { version = "1.0" }
mail-parser = { path = "..", features = ["serde"] }
[dependencies.mail-parser] [features]
path = ".." default = ["full_encoding"]
full_encoding = ["mail-parser/full_encoding"]
# Prevent this from interfering with workspaces
[workspace] [workspace]
members = ["."] members = ["."]
[[bin]] [lib]
name = "mail_parser" path = "src/lib.rs"
path = "fuzz_targets/mail_parser.rs"
test = false test = false
doc = false doc = false
bench = false
[lints.rust]
rust_2018_idioms = { level = "deny", priority = -1 }
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "deny"
[lints.clippy]
unwrap_used = "deny"
[[bin]]
name = "parse"
path = "fuzz_targets/parse.rs"
test = false
doc = false
bench = false
[[bin]]
name = "limits"
path = "fuzz_targets/limits.rs"
test = false
doc = false
bench = false
[[bin]]
name = "fields"
path = "fuzz_targets/fields.rs"
test = false
doc = false
bench = false
[[bin]]
name = "charsets"
path = "fuzz_targets/charsets.rs"
test = false
doc = false
bench = false
[[bin]]
name = "kernels"
path = "fuzz_targets/kernels.rs"
test = false
doc = false
bench = false
[[bin]]
name = "mbox"
path = "fuzz_targets/mbox.rs"
test = false
doc = false
bench = false
+8
View File
@@ -0,0 +1,8 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser_fuzz::charsets;
fuzz_target!(|data: &[u8]| {
charsets::check(data);
});
+8
View File
@@ -0,0 +1,8 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser_fuzz::fields;
fuzz_target!(|data: &[u8]| {
fields::check(data);
});
+12
View File
@@ -0,0 +1,12 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser_fuzz::kernels;
use std::sync::Once;
static REPORTED: Once = Once::new();
fuzz_target!(|data: &[u8]| {
REPORTED.call_once(kernels::report);
kernels::check(data);
});
+25
View File
@@ -0,0 +1,25 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser::MessageParser;
use mail_parser_fuzz::walk::{self, Limits};
const MAX_DEPTH: u8 = 8;
const MAX_PARTS: u8 = 24;
const MAX_ENCODED: u8 = 4;
fuzz_target!(|data: &[u8]| {
let Some(([depth, parts, encoded], raw)) = data.split_first_chunk::<3>() else {
return;
};
let limits = Limits {
depth: usize::from(depth % MAX_DEPTH) + 1,
parts: usize::from(parts % MAX_PARTS) + 1,
encoded: usize::from(encoded % MAX_ENCODED),
};
let parser = MessageParser::new()
.max_depth(limits.depth)
.max_parts(limits.parts)
.max_encoded_nesting(limits.encoded);
walk::run(&parser, raw, Some(limits));
});
-91
View File
@@ -1,91 +0,0 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser::{
decoders::{
base64::base64_decode,
charsets::{
map::charset_decoder,
single_byte::decoder_iso_8859_1,
utf::{decoder_utf16, decoder_utf16_be, decoder_utf16_le, decoder_utf7},
},
hex::decode_hex,
html::{add_html_token, html_to_text, text_to_html},
quoted_printable::quoted_printable_decode,
},
parsers::{
fields::thread::{thread_name, trim_trailing_fwd},
MessageStream,
},
Message,
};
static RFC822_ALPHABET: &[u8] = b"0123456789abcdefghijklm:=- \r\n";
fuzz_target!(|data: &[u8]| {
for data_ in [
std::borrow::Cow::from(data),
std::borrow::Cow::from(into_alphabet(data, RFC822_ALPHABET)),
] {
let data = data_.as_ref();
// Fuzz every parsing function
MessageStream::new(data).parse_date();
MessageStream::new(data).parse_address();
MessageStream::new(data).parse_id();
MessageStream::new(data).parse_comma_separared();
MessageStream::new(data).parse_and_ignore();
MessageStream::new(data).parse_raw();
MessageStream::new(data).parse_unstructured();
MessageStream::new(data).parse_content_type();
MessageStream::new(data).parse_headers(&mut Vec::new());
MessageStream::new(data).parse_header_name();
MessageStream::new(data).decode_rfc2047();
MessageStream::new(data).seek_next_part(b"\n");
MessageStream::new(data).mime_part(b"\n");
MessageStream::new(data).seek_part_end(b"\n"[..].into());
MessageStream::new(data).skip_crlf();
MessageStream::new(data).is_multipart_end();
base64_decode(data);
MessageStream::new(data).decode_base64_word();
MessageStream::new(data).decode_base64_mime(b"\n");
quoted_printable_decode(data);
MessageStream::new(data).decode_quoted_printable_word();
MessageStream::new(data).decode_quoted_printable_mime(b"\n");
// Fuzz text 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);
thread_name(&str_data);
trim_trailing_fwd(&str_data);
// Fuzz decoding functions
decode_hex(data);
charset_decoder(data);
for decoder in &[
decoder_utf7,
decoder_utf16_le,
decoder_utf16_be,
decoder_utf16,
decoder_iso_8859_1,
] as &[for<'x> fn(&'x [u8]) -> String]
{
decoder(data);
}
// Fuzz the entire library
Message::parse(data);
}
});
fn into_alphabet(data: &[u8], alphabet: &[u8]) -> Vec<u8> {
data.iter()
.map(|&byte| alphabet[byte as usize % alphabet.len()])
.collect()
}
+8
View File
@@ -0,0 +1,8 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser_fuzz::mbox;
fuzz_target!(|data: &[u8]| {
mbox::check(data);
});
+12
View File
@@ -0,0 +1,12 @@
#![no_main]
use libfuzzer_sys::fuzz_target;
use mail_parser::MessageParser;
use mail_parser_fuzz::walk;
use std::sync::LazyLock;
static PARSER: LazyLock<MessageParser> = LazyLock::new(MessageParser::new);
fuzz_target!(|data: &[u8]| {
walk::run(&PARSER, data, None);
});
+194
View File
@@ -0,0 +1,194 @@
"\x0a"
"\x0d\x0a"
"\x0a\x0a"
"\x0d\x0a\x0d\x0a"
"\x0a--"
"\x0d\x0a--"
"--"
"\x0a "
"\x0a\x09"
": "
":"
";"
","
"="
"\""
"\\"
"("
")"
"<"
">"
"@"
"["
"]"
"From: "
"To: "
"Cc: "
"Bcc: "
"Reply-To: "
"Sender: "
"Subject: "
"Date: "
"Message-ID: "
"In-Reply-To: "
"References: "
"Return-Path: "
"Received: "
"MIME-Version: 1.0"
"Keywords: "
"Comments: "
"Resent-From: "
"Resent-Date: "
"List-Unsubscribe: "
"Content-Type: "
"Content-Transfer-Encoding: "
"Content-Disposition: "
"Content-ID: "
"Content-Language: "
"Content-Location: "
"Content-Description: "
"DKIM-Signature: "
"X-Mailer: "
"text/plain"
"text/html"
"text/enriched"
"multipart/mixed"
"multipart/alternative"
"multipart/related"
"multipart/digest"
"multipart/report"
"message/rfc822"
"message/global"
"message/delivery-status"
"application/octet-stream"
"image/png"
"boundary="
"boundary=\""
"charset="
"charset=\""
"name="
"filename="
"format=flowed"
"delsp=yes"
"name*0="
"name*1="
"name*0*="
"name*1*="
"filename*="
"utf-8''"
"iso-8859-1'en'"
"attachment"
"inline"
"attachment; filename="
"inline; filename="
"7bit"
"8bit"
"binary"
"base64"
"quoted-printable"
"x-uuencode"
"=?utf-8?q?"
"=?utf-8?b?"
"=?iso-8859-1?q?"
"=?us-ascii?Q?"
"?="
"=?"
"_"
"=20"
"=3D"
"=\x0a"
"=\x0d\x0a"
"=C3=A9"
"=="
"utf-8"
"us-ascii"
"iso-8859-1"
"iso-8859-15"
"windows-1252"
"utf-16"
"utf-16le"
"utf-16be"
"utf-7"
"koi8-r"
"shift_jis"
"iso-2022-jp"
"gb18030"
"big5"
"euc-kr"
"x-user-defined"
"\xfe\xff"
"\xff\xfe"
"\x1b$B"
"\x1b(B"
"+AKM-"
"+-"
"Mon, "
"Sat, 20 Nov 2021 14:22:01 -0800"
" GMT"
" +0000"
" -0000"
" (UTC)"
" EST"
" PDT"
"Jan"
"Feb"
"Dec"
"2021-11-20T14:22:01Z"
"from "
" by "
" with "
" via "
" id "
" for "
" ESMTPS"
" ESMTP"
" SMTP"
" LMTP"
" HTTP"
" (version=TLS1_3 cipher="
" helo="
" ehlo "
"[127.0.0.1]"
"[IPv6:::1]"
"localhost"
"(Postfix)"
"undisclosed-recipients:;"
"Group: a@b.c, d@e.f;"
"\"Last, First\" <first@example.com>"
"<a@b>"
"a@b.c"
"mailto:"
"Re: "
"Fwd: "
"Fw: "
"[list] "
"(fwd)"
"<html>"
"</html>"
"<body>"
"<br>"
"<br/>"
"<p>"
"</p>"
"<head>"
"<style>"
"</style>"
"<script>"
"<!--"
"-->"
"<meta charset=\""
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset="
"&amp;"
"&lt;"
"&nbsp;"
"&#233;"
"&#x263a;"
"From "
">From "
">>From "
"\x00"
"\xc3\xa9"
"\xe2\x98\x95"
"\xf0\x9d\x84\x9e"
"\xff"
"\x80"
+290
View File
@@ -0,0 +1,290 @@
use crate::{char_prefix, debug, valid, walk};
use encodify::{base64, qp};
use mail_parser::{
Charset, MessageParser, add_html_token,
decoders::charsets::{self, charset_decoder},
html_to_text, preview_html, preview_text, strip_charset_meta, text_to_html, truncate_html,
truncate_text,
};
use std::borrow::Cow;
const LABELS: [&str; 44] = [
"utf-8",
"utf-7",
"utf-16",
"utf-16le",
"utf-16be",
"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",
"windows-1250",
"windows-1251",
"windows-1252",
"windows-1253",
"windows-1254",
"windows-1255",
"windows-1256",
"windows-1257",
"windows-1258",
"koi8-r",
"koi8-u",
"macintosh",
"ibm850",
"tis-620",
"shift_jis",
"big5",
"euc-jp",
"euc-kr",
"gb18030",
"gbk",
"iso-2022-jp",
"windows-874",
"ibm866",
"x-mac-cyrillic",
"x-user-defined",
"hz-gb-2312",
];
const PREVIEW_LENS: [usize; 6] = [0, 1, 6, 7, 20, 300];
const PREFIX_CHARS: [usize; 5] = [0, 1, 5, 64, 1_000];
const PREFIX_BYTES: [usize; 6] = [0, 1, 7, 64, 300, 1_000];
const ELLIPSIS: &str = "...";
const APPENDED: &str = "appended";
const HTML_OPEN: &str = "<html><body>";
const HTML_CLOSE: &str = "</body></html>";
const MAX_LABEL: usize = 48;
const BOMS: [&[u8]; 3] = [b"\xef\xbb\xbf", b"\xff\xfe", b"\xfe\xff"];
#[derive(Debug, Clone, Copy)]
enum Transfer {
Identity,
Base64,
QuotedPrintable,
RawBase64,
RawQuotedPrintable,
}
const TRANSFERS: [(Transfer, &str); 5] = [
(Transfer::Identity, "8bit"),
(Transfer::Base64, "base64"),
(Transfer::QuotedPrintable, "quoted-printable"),
(Transfer::RawBase64, "base64"),
(Transfer::RawQuotedPrintable, "quoted-printable"),
];
pub fn check(data: &[u8]) {
let mut pieces = data.splitn(2, |&byte| byte == b'\n');
let (label, bytes) = match (pieces.next(), pieces.next()) {
(Some(label), Some(rest)) => (label, rest),
_ => (data.get(..MAX_LABEL).unwrap_or(data), data),
};
let charset = Charset::from_label(label);
labels(label, charset, bytes);
let fallback = data
.first()
.and_then(|&byte| LABELS.get(usize::from(byte) % LABELS.len()))
.copied()
.unwrap_or("utf-8");
let label = match (charset, std::str::from_utf8(label)) {
(Some(_), Ok(label)) if label.bytes().all(is_token) => label,
_ => fallback,
};
let charset = Charset::from_label(label.as_bytes()).unwrap_or_default();
let decoded = conversions(charset, bytes);
for (transfer, name) in TRANSFERS {
in_message(label, transfer, name, bytes, &decoded);
}
text_functions(&decoded);
text_functions(&String::from_utf8_lossy(data));
}
fn is_token(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':')
}
fn labels(label: &[u8], charset: Option<Charset>, bytes: &[u8]) {
assert_eq!(Charset::from_label(&label.to_ascii_uppercase()), charset);
assert_eq!(Charset::from_label(&label.to_ascii_lowercase()), charset);
let expected = charset.unwrap_or_default().decode(bytes);
assert_eq!(charsets::decode(label, bytes), expected);
let mut appended = String::from(APPENDED);
charsets::decode_append(label, bytes, &mut appended);
assert_eq!(appended.strip_prefix(APPENDED), Some(expected.as_ref()));
match charset_decoder(label) {
Some(decoder) => {
assert!(charset.is_some_and(|charset| charset != Charset::Utf8));
assert_eq!(decoder(bytes), expected);
}
None => assert!(charset.is_none_or(|charset| charset == Charset::Utf8)),
}
debug(&charset);
}
fn sniffs_bom(charset: Charset) -> bool {
matches!(
charset,
Charset::ShiftJis
| Charset::Big5
| Charset::EucJp
| Charset::EucKr
| Charset::Gb18030
| Charset::Gbk
| Charset::Iso2022Jp
| Charset::Ibm866
| Charset::XMacCyrillic
| Charset::XUserDefined
| Charset::Replacement
)
}
fn conversions(charset: Charset, bytes: &[u8]) -> Cow<'_, str> {
let decoded = charset.decode(bytes);
valid(&decoded);
if let Cow::Borrowed(text) = &decoded {
assert!(
text.as_bytes() == bytes
|| sniffs_bom(charset)
&& BOMS
.iter()
.any(|bom| bytes.strip_prefix(*bom) == Some(text.as_bytes())),
"borrowed text differs from its bytes"
);
}
assert_eq!(
charset.decode_owned(bytes.to_vec()),
decoded,
"decode_owned"
);
let mut appended = String::from(APPENDED);
charset.decode_append(bytes, &mut appended);
assert_eq!(
appended.strip_prefix(APPENDED),
Some(decoded.as_ref()),
"decode_append"
);
decoded
}
fn in_message(label: &str, transfer: Transfer, name: &str, bytes: &[u8], decoded: &str) {
let mut raw = format!(
"Content-Type: text/plain; charset=\"{label}\"\r\nContent-Transfer-Encoding: {name}\r\n\r\n"
)
.into_bytes();
match transfer {
Transfer::Identity | Transfer::RawBase64 | Transfer::RawQuotedPrintable => {
raw.extend_from_slice(bytes)
}
Transfer::Base64 => raw.extend_from_slice(base64::MIME.encode(bytes).as_bytes()),
Transfer::QuotedPrintable => raw.extend_from_slice(qp::BINARY.encode(bytes).as_bytes()),
}
let message = MessageParser::new()
.parse(&raw)
.expect("a message with a header parses");
walk::check_message(&message);
let part = message.root().root_part();
let body = part.decoded();
if matches!(transfer, Transfer::Identity | Transfer::Base64) {
assert_eq!(body.as_ref(), bytes, "{transfer:?} body");
}
let text = part.text().expect("a text/plain part has text");
if body.as_ref() == bytes {
assert_eq!(text, decoded, "{label} text differs from Charset::decode");
}
let chars = text.chars().count();
for max_chars in PREFIX_CHARS
.into_iter()
.chain([chars.saturating_sub(1), chars, chars + 1])
{
assert_eq!(
part.text_prefix(max_chars).as_deref(),
Some(char_prefix(&text, max_chars)),
"{label} {transfer:?} text_prefix({max_chars})"
);
}
for max_bytes in
PREFIX_BYTES
.into_iter()
.chain([text.len().saturating_sub(1), text.len(), text.len() + 1])
{
assert_eq!(
part.text_prefix_bytes(max_bytes).as_deref(),
Some(byte_prefix(&text, max_bytes)),
"{label} {transfer:?} text_prefix_bytes({max_bytes})"
);
let probe = part
.text_prefix_bytes(max_bytes + char::MAX_LEN_UTF8)
.expect("a text/plain part has text");
assert_eq!(
probe.len() > max_bytes,
text.len() > max_bytes,
"{label} {transfer:?} text_prefix_bytes({max_bytes} + {})",
char::MAX_LEN_UTF8
);
}
}
fn byte_prefix(text: &str, max_bytes: usize) -> &str {
text.get(..text.floor_char_boundary(max_bytes))
.unwrap_or(text)
}
fn text_functions(text: &str) {
let plain = html_to_text(text);
valid(&plain);
let html = text_to_html(text);
valid(&html);
assert!(html.starts_with(HTML_OPEN) && html.ends_with(HTML_CLOSE));
assert!(!html.contains('\r'));
valid(&strip_charset_meta(text));
let mut token = String::new();
add_html_token(&mut token, text.as_bytes(), true);
valid(&token);
let stripped = text.replace('\r', "");
for max_len in PREVIEW_LENS {
let preview = preview_text(text, max_len);
check_cut(&preview, &stripped, max_len);
assert_eq!(truncate_text(text, max_len), preview);
let html_preview = preview_html(text, max_len);
valid(&html_preview);
assert!(html_preview.len() <= max_len && !html_preview.contains('\r'));
assert_eq!(
html_preview,
preview_text(&plain, max_len),
"preview_html differs from preview_text of html_to_text"
);
let truncated = truncate_html(text, max_len);
valid(&truncated);
assert!(truncated.len() <= max_len && !truncated.contains('\r'));
if stripped.len() <= max_len {
assert_eq!(truncated, stripped);
}
}
}
fn check_cut(preview: &str, stripped: &str, max_len: usize) {
valid(preview);
assert!(preview.len() <= max_len, "preview longer than {max_len}");
assert!(!preview.contains('\r'));
if stripped.len() <= max_len {
assert_eq!(preview, stripped);
return;
}
let kept = if stripped.starts_with(preview) {
preview
} else {
preview
.strip_suffix(ELLIPSIS)
.expect("a cut preview ends with an ellipsis")
};
assert!(stripped.starts_with(kept), "preview is not a prefix");
}
+160
View File
@@ -0,0 +1,160 @@
use crate::{debug, display, valid, walk, within};
use mail_parser::{
DateTime, HeaderForm, HeaderName, MessageParser, parse_address_detail_part,
parse_address_domain, parse_address_local_part, parse_address_user_part, thread_name,
};
use std::{
borrow::Cow,
cmp::Ordering,
hash::{DefaultHasher, Hash, Hasher},
sync::LazyLock,
};
const FIELD: &str = "X-Fuzz";
const FIELD_END: &[u8] = b"\n\n";
static PARSERS: LazyLock<[MessageParser; 9]> =
LazyLock::new(|| walk::FORMS.map(|form| MessageParser::new().header(FIELD, form)));
type AddressHelper = fn(&str) -> Option<&str>;
const ADDRESS_HELPERS: [AddressHelper; 4] = [
parse_address_local_part,
parse_address_domain,
parse_address_user_part,
parse_address_detail_part,
];
pub fn check(data: &[u8]) {
for form in walk::FORMS {
let parsed = form.parse(data);
walk::header_value(parsed.value());
debug(&parsed);
}
in_message(data);
let text = String::from_utf8_lossy(data);
dates(&text, data);
names(&text);
if let Some((name, _)) = text.split_once(':') {
names(name);
names(name.trim());
}
for helper in ADDRESS_HELPERS {
if let Some(part) = helper(&text) {
valid(part);
assert!(within(part.as_bytes(), text.as_bytes()));
}
}
let thread = thread_name(&text);
valid(thread);
assert!(within(thread.as_bytes(), text.as_bytes()));
}
fn in_message(data: &[u8]) {
let mut raw = Vec::with_capacity(FIELD.len() + 1 + data.len() + FIELD_END.len());
raw.extend_from_slice(FIELD.as_bytes());
raw.push(b':');
raw.extend_from_slice(data);
raw.extend_from_slice(FIELD_END);
for (parser, form) in PARSERS.iter().zip(walk::FORMS) {
let message = parser.parse(&raw).expect("a message with a header parses");
let header = message
.headers()
.iter()
.next()
.expect("the message has its header");
assert_eq!(header.raw_name(), FIELD);
let parsed = header.parse_as(form);
assert_eq!(
parsed.value(),
header.value(),
"{form:?}: in-message value differs from parse_as"
);
assert!(
form.parse(header.raw_value()) == parsed,
"{form:?}: HeaderForm::parse differs from parse_as"
);
}
}
fn dates(text: &str, data: &[u8]) {
let rfc822 = DateTime::parse_rfc822(text);
let header = HeaderForm::Date.parse(text.as_bytes());
assert_eq!(
rfc822,
header.value().as_datetime(),
"parse_rfc822 differs from the Date form"
);
for date in [rfc822, DateTime::parse_rfc3339(text)]
.into_iter()
.flatten()
{
walk::datetime(date);
}
if let Some(bytes) = data.first_chunk::<8>() {
walk::datetime(DateTime::from_timestamp(i64::from_le_bytes(*bytes)));
}
}
fn is_ftext(byte: u8) -> bool {
matches!(byte, b'!'..=b'9' | b';'..=b'~')
}
fn fingerprint(name: &HeaderName<'_>) -> u64 {
let mut hasher = DefaultHasher::new();
name.hash(&mut hasher);
hasher.finish()
}
fn same_name(left: &HeaderName<'_>, right: &HeaderName<'_>) {
assert_eq!(left, right);
assert_eq!(left.cmp(right), Ordering::Equal);
assert_eq!(fingerprint(left), fingerprint(right));
}
fn names(candidate: &str) {
let parsed = HeaderName::parse(candidate);
let allowed = !candidate.is_empty() && candidate.bytes().all(is_ftext);
assert_eq!(
parsed.is_some(),
allowed,
"HeaderName::parse({candidate:?})"
);
let converted = HeaderName::from(candidate);
check_name(&converted, candidate);
if let Some(name) = &parsed {
same_name(name, &converted);
check_name(name, candidate);
}
same_name(&converted, &HeaderName::from(candidate.to_string()));
same_name(&converted, &HeaderName::from(Cow::Borrowed(candidate)));
same_name(&converted, &HeaderName::Other(Cow::Borrowed(candidate)));
same_name(
&converted,
&HeaderName::Other(Cow::Owned(candidate.to_ascii_uppercase())),
);
}
fn check_name(name: &HeaderName<'_>, spelling: &str) {
let text = name.as_str();
valid(text);
assert!(
text.eq_ignore_ascii_case(spelling),
"{name:?} spelled {spelling:?}"
);
display(name);
debug(name);
same_name(&name.clone().into_owned(), name);
assert_eq!(Cow::from(name.clone()), text);
assert_eq!(String::from(name.clone()), text);
let _ = (
name.is_other(),
name.is_mime_header(),
name.is_structured(),
name.as_static_str(),
);
let json = serde_json::to_string(name).expect("a header name serializes");
let back: HeaderName<'static> =
serde_json::from_str(&json).expect("a serialized header name deserializes");
same_name(&back, name);
}
+245
View File
@@ -0,0 +1,245 @@
use crate::scan::{self, ByteSet, swar};
use mail_parser::scan::Kernel;
use std::sync::LazyLock;
const SHIFTS: usize = 64;
const SET_SHIFTS: usize = 16;
const SPAN: usize = 256;
const MAX_MEMBERS: usize = 16;
const ASCII_MASK: u8 = 0x7f;
const BELOW_LIMIT: u8 = 0x80;
const CLASS: u8 = 1;
const BITMAP_BYTES: usize = 16;
const BITS: usize = 8;
const HIGH_BIT: usize = 7;
const FIELD_STOPS: u8 = 0x21;
static SIMPLE_NAME: ByteSet = ByteSet::with_marks(b"\n\r,;<\"(:=", b"@");
static SIMPLE_QUOTED: ByteSet = ByteSet::new(b"\n\r\"\\=");
static SIMPLE_ADDRESS: ByteSet = ByteSet::new(b"\n\r>\\(=");
static QUOTED_LOCAL_PART: ByteSet = ByteSet::new(b"\n\"\\");
static TOKEN_STOPS: LazyLock<ByteSet> = LazyLock::new(token_stops);
type Scan = fn(Kernel, &[u8], usize) -> Option<usize>;
const SCANS: [(Scan, &str); 2] = [
(Kernel::dash_line, "dash_line"),
(Kernel::field_end, "field_end"),
];
pub fn report() {
let public: Vec<_> = Kernel::available().map(Kernel::name).collect();
let sets: Vec<_> = scan::Kernel::available().map(scan::Kernel::name).collect();
eprintln!(
"kernels: scan {}; set {}",
public.join(", "),
sets.join(", ")
);
}
pub fn check(data: &[u8]) {
variants(data, SHIFTS, scans);
for set in [
&SIMPLE_NAME,
&SIMPLE_QUOTED,
&SIMPLE_ADDRESS,
&QUOTED_LOCAL_PART,
&TOKEN_STOPS,
] {
sets(set, data);
}
if let Some((custom, hay)) = custom_sets(data) {
for set in &custom {
sets(set, hay);
}
}
let (low, high, limit) = match data {
[low, high, limit, ..] => (
low & ASCII_MASK,
high & ASCII_MASK,
limit % (BELOW_LIMIT + 1),
),
_ => (b'A', b'Z', FIELD_STOPS),
};
for skip in 0..data.len().min(swar::WORD) {
words(data.get(skip..).unwrap_or_default(), low, high, limit);
}
}
fn variants(data: &[u8], shifts: usize, mut each: impl FnMut(&[u8])) {
each(data);
let len = data.len();
for skip in 1..len.min(shifts) {
each(data.get(skip..len.min(skip + SPAN)).unwrap_or_default());
}
for cut in 1..len.min(shifts) {
let end = len - cut;
let tail: Box<[u8]> =
Box::from(data.get(end.saturating_sub(SPAN)..end).unwrap_or_default());
each(&tail);
}
}
fn scans(hay: &[u8]) {
for kernel in Kernel::available() {
for (scan, name) in SCANS {
let mut from = 0;
loop {
let expected = scan(Kernel::SCALAR, hay, from);
assert_eq!(
scan(kernel, hay, from),
expected,
"{} {name} from {from} over {} bytes",
kernel.name(),
hay.len()
);
match expected {
Some(hit) => from = hit + 1,
None => break,
}
}
for from in [hay.len(), hay.len() + 1, usize::MAX] {
assert_eq!(scan(kernel, hay, from), scan(Kernel::SCALAR, hay, from));
}
}
}
}
fn token_stops() -> ByteSet {
let classes: [u8; 256] = std::array::from_fn(|byte| {
let byte = byte as u8;
let token = byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`{|}~".contains(&byte);
if token || !byte.is_ascii() { CLASS } else { 0 }
});
ByteSet::excluding(&classes, CLASS)
}
fn custom_sets(data: &[u8]) -> Option<([ByteSet; 3], &[u8])> {
let (&count, rest) = data.split_first()?;
let (stops, rest) = rest.split_at_checked(1 + usize::from(count) % MAX_MEMBERS)?;
let (&count, rest) = rest.split_first()?;
let (marks, rest) = rest.split_at_checked(usize::from(count) % (MAX_MEMBERS + 1))?;
let (bitmap, hay) = rest.split_first_chunk::<BITMAP_BYTES>()?;
let bucket = |byte: u8| 1u8 << (byte >> 4);
let mut stop_bytes = [0u8; MAX_MEMBERS];
let mut stop_buckets = 0u8;
for (out, &byte) in stop_bytes.iter_mut().zip(stops) {
*out = byte & ASCII_MASK;
stop_buckets |= bucket(*out);
}
let mut mark_bytes = [0u8; MAX_MEMBERS];
let mut marked = 0;
for byte in marks.iter().map(|&byte| byte & ASCII_MASK) {
if bucket(byte) & stop_buckets == 0
&& let Some(out) = mark_bytes.get_mut(marked)
{
*out = byte;
marked += 1;
}
}
let classes: [u8; 256] = std::array::from_fn(|byte| {
let bit = bitmap
.get(byte / BITS)
.is_some_and(|bits| bits >> (byte % BITS) & 1 == 1);
if bit || byte >= usize::from(BELOW_LIMIT) {
CLASS
} else {
0
}
});
let stops = stop_bytes.get(..stops.len()).unwrap_or_default();
let marks = mark_bytes.get(..marked).unwrap_or_default();
Some((
[
ByteSet::new(stops),
ByteSet::with_marks(stops, marks),
ByteSet::excluding(&classes, CLASS),
],
hay,
))
}
fn sets(set: &ByteSet, hay: &[u8]) {
let len = hay.len();
for end in [len.saturating_sub(1), len / 2, usize::MAX] {
set_scans(set, hay, end);
}
variants(hay, SET_SHIFTS, |window| {
set_scans(set, window, window.len())
});
}
fn set_scans(set: &ByteSet, hay: &[u8], end: usize) {
for kernel in scan::Kernel::available() {
let mut from = 0;
loop {
let expected = scan::Kernel::SCALAR.first_in_set(set, hay, from, end);
assert_eq!(
kernel.first_in_set(set, hay, from, end),
expected,
"{} first_in_set {from}..{end} over {} bytes",
kernel.name(),
hay.len()
);
assert_eq!(
kernel.stop_in_set(set, hay, from, end),
scan::Kernel::SCALAR.stop_in_set(set, hay, from, end),
"{} stop_in_set {from}..{end} over {} bytes",
kernel.name(),
hay.len()
);
match expected {
Some(hit) => from = hit + 1,
None => break,
}
}
for from in [end, end.saturating_add(1), hay.len() + 1] {
assert_eq!(
kernel.first_in_set(set, hay, from, end),
scan::Kernel::SCALAR.first_in_set(set, hay, from, end)
);
assert_eq!(
kernel.stop_in_set(set, hay, from, end),
scan::Kernel::SCALAR.stop_in_set(set, hay, from, end)
);
}
}
}
fn words(hay: &[u8], low: u8, high: u8, limit: u8) {
for chunk in hay.chunks(swar::WORD) {
let mut bytes = [0u8; swar::WORD];
bytes
.iter_mut()
.zip(chunk)
.for_each(|(out, &byte)| *out = byte);
let word = swar::load(chunk);
assert_eq!(word, u64::from_le_bytes(bytes), "swar::load");
let first = |mask: u64| (mask != 0).then(|| swar::first_byte(mask));
assert_eq!(
first(swar::equal_bytes(word, b':')),
bytes.iter().position(|&byte| byte == b':')
);
assert_eq!(
first(swar::zero_bytes(word)),
bytes.iter().position(|&byte| byte == 0)
);
assert_eq!(
first(swar::bytes_below(word, limit)),
bytes.iter().position(|&byte| byte < limit),
"bytes_below {limit}"
);
let range = swar::ascii_in_range(word, low, high);
for (index, byte) in bytes.iter().enumerate() {
assert_eq!(
range >> (index * BITS + HIGH_BIT) & 1 == 1,
(low..=high).contains(byte),
"ascii_in_range {low}..={high} byte {byte}"
);
}
assert_eq!(
swar::ascii_lowercase(word).to_le_bytes(),
bytes.map(|byte| byte.to_ascii_lowercase())
);
}
}
+41
View File
@@ -0,0 +1,41 @@
#[allow(dead_code, unreachable_pub)]
#[path = "../../src/scan/mod.rs"]
mod scan;
pub mod charsets;
pub mod fields;
pub mod kernels;
pub mod mbox;
pub mod walk;
use std::{
fmt::{Debug, Display},
io::{self, Write},
};
pub fn valid(text: &str) {
assert!(
std::str::from_utf8(text.as_bytes()).is_ok(),
"invalid UTF-8 returned as &str"
);
}
pub fn debug(value: &impl Debug) {
let _ = write!(io::sink(), "{value:?}");
}
pub fn display(value: &impl Display) {
let _ = write!(io::sink(), "{value}");
}
pub fn within(inner: &[u8], outer: &[u8]) -> bool {
let (range, outer) = (inner.as_ptr_range(), outer.as_ptr_range());
inner.is_empty() || range.start >= outer.start && range.end <= outer.end
}
pub fn char_prefix(text: &str, chars: usize) -> &str {
text.char_indices()
.nth(chars)
.and_then(|(end, _)| text.get(..end))
.unwrap_or(text)
}
+109
View File
@@ -0,0 +1,109 @@
use mail_parser::mailbox::mbox::{Message, MessageIterator};
use std::io::{self, BufRead, BufReader, Read};
const SEPARATOR: &[u8] = b"From ";
const QUOTE: u8 = b'>';
const CAPACITIES: [usize; 7] = [1, 2, 3, 7, 16, 64, 4_096];
const CHUNK_SIZES: usize = 4;
const MAX_CHUNK: usize = 9;
const CHUNKED_CAPACITY: usize = 16;
#[derive(Debug, PartialEq, Eq)]
struct Expected {
from: String,
contents: Vec<u8>,
}
fn unquoted(line: &[u8]) -> &[u8] {
let quotes = line.iter().take_while(|&&byte| byte == QUOTE).count();
match (line.get(quotes..), line.get(1..)) {
(Some(rest), Some(unquoted)) if quotes > 0 && rest.starts_with(SEPARATOR) => unquoted,
_ => line,
}
}
fn sender(line: &[u8]) -> String {
line.strip_prefix(SEPARATOR)
.and_then(|rest| std::str::from_utf8(rest).ok())
.and_then(|rest| rest.split_once(' '))
.map_or_else(String::new, |(from, _)| from.trim().to_string())
}
fn reference(mbox: &[u8]) -> Vec<Expected> {
let mut messages = Vec::new();
let mut current: Option<Expected> = None;
for line in mbox.split_inclusive(|&byte| byte == b'\n') {
if line.starts_with(SEPARATOR) {
messages.extend(current.replace(Expected {
from: sender(line),
contents: Vec::new(),
}));
} else if let Some(message) = &mut current {
message.contents.extend_from_slice(unquoted(line));
}
}
messages.extend(current);
messages
}
fn read_all(reader: impl BufRead) -> Vec<Message> {
MessageIterator::new(reader)
.map(|message| message.expect("an in-memory mbox is readable"))
.collect()
}
struct Chunked<'x> {
data: &'x [u8],
sizes: [usize; CHUNK_SIZES],
next: usize,
}
impl Read for Chunked<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let size = self.sizes.get(self.next).copied().unwrap_or(1);
self.next = (self.next + 1) % CHUNK_SIZES;
let len = size.min(buf.len()).min(self.data.len());
let (head, tail) = self.data.split_at(len);
if let Some(out) = buf.get_mut(..len) {
out.copy_from_slice(head);
}
self.data = tail;
Ok(len)
}
}
pub fn check(data: &[u8]) {
let whole = read_all(data);
let expected = reference(data);
assert_eq!(whole.len(), expected.len(), "message count");
for (message, expected) in whole.iter().zip(&expected) {
assert_eq!(message.from(), expected.from, "separator sender");
assert_eq!(message.contents(), expected.contents, "contents");
let _ = message.internal_date();
}
for capacity in CAPACITIES {
assert_eq!(
read_all(BufReader::with_capacity(capacity, data)),
whole,
"capacity {capacity}"
);
}
let mut sizes = [1; CHUNK_SIZES];
for (size, &byte) in sizes.iter_mut().zip(data.iter().rev()) {
*size = 1 + usize::from(byte) % MAX_CHUNK;
}
let chunked = Chunked {
data,
sizes,
next: 0,
};
assert_eq!(
read_all(BufReader::with_capacity(CHUNKED_CAPACITY, chunked)),
whole,
"chunked reader {sizes:?}"
);
for message in whole {
let contents = message.unwrap_contents();
let _ = mail_parser::MessageParser::new().parse(&contents);
}
}
+65
View File
@@ -0,0 +1,65 @@
use crate::{char_prefix, debug, valid};
use mail_parser::{MessagePart, PartKind, strip_charset_meta};
const PREFIX_CHARS: [usize; 7] = [0, 1, 2, 3, 7, 64, 1_000];
const PROBE_CHARS: usize = 8;
const APPENDED: &str = "appended";
pub fn check(part: MessagePart<'_>) {
let decoded = part.decoded();
assert_eq!(part.decoded_len(), decoded.len(), "decoded_len");
let (checked, problems) = part.decoded_checked();
assert_eq!(checked, decoded, "decoded_checked");
assert_eq!(
problems.names().count(),
problems.bits().count_ones() as usize
);
debug(&problems);
let mut appended = APPENDED.as_bytes().to_vec();
part.decode_into(&mut appended);
assert_eq!(
appended.strip_prefix(APPENDED.as_bytes()),
Some(decoded.as_ref()),
"decode_into"
);
let Some(text) = part.text() else {
assert!(!part.is_text());
assert!(part.text_checked().is_none());
assert!(part.text_prefix(PROBE_CHARS).is_none());
assert!(!part.text_into(&mut String::new()));
assert!(part.html_utf8().is_none());
return;
};
valid(&text);
assert!(part.is_text());
let (checked, problems) = part.text_checked().expect("a text part has checked text");
assert_eq!(checked, text, "text_checked");
debug(&problems);
let mut appended = String::from(APPENDED);
assert!(part.text_into(&mut appended));
assert_eq!(
appended.strip_prefix(APPENDED),
Some(text.as_ref()),
"text_into"
);
let chars = text.chars().count();
for max_chars in PREFIX_CHARS
.into_iter()
.chain([chars.saturating_sub(1), chars, chars + 1])
{
let prefix = part.text_prefix(max_chars);
assert_eq!(
prefix.as_deref(),
Some(char_prefix(&text, max_chars)),
"text_prefix({max_chars})"
);
}
match part.kind() {
PartKind::Html => {
let html = part.html_utf8().expect("an HTML part has UTF-8 HTML");
valid(&html);
assert_eq!(html, strip_charset_meta(&text), "html_utf8");
}
_ => assert!(part.html_utf8().is_none()),
}
}
+222
View File
@@ -0,0 +1,222 @@
use super::values::header_value;
use crate::{debug, valid};
use mail_parser::{Header, HeaderForm, HeaderName, HeaderValue, Headers};
pub const FORMS: [HeaderForm; 9] = [
HeaderForm::Raw,
HeaderForm::Text,
HeaderForm::Addresses,
HeaderForm::MessageIds,
HeaderForm::CommaList,
HeaderForm::Date,
HeaderForm::ContentType,
HeaderForm::Received,
HeaderForm::Ignore,
];
const CHECKED_LOOKUPS: usize = 64;
const CHECKED_REPARSES: usize = 256;
const MAX_LINE_BREAK: usize = 2;
macro_rules! getters {
($target:expr) => {{
let target = &$target;
for text in [
target.subject(),
target.comments(),
target.mime_version(),
target.thread_name(),
target.message_id(),
target.return_address(),
]
.into_iter()
.flatten()
{
$crate::valid(text);
}
assert_eq!(
target.thread_name(),
target.subject().map(mail_parser::thread_name)
);
for list in [
target.from(),
target.to(),
target.cc(),
target.bcc(),
target.reply_to(),
target.sender(),
target.resent_to(),
target.resent_from(),
target.resent_cc(),
target.resent_bcc(),
target.resent_sender(),
target.list_archive(),
target.list_help(),
target.list_id(),
target.list_owner(),
target.list_post(),
target.list_subscribe(),
target.list_unsubscribe(),
]
.into_iter()
.flatten()
.chain(target.all_to())
.chain(target.all_cc())
.chain(target.all_bcc())
{
$crate::walk::addresses(list);
}
for date in [target.date(), target.resent_date()].into_iter().flatten() {
$crate::walk::datetime(date);
}
for list in [
target.in_reply_to(),
target.references(),
target.resent_message_id(),
target.return_path(),
target.keywords(),
]
.into_iter()
.flatten()
{
$crate::walk::text_list(list);
}
for trace in target.received().into_iter().chain(target.all_received()) {
$crate::walk::received(trace);
}
}};
}
pub(crate) use getters;
pub fn check_headers(headers: Headers<'_>, source: &[u8], part_header: usize, body: usize) {
let len = headers.len();
assert_eq!(headers.is_empty(), len == 0);
assert_eq!(headers.iter().len(), len);
assert_eq!(headers.iter().rev().count(), len);
assert_eq!((&headers).into_iter().count(), len);
let mut previous = None;
for (index, header) in headers.iter().enumerate() {
check_offsets(header, source, part_header, body);
assert!(
previous < Some(header.offset_field()),
"headers out of order"
);
previous = Some(header.offset_field());
check_name(headers, header, index < CHECKED_LOOKUPS);
if index < CHECKED_REPARSES {
check_value(header);
} else {
header_value(header.value());
}
debug(&header);
}
let _ = headers.has_known();
getters!(headers);
debug(&headers);
}
fn check_offsets(header: Header<'_>, source: &[u8], part_header: usize, body: usize) {
let (field, start, end) = (
header.offset_field() as usize,
header.offset_start() as usize,
header.offset_end() as usize,
);
assert!(
part_header <= field && field < start && start <= end && end <= source.len(),
"header {:?} offsets {field}..{start}..{end}, part header {part_header}, source {}",
header.raw_name(),
source.len()
);
assert!(start <= body, "header value starts past the body");
if end > body {
let tail = source.get(body..end).unwrap_or_default();
assert!(
tail.len() <= MAX_LINE_BREAK && tail.iter().all(|byte| matches!(byte, b'\r' | b'\n')),
"header {:?} ends {} bytes past the body offset",
header.raw_name(),
end - body
);
}
assert_eq!(source.get(start..end), Some(header.raw_value()));
let name = header.raw_name();
valid(name);
let region = source.get(field..start).unwrap_or_default();
let found = if name.contains(char::REPLACEMENT_CHARACTER) {
String::from_utf8_lossy(region).contains(name)
} else {
region
.windows(name.len())
.any(|window| window == name.as_bytes())
};
assert!(
name.is_empty() || found,
"raw_name {name:?} not in its region {region:?}"
);
}
fn check_name(headers: Headers<'_>, header: Header<'_>, lookups: bool) {
let name = header.name();
let raw = header.raw_name();
valid(name.as_str());
match &name {
HeaderName::Other(other) => assert_eq!(other.as_ref(), raw),
known => assert!(
known.as_str().eq_ignore_ascii_case(raw),
"known name {known:?} spelled {raw:?}"
),
}
if !lookups {
return;
}
let last = headers
.get(&name)
.expect("get finds the name of a present header");
assert!(last.offset_field() >= header.offset_field());
assert!(
headers
.all(&name)
.any(|same| same.offset_field() == header.offset_field())
);
assert!(headers.contains(&name));
assert_eq!(headers.value(&name), Some(last.value()));
if !raw.is_empty() {
let by_raw = headers.get(raw).map(|found| found.offset_field());
assert_eq!(by_raw, Some(last.offset_field()));
}
}
fn own_forms(value: HeaderValue<'_>) -> &'static [HeaderForm] {
match value {
HeaderValue::Empty => &[],
HeaderValue::Text(_) => &[HeaderForm::Text, HeaderForm::Raw],
HeaderValue::TextList(_) => &[HeaderForm::MessageIds, HeaderForm::CommaList],
HeaderValue::Address(_) => &[HeaderForm::Addresses],
HeaderValue::DateTime(_) => &[HeaderForm::Date],
HeaderValue::ContentType(_) => &[HeaderForm::ContentType],
HeaderValue::Received(_) => &[HeaderForm::Received],
}
}
fn check_value(header: Header<'_>) {
let value = header.value();
header_value(value);
let forms = own_forms(value);
let mut matched = forms.is_empty();
for form in FORMS {
let parsed = header.parse_as(form);
let reparsed = parsed.value();
header_value(reparsed);
matched |= forms.contains(&form) && reparsed == value;
assert!(
form.parse(header.raw_value()) == parsed,
"parse_as({form:?}) differs from HeaderForm::parse of the raw value"
);
debug(&parsed);
}
assert!(
matched,
"value of {:?} differs from parse_as in its own form",
header.raw_name()
);
}
+493
View File
@@ -0,0 +1,493 @@
mod body;
mod headers;
mod values;
pub use headers::{FORMS, check_headers};
pub use values::{addresses, content_type, datetime, header_value, received, text_list};
use crate::{debug, valid, within};
use mail_parser::{
Encoding, Message, MessageBuffers, MessageParser, MessagePart, MessageRef, PartId, PartKind,
PartRole, Source, html_to_text, preview_html, preview_text, text_to_html,
};
use std::{borrow::Cow, ptr};
const PREVIEW_LENS: [usize; 5] = [0, 3, 7, 20, 256];
const CHECKED_BOUNDARIES: usize = 16;
const CHECKED_BODIES: usize = 2;
#[derive(Debug, Clone, Copy)]
pub struct Limits {
pub depth: usize,
pub parts: usize,
pub encoded: usize,
}
pub fn run(parser: &MessageParser, raw: &[u8], limits: Option<Limits>) {
let parsed = parser.parse(raw);
let headers_only = parser.parse_headers(raw);
assert_eq!(parsed.is_some(), headers_only.is_some());
if let Some(message) = &headers_only {
check_message(message);
check_headers_only(message, parsed.as_ref());
limits
.into_iter()
.for_each(|limits| check_limits(message, limits));
}
let json = parsed.as_ref().map(|message| {
check_message(message);
limits
.into_iter()
.for_each(|limits| check_limits(message, limits));
serialize(message)
});
if let Some(message) = parsed {
assert_eq!(
Some(serialize(&message.clone().into_owned())),
json,
"into_owned"
);
}
assert_eq!(
parser.parse_owned(raw.to_vec()).as_ref().map(serialize),
json,
"parse_owned"
);
reuse(parser, raw, json.as_deref());
}
fn serialize(message: &Message<'_>) -> String {
serde_json::to_string(message).expect("a message serializes")
}
fn reuse(parser: &MessageParser, raw: &[u8], json: Option<&str>) {
let (_, second) = raw.split_at(raw.len() / 2);
let second_json = parser.parse(second).as_ref().map(serialize);
let mut buffers = MessageBuffers::new();
for (input, expected) in [(raw, json), (second, second_json.as_deref()), (raw, json)] {
let reused = parser.parse_with(input, &mut buffers);
assert_eq!(
reused.as_ref().map(serialize).as_deref(),
expected,
"parse_with"
);
if let Some(message) = reused {
buffers = message.into_buffers();
}
}
}
fn check_headers_only(message: &Message<'_>, full: Option<&Message<'_>>) {
assert_eq!(message.messages().len(), 1);
assert_eq!(message.parts().len(), 1);
let root = message.root();
assert_eq!(root.text_body().len(), 0);
assert_eq!(root.html_body().len(), 0);
assert_eq!(root.attachments().len(), 0);
assert!(!root.has_attachments());
let (part, raw) = (root.root_part(), message.raw());
assert_eq!(part.offset_end() as usize, raw.len());
if let Some(full) = full {
let full_part = full.root().root_part();
assert_eq!(part.offset_header(), full_part.offset_header());
assert_eq!(part.offset_body(), full_part.offset_body());
assert_eq!(
serde_json::to_string(&part.headers()).ok(),
serde_json::to_string(&full_part.headers()).ok(),
"parse_headers and parse disagree on the root header block"
);
}
}
pub fn check_message(message: &Message<'_>) {
for (part, id) in message.parts().zip(0..) {
assert_eq!(part.id(), id);
check_part(part);
}
let missing = PartId::try_from(message.parts().len()).ok();
assert!(missing.and_then(|id| message.part(id)).is_none());
let listed: usize = message.parts().map(|part| part.children().len()).sum();
let with_parent = message
.parts()
.filter(|part| part.parent().is_some())
.count();
assert_eq!(
listed, with_parent,
"children lists and parent links differ"
);
for (nested, id) in message.messages().zip(0..) {
assert_eq!(nested.id(), id);
check_ref(message, nested);
}
for boundary in message
.parts()
.filter_map(|part| part.boundary())
.take(CHECKED_BOUNDARIES)
{
let found = message.part_by_boundary(boundary);
assert_eq!(found.and_then(|part| part.boundary()), Some(boundary));
}
let root = message.root();
assert_eq!(root.id(), 0);
assert_eq!(root.source(), Source::Raw);
assert_eq!(message.subject(), root.subject());
assert_eq!(message.from(), root.from());
assert_eq!(message.root_part().id(), root.root_part().id());
assert_eq!(message.has_attachments(), root.has_attachments());
assert_eq!(message.body_preview(20), root.body_preview(20));
assert_eq!(message.body_text(0), root.body_text(0));
assert_eq!(message.body_html(0), root.body_html(0));
assert_eq!(message.attachment_name(), root.attachment_name());
assert_eq!(message.content_type(), root.content_type());
assert_eq!(message.text_body().len(), root.text_body().len());
assert_eq!(message.html_body().len(), root.html_body().len());
assert_eq!(message.attachments().len(), root.attachments().len());
assert_eq!(message.other_parts().count(), root.other_parts().count());
assert_eq!(message.headers().len(), root.headers().len());
headers::getters!(message);
debug(message);
}
fn check_ref(message: &Message<'_>, nested: MessageRef<'_>) {
let source = nested.source_bytes();
match nested.source() {
Source::Raw => assert!(ptr::eq(source, message.raw())),
Source::Decoded(id) => {
let holder = message.part(id).expect("the source part exists");
assert_ne!(holder.encoding(), Encoding::None);
assert!(holder.is_message());
assert_eq!(
holder.decoded().as_ref(),
source,
"source is not the decoded body"
);
}
}
assert!(within(nested.raw(), source));
let root = nested.root_part();
assert_eq!(root.message().id(), nested.id());
assert!(root.parent().is_none());
match nested.container() {
None => assert_eq!(nested.id(), 0),
Some(container) => {
assert!(container.is_message());
assert!(container.id() < root.id());
assert_eq!(
container.nested().map(|inner| inner.id()),
Some(nested.id())
);
assert!(
matches!(container.kind(), PartKind::Message(inner) if inner.id() == nested.id())
);
}
}
assert_eq!(nested.parts().next().map(|part| part.id()), Some(root.id()));
let mut previous = None;
for part in nested.parts() {
assert_eq!(part.message().id(), nested.id());
assert!(previous < Some(part.id()));
previous = Some(part.id());
}
check_list(nested, nested.text_body(), MessagePart::in_text_body);
check_list(nested, nested.html_body(), MessagePart::in_html_body);
check_list(nested, nested.attachments(), MessagePart::is_attachment);
assert_eq!(
nested.has_attachments(),
nested.attachments().any(|part| {
!part
.content_disposition()
.is_some_and(|disposition| disposition.is_inline())
})
);
assert!(
nested
.other_parts()
.all(|part| part.role() == PartRole::Dropped)
);
check_bodies(nested);
for max_len in PREVIEW_LENS {
check_preview(nested, max_len);
}
assert_eq!(nested.headers().len(), root.headers().len());
let _ = nested.is_content_type("text", "plain");
nested.attachment_name().into_iter().for_each(valid);
[nested.content_type(), nested.content_disposition()]
.into_iter()
.flatten()
.for_each(content_type);
headers::getters!(nested);
debug(&nested);
}
fn check_list<'m>(
owner: MessageRef<'m>,
list: impl ExactSizeIterator<Item = MessagePart<'m>>,
member: fn(&MessagePart<'m>) -> bool,
) {
let len = list.len();
let mut count = 0;
for part in list {
assert_eq!(part.message().id(), owner.id());
assert!(member(&part));
count += 1;
}
assert_eq!(count, len);
assert_eq!(owner.parts().filter(member).count(), len);
}
fn as_text(part: MessagePart<'_>) -> Option<Cow<'_, str>> {
match part.kind() {
PartKind::Text => part.text(),
PartKind::Html => part.text().map(|html| Cow::Owned(html_to_text(&html))),
_ => None,
}
}
fn as_html(part: MessagePart<'_>) -> Option<Cow<'_, str>> {
match part.kind() {
PartKind::Html => part.text(),
PartKind::Text => part.text().map(|text| Cow::Owned(text_to_html(&text))),
_ => None,
}
}
fn check_bodies(owner: MessageRef<'_>) {
for (index, part) in owner.text_body().enumerate().take(CHECKED_BODIES) {
assert_eq!(owner.body_text(index), as_text(part));
}
for (index, part) in owner.html_body().enumerate().take(CHECKED_BODIES) {
assert_eq!(owner.body_html(index), as_html(part));
}
let texts = owner.text_body().filter_map(as_text);
assert!(
owner
.text_bodies()
.take(CHECKED_BODIES)
.eq(texts.take(CHECKED_BODIES))
);
let htmls = owner.html_body().filter_map(as_html);
assert!(
owner
.html_bodies()
.take(CHECKED_BODIES)
.eq(htmls.take(CHECKED_BODIES))
);
}
fn check_preview(owner: MessageRef<'_>, max_len: usize) {
let preview = owner.body_preview(max_len);
let expected = match (owner.text_body().next(), owner.html_body().next()) {
(Some(part), _) => match part.kind() {
PartKind::Text => part
.text()
.map(|text| preview_text(&text, max_len).into_owned()),
PartKind::Html => part.text().map(|html| preview_html(&html, max_len)),
_ => None,
},
(None, Some(part)) => match part.kind() {
PartKind::Html => part.text().map(|html| preview_html(&html, max_len)),
PartKind::Text => part
.text()
.map(|text| preview_html(&text_to_html(&text), max_len)),
_ => None,
},
(None, None) => None,
};
assert_eq!(preview.as_deref(), expected.as_deref(), "body_preview");
if let Some(preview) = preview {
valid(&preview);
assert!(preview.len() <= max_len);
assert!(!preview.contains('\r'));
}
}
fn check_part(part: MessagePart<'_>) {
let source = part.message().source_bytes();
let (header, body, end) = (
part.offset_header() as usize,
part.offset_body() as usize,
part.offset_end() as usize,
);
assert!(
header <= body && body <= end && end <= source.len(),
"part {} offsets {header}..{body}..{end} outside its source of {} bytes",
part.id(),
source.len()
);
assert_eq!(source.get(header..end), Some(part.raw()));
assert_eq!(source.get(header..body), Some(part.raw_headers()));
assert_eq!(source.get(body..end), Some(part.raw_body()));
check_family(part, header, end);
check_role(part);
let flags = part.flags();
assert_eq!(part.has_problems(), !flags.is_empty());
assert_eq!(flags.names().count(), flags.bits().count_ones() as usize);
debug(&flags);
if let Some(boundary) = part.boundary() {
valid(boundary);
assert!(part.is_multipart());
let declared = part.content_type().and_then(|ct| ct.attribute("boundary"));
assert_eq!(declared, Some(boundary));
}
assert_eq!(
part.delimiter(),
part.parent().and_then(|parent| parent.boundary())
);
check_headers(part.headers(), source, header, body);
[
part.attachment_name(),
part.content_id(),
part.content_description(),
part.content_location(),
part.content_transfer_encoding(),
]
.into_iter()
.flatten()
.for_each(valid);
[part.content_type(), part.content_disposition()]
.into_iter()
.flatten()
.for_each(content_type);
part.content_language().into_iter().for_each(text_list);
if let Some(ct) = part.content_type()
&& let Some(subtype) = ct.subtype()
{
assert!(part.is_content_type(ct.ctype(), subtype));
}
let _ = (part.is_inline(), part.encoding());
body::check(part);
debug(&part);
debug(&part.kind());
}
fn check_family(part: MessagePart<'_>, header: usize, end: usize) {
if let Some(parent) = part.parent() {
assert!(parent.is_multipart());
assert!(parent.id() < part.id());
assert_eq!(parent.message().id(), part.message().id());
assert!(
parent.offset_body() as usize <= header && end <= parent.offset_end() as usize,
"part {} {header}..{end} outside its parent {} body {}..{}",
part.id(),
parent.id(),
parent.offset_body(),
parent.offset_end()
);
}
let children = part.children();
let len = children.len();
let mut previous = part.id();
let mut count = 0;
for child in children {
assert!(child.id() > previous);
assert_eq!(child.parent().map(|parent| parent.id()), Some(part.id()));
previous = child.id();
count += 1;
}
assert_eq!(count, len);
assert_eq!(part.children().rev().count(), len);
if !part.is_multipart() {
assert_eq!(len, 0);
}
let kind = part.kind();
assert_eq!(
part.is_text(),
matches!(kind, PartKind::Text | PartKind::Html)
);
assert_eq!(part.is_multipart(), matches!(kind, PartKind::Multipart));
assert_eq!(part.is_message(), matches!(kind, PartKind::Message(_)));
assert_eq!(part.nested().is_some(), part.is_message());
if let PartKind::Message(nested) = kind {
assert_eq!(part.nested().map(|inner| inner.id()), Some(nested.id()));
assert_eq!(
nested.container().map(|container| container.id()),
Some(part.id())
);
let root = nested.root_part();
if ptr::eq(nested.source_bytes(), part.message().source_bytes()) {
assert!(
root.offset_header() >= part.offset_body()
&& root.offset_end() <= part.offset_end(),
"nested root {} {}..{} outside its container {} body {}..{}",
root.id(),
root.offset_header(),
root.offset_end(),
part.id(),
part.offset_body(),
part.offset_end()
);
} else {
assert_eq!(nested.source(), Source::Decoded(part.id()));
}
}
}
fn check_role(part: MessagePart<'_>) {
let (text, html, attachment) = (
part.in_text_body(),
part.in_html_body(),
part.is_attachment(),
);
match part.role() {
PartRole::Container => {
assert!(part.is_multipart());
assert!(!text && !html && !attachment);
}
PartRole::CopiedBody => assert!(text && html),
PartRole::TextBody => {
assert!(matches!(part.kind(), PartKind::Text));
assert!(text || html);
}
PartRole::HtmlBody => {
assert!(matches!(part.kind(), PartKind::Html));
assert!(text || html);
}
PartRole::MediaBody => {
assert!(!part.is_text() && !part.is_multipart());
assert!(text || html);
}
PartRole::Attachment => assert!(attachment && !text && !html),
PartRole::Dropped => assert!(!text && !html && !attachment),
}
debug(&part.role());
}
fn part_depth(part: MessagePart<'_>) -> usize {
let mut depth = 0;
let mut current = part;
loop {
depth += 1;
current = match current.parent() {
Some(parent) => parent,
None => match current.message().container() {
Some(container) => container,
None => return depth,
},
};
}
}
fn encoded_depth(nested: MessageRef<'_>) -> usize {
let mut depth = 0;
let mut current = nested.container();
while let Some(container) = current {
if container.encoding() != Encoding::None {
depth += 1;
}
current = container.message().container();
}
depth
}
pub fn check_limits(message: &Message<'_>, limits: Limits) {
assert!(message.parts().len() <= limits.parts, "part limit exceeded");
for part in message.parts() {
assert!(part_depth(part) <= limits.depth, "depth limit exceeded");
}
for nested in message.messages() {
assert!(
encoded_depth(nested) <= limits.encoded,
"encoded nesting limit exceeded"
);
}
}
+209
View File
@@ -0,0 +1,209 @@
use crate::{debug, display, valid};
use mail_parser::{
Address, AddressList, ContentType, DateTime, HeaderValue, Host, Mailbox, Received, TextList,
};
use std::cmp::Ordering;
const ZONES: [i64; 6] = [0, 3_600, -39_600, 50_400, i64::MIN, i64::MAX];
const DAYS_PER_WEEK: u8 = 7;
pub fn header_value(value: HeaderValue<'_>) {
assert_eq!(value.is_empty(), matches!(value, HeaderValue::Empty));
match value {
HeaderValue::Empty => assert_eq!(value.as_text(), None),
HeaderValue::Text(text) => {
valid(text);
assert_eq!(value.as_text(), Some(text));
}
HeaderValue::TextList(list) => {
text_list(list);
assert_eq!(value.as_text(), list.last());
assert_eq!(value.as_text_list(), Some(list));
}
HeaderValue::Address(list) => {
addresses(list);
assert_eq!(value.as_address(), Some(list));
}
HeaderValue::DateTime(date) => {
datetime(date);
assert_eq!(value.as_datetime(), Some(date));
}
HeaderValue::ContentType(ct) => {
content_type(ct);
assert_eq!(value.as_content_type(), Some(ct));
}
HeaderValue::Received(trace) => {
received(trace);
assert_eq!(value.as_received(), Some(trace));
}
}
debug(&value);
}
pub fn text_list(list: TextList<'_>) {
let len = list.len();
assert_eq!(list.is_empty(), len == 0);
assert_eq!(list.iter().len(), len);
assert_eq!(list.iter().rev().count(), len);
for (index, item) in list.iter().enumerate() {
valid(item);
assert_eq!(list.get(index), Some(item));
assert!(list.contains(item));
}
assert_eq!(list.get(len), None);
assert_eq!(list.first(), list.iter().next());
assert_eq!(list.last(), list.iter().next_back());
let copy = list;
assert!(copy == list);
debug(&list);
}
fn mailbox(mailbox: Mailbox<'_>, list: AddressList<'_>) {
[mailbox.name(), mailbox.address()]
.into_iter()
.flatten()
.for_each(valid);
if let Some(address) = mailbox.address() {
assert!(list.contains(address));
}
}
pub fn addresses(list: AddressList<'_>) {
let flattened = list.iter().flat_map(|address| {
let (single, members) = match address {
Address::Mailbox(mailbox) => (Some(mailbox), None),
Address::Group(group) => (None, Some(group.mailboxes())),
};
single.into_iter().chain(members.into_iter().flatten())
});
assert!(
flattened.eq(list.mailboxes()),
"iter() and mailboxes() differ"
);
let grouped = list.groups().flat_map(|(_, run)| run);
assert!(
grouped.eq(list.mailboxes()),
"groups() and mailboxes() differ"
);
for (name, run) in list.groups() {
name.into_iter().for_each(valid);
debug(&run);
}
let mut has_groups = false;
for address in list.iter() {
if let Address::Group(group) = address {
has_groups = true;
group.name().into_iter().for_each(valid);
let members = group.mailboxes();
assert_eq!(group.len(), members.len());
assert_eq!(group.is_empty(), members.len() == 0);
assert_eq!(members.rev().count(), group.len());
}
debug(&address);
}
assert_eq!(list.has_groups(), has_groups);
assert_eq!(list.is_empty(), list.iter().next().is_none());
assert_eq!(list.first(), list.mailboxes().next());
assert_eq!(list.last(), list.mailboxes().last());
for entry in list.mailboxes() {
mailbox(entry, list);
}
let copy = list;
assert!(copy == list);
debug(&list);
}
pub fn content_type(ct: ContentType<'_>) {
valid(ct.ctype());
ct.subtype().into_iter().for_each(valid);
let attributes = ct.attributes();
let len = attributes.len();
let mut count = 0;
for (name, value) in attributes {
valid(name);
valid(value);
assert!(ct.has_attribute(name));
count += 1;
}
assert_eq!(count, len);
assert_eq!(ct.attributes().rev().count(), len);
let _ = (ct.is_attachment(), ct.is_inline());
let copy = ct;
assert!(copy == ct);
debug(&ct);
}
fn host(host: Host<'_>) {
if let Host::Name(name) = host {
valid(name);
}
display(&host);
debug(&host);
}
pub fn received(trace: Received<'_>) {
[trace.from(), trace.by(), trace.helo()]
.into_iter()
.flatten()
.for_each(host);
[
trace.from_iprev(),
trace.for_(),
trace.tls_cipher(),
trace.id(),
trace.ident(),
trace.via(),
]
.into_iter()
.flatten()
.for_each(valid);
let _ = trace.from_ip();
if let Some(protocol) = trace.with() {
valid(protocol.as_str());
display(&protocol);
}
if let Some(version) = trace.tls_version() {
valid(version.as_str());
display(&version);
}
if let Some(greeting) = trace.helo_cmd() {
valid(greeting.as_str());
display(&greeting);
}
trace.date().into_iter().for_each(datetime);
let copy = trace;
assert!(copy == trace);
debug(&trace);
}
pub fn datetime(date: DateTime) {
assert!(date.day_of_week() < DAYS_PER_WEEK);
let _ = (date.julian_day(), date.to_timestamp_local());
assert_eq!(date.cmp(&date), Ordering::Equal);
valid(&date.to_rfc822());
valid(&date.to_rfc3339());
display(&date);
for zone in ZONES {
let shifted = date.to_timezone(zone);
assert!(shifted.day_of_week() < DAYS_PER_WEEK);
}
let _ = i64::from(date);
if date.is_valid() {
let timestamp = date.to_timestamp();
assert_eq!(
DateTime::from_timestamp(timestamp).to_timestamp(),
timestamp,
"from_timestamp does not invert to_timestamp for {date:?}"
);
assert_eq!(
DateTime::parse_rfc3339(&date.to_rfc3339()).map(|parsed| parsed.to_timestamp()),
Some(timestamp),
"RFC 3339 round trip of {date:?}"
);
assert_eq!(
DateTime::parse_rfc822(&date.to_rfc822()).map(|parsed| parsed.to_timestamp()),
Some(timestamp),
"RFC 822 round trip of {date:?}"
);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1048
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
[
{
"input": "<head><meta charset=Windows-1252></head><body>\u2014</body>",
"expected": "<head><meta charset=utf-8></head><body>\u2014</body>"
},
{
"input": "<head><meta charset=\"Windows-1252\"></head><body>\u2014</body>",
"expected": "<head><meta charset=\"utf-8\"></head><body>\u2014</body>"
},
{
"input": "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\"></head><body>\u2014</body>",
"expected": "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>\u2014</body>"
},
{
"input": "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=&quot;Windows-1252&quot;\"></head><body>\u2014</body>",
"expected": "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=&quot;utf-8&quot;\"></head><body>\u2014</body>"
},
{
"input": "<head><meta charset=\"utf-8\"></head><body>x</body>",
"expected": "<head><meta charset=\"utf-8\"></head><body>x</body>"
},
{
"input": "<body><meta charset=Windows-1252></body>",
"expected": "<body><meta charset=Windows-1252></body>"
},
{
"input": "plain text",
"expected": "plain text"
}
]
+38
View File
@@ -0,0 +1,38 @@
[
{
"input": "&lt;",
"expected": "<"
},
{
"input": "&#32;",
"expected": " "
},
{
"input": "&#x20;",
"expected": " "
},
{
"input": "&nbsp;",
"expected": " "
},
{
"input": "&CounterClockwiseContourIntegral;",
"expected": "∳"
},
{
"input": "&curvearrowright;",
"expected": "↷"
},
{
"input": "&rarr;",
"expected": "→"
},
{
"input": "&#xFFFFFFF;",
"expected": "�"
},
{
"input": "&hmmm",
"expected": "&hmmm"
}
]
+166
View File
@@ -0,0 +1,166 @@
[
{
"input": "<html>hello<br/>world<br/></html>",
"expected": "hello\nworld\n"
},
{
"input": "<html>using &lt;><br/></html>",
"expected": "using <>\n"
},
{
"input": "test <not br/>tag<br />",
"expected": "test tag\n"
},
{
"input": "<>< ><tag\n/>>hello world< br \n />",
"expected": ">hello world\n"
},
{
"input": "<head><title>ignore head</title><not head>xyz</not head></head><h1>&lt;body&gt;</h1>",
"expected": "<body>\n"
},
{
"input": "<p>what is &heartsuit;?</p><p>&#x000DF;&Abreve;&#914;&gamma; don&apos;t hurt me.</p>",
"expected": "what is ♥?\nßĂΒγ don't hurt me.\n"
},
{
"input": "<!--[if mso]><style type=\"text/css\">body, table, td, a, p, span, ul, li {font-family: Arial, sans-serif!important;}</style><![endif]-->this is <!-- <> < < < < ignore > -> here -->the actual<!--> text",
"expected": "this is the actual text"
},
{
"input": " < p > hello < / p > < p > world < / p > !!! < br > ",
"expected": "hello\nworld\n!!!\n"
},
{
"input": " <p>please unsubscribe <a href=#>here</a>.</p> ",
"expected": "please unsubscribe here.\n"
},
{
"input": "<style>body{color:red}</style><div>Hello</div>",
"expected": "Hello\n"
},
{
"input": "<style>body{color:red}</style><div>Hello</div><script>alert('x')</script><div>World</div>",
"expected": "Hello\nWorld\n"
},
{
"input": "<div>Hello</div><template><div>Hidden</div><style>.x{}</style></template><div>World</div>",
"expected": "Hello\nWorld\n"
},
{
"input": "<style type=\"text/css\">p { color: red; }</style><p>Hello world</p>",
"expected": "Hello world\n"
},
{
"input": "<script type=\"text/javascript\">var x = 1;</script><p>Hello world</p>",
"expected": "Hello world\n"
},
{
"input": "<STYLE TYPE=\"text/css\" media=\"screen\">.a{b:c}</STYLE>Hi",
"expected": "Hi"
},
{
"input": "<head lang=\"en\"><title>Title</title></head><body class=\"main\">Body</body>",
"expected": "Body"
},
{
"input": "<div>Hello</div><template id=\"row\"><div>Hidden</div></template><div>World</div>",
"expected": "Hello\nWorld\n"
},
{
"input": "line one<br class=\"x\">line two<br style=\"a\" />end",
"expected": "line one\nline two\nend"
},
{
"input": "<p class=\"intro\">first</p><p style=\"margin:0\">second</p>",
"expected": "first\nsecond\n"
},
{
"input": "<!--[if mso]><style type=\"text/css\">td{}</style><![endif]--><style type=\"text/css\">@media{.a{b:c}}</style><table role=\"presentation\"><tr><td style=\"padding:0\">Sale &amp; more</td></tr></table>",
"expected": "Sale & more\n"
},
{
"input": "<p>Before</p><!----><p>Hello world</p>",
"expected": "Before\nHello world\n"
},
{
"input": "a<!-- x --->b<!---->c<!-->d<!--->e<!-- y --!>f",
"expected": "abcdef"
},
{
"input": "a<!---!>x--><!--!>y--><!-- z- ->w -->b",
"expected": "ab"
},
{
"input": "before<!-- unterminated --",
"expected": "before"
},
{
"input": "<b>Hello</b> world",
"expected": "Hello world"
},
{
"input": "<a href=u>link</a> text",
"expected": "link text"
},
{
"input": "<p>Name: <b>John</b> Smith</p>",
"expected": "Name: John Smith\n"
},
{
"input": "<p>a</p>\n<p>b</p>",
"expected": "a\nb\n"
},
{
"input": "<img alt=\"a > b\"> after",
"expected": "after"
},
{
"input": "<a title='1>0'>t</a>",
"expected": "t"
},
{
"input": "<img alt=\"a < b\" src=x>after",
"expected": "after"
},
{
"input": "<a href = \"x>y\" class=c>t</a> u",
"expected": "t u"
},
{
"input": "a<img alt=\"x>y",
"expected": "a"
},
{
"input": "<div>One</div><div>Two</div>",
"expected": "One\nTwo\n"
},
{
"input": "<ul><li>One</li><li>Two</li></ul>",
"expected": "One\nTwo\n"
},
{
"input": "<table><tr><td>One</td><td>Two</td></tr><tr><td>Three</td></tr></table>",
"expected": "One Two\nThree\n"
},
{
"input": "<h1>Title</h1><p>Body</p>",
"expected": "Title\nBody\n"
},
{
"input": "Intro<DIV class=\"a\"><Div>nested</div>tail</DIV>end",
"expected": "Intro\nnested\ntail\nend"
},
{
"input": "<p>a</p><p></p><hr><p>b<br></p>",
"expected": "a\nb\n"
},
{
"input": "<table>\n <tr>\n <th>Item</th>\n <th>Price</th>\n </tr>\n</table>",
"expected": "Item Price\n"
},
{
"input": "Hello<template><div>a</div><br><td>b</td></template> <style>p{}</style>World<script>\"<br>\"</script>!",
"expected": "Hello World!"
}
]
+14
View File
@@ -0,0 +1,14 @@
[
{
"input": "hello\nworld\n",
"expected": "<html><body>hello<br/>world<br/></body></html>"
},
{
"input": "using <>\n",
"expected": "<html><body>using &lt;&gt;<br/></body></html>"
},
{
"input": "a & b\r\n",
"expected": "<html><body>a &amp; b<br/></body></html>"
}
]
+47
View File
@@ -0,0 +1,47 @@
[
{
"input": "<html>hello<br/>world<br/></html>",
"max_len": 25,
"expected": "<html>hello<br/>world..."
},
{
"input": "<html>using &lt;><br/></html>",
"max_len": 25,
"expected": "<html>using &lt;><br/>..."
},
{
"input": "test <not br/>tag<br />test <not br/>tag<br />",
"max_len": 25,
"expected": "test <not br/>tag..."
},
{
"input": "<>< ><tag\n/>>hello world< br \n />",
"max_len": 25,
"expected": "<>< ><tag\n/>>hello ..."
},
{
"input": "<head><title>ignore head</title><not head>xyz</not head></head><h1>&lt;body&gt;</h1>",
"max_len": 25,
"expected": "<head><title>ignore he..."
},
{
"input": "<p>what is &heartsuit;?</p><p>&#x000DF;&Abreve;&#914;&gamma; don&apos;t hurt me.</p>",
"max_len": 25,
"expected": "<p>what is &heartsuit;..."
},
{
"input": "<!-- <> < < < -->the actual<!--> text",
"max_len": 25,
"expected": "<!-- <> < < < -->the a..."
},
{
"input": " < p > hello < / p > < p > world < / p > !!! < br > ",
"max_len": 25,
"expected": " < p > hello ..."
},
{
"input": " <p>please unsubscribe <a href=#>here</a>.</p> ",
"max_len": 25,
"expected": " <p>please unsubscribe..."
}
]
+12
View File
@@ -0,0 +1,12 @@
[
{
"input": "J'interdis aux marchands de vanter trop leurs marchandises. Car ils se fontvite pédagogues et t'enseignent comme but ce qui n'est par essence qu'un moyen, et te trompant ainsi sur la route à suivre les voilà bientôt qui te dégradent, car si leur musique est vulgaire ils te fabriquent pour te la vendre une âme vulgaire.\n\u2014 Antoine de Saint-Exupéry, Citadelle (1948)",
"max_len": 110,
"expected": "J'interdis aux marchands de vanter trop leurs marchandises. Car ils se fontvite pédagogues et t'enseignent..."
},
{
"input": "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」子路曰:「為孔丘。」曰:「是魯孔丘與?」曰:「是也。」曰:「是知津矣。」問於桀溺,桀溺曰:「子為誰?」曰:「為仲由。」曰:「是魯孔丘之徒與?」對曰:「然。」曰:「滔滔者天下皆是也,而誰以易之?且而與其從辟人之士也,豈若從辟世之士哉?」耰而不輟。子路行以告。夫子憮然曰:「鳥獸不可與同群,吾非斯人之徒與而誰與?天下有道,丘不與易也。」子路從而後,遇丈人,以杖荷蓧。子路問曰:「子見夫子乎?」丈人曰:「四體不勤,五穀不分。孰為夫子?」植其杖而芸。子路拱而立。止子路宿,殺雞為黍而食之,見其二子焉。明日,子路行以告。子曰:「隱者也。」使子路反見之。至則行矣。子路曰:「不仕無義。長幼之節,不可廢也;君臣之義,如之何其廢之?欲潔其身,而亂大倫。君子之仕也,行其義也。道之不行,已知之矣。」",
"max_len": 110,
"expected": "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」子..."
}
]
+46
View File
@@ -0,0 +1,46 @@
Message-ID: <39235EAD.E48E2160@example.com>
Date: Wed, 17 May 2000 23:08:29 -0400
From: Doug Sauder <dwsauder@example.com>
MIME-Version: 1.0
To: Joe Blow <blow@example.com>
Subject: Inline image before the alternative
Content-Type: multipart/mixed;
boundary="------------C78F594988075E36AE03C243"
This is a multi-part message in MIME format.
--------------C78F594988075E36AE03C243
Content-Type: image/png;
name="greenball.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;
filename="greenball.png"
iVBORw0KGgo=
--------------C78F594988075E36AE03C243
Content-Type: multipart/alternative;
boundary="------------D74AE2393FB01D1B284AE257"
--------------D74AE2393FB01D1B284AE257
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Die Hasen und die Froesche
--------------D74AE2393FB01D1B284AE257
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit
<html><b>Die Hasen und die Fr&ouml;sche</b></html>
--------------D74AE2393FB01D1B284AE257--
--------------C78F594988075E36AE03C243
Content-Type: image/png;
name="blueball.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;
filename="blueball.png"
iVBORw0KGgo=
--------------C78F594988075E36AE03C243--
@@ -0,0 +1,23 @@
Content-Type: multipart/alternative;
boundary="_000_965A26A6D93540AD9522027B9387AAACXXX_"
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
=97
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/html; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<html>
<head>
<meta charset=3D"Windows-1252">
</head>
<body dir=3D"auto">
=97
</body>
</html>
--_000_965A26A6D93540AD9522027B9387AAACXXX_--
+23
View File
@@ -0,0 +1,23 @@
Content-Type: multipart/alternative;
boundary="_000_965A26A6D93540AD9522027B9387AAACXXX_"
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
=97
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/html; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<html>
<head>
<meta charset=3DWindows-1252>
</head>
<body dir=3D"auto">
=97
</body>
</html>
--_000_965A26A6D93540AD9522027B9387AAACXXX_--
@@ -0,0 +1,23 @@
Content-Type: multipart/alternative;
boundary="_000_965A26A6D93540AD9522027B9387AAACXXX_"
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
=97
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/html; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<html>
<head>
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3D&quot;Windows-1252&quot;">
</head>
<body dir=3D"auto">
=97
</body>
</html>
--_000_965A26A6D93540AD9522027B9387AAACXXX_--
+23
View File
@@ -0,0 +1,23 @@
Content-Type: multipart/alternative;
boundary="_000_965A26A6D93540AD9522027B9387AAACXXX_"
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
=97
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/html; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<html>
<head>
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DWindows-1252">
</head>
<body dir=3D"auto">
=97
</body>
</html>
--_000_965A26A6D93540AD9522027B9387AAACXXX_--
+24
View File
@@ -0,0 +1,24 @@
Content-Type: multipart/alternative;
boundary="_000_965A26A6D93540AD9522027B9387AAACXXX_"
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
=97
--_000_965A26A6D93540AD9522027B9387AAACXXX_
Content-Type: text/html; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
<html>
<head>
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DWindows-1=
252">
</head>
<body dir=3D"auto">
=97
</body>
</html>
--_000_965A26A6D93540AD9522027B9387AAACXXX_--
+41
View File
@@ -0,0 +1,41 @@
From: Boundary Tester <tester@example.com>
To: Recipient <recipient@example.com>
Subject: Boundaries of every part
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="outer-mixed"
This is the preamble.
--outer-mixed
Content-Type: multipart/alternative; boundary="inner-alternative"
--inner-alternative
Content-Type: text/plain; charset=us-ascii
Plain version.
--inner-alternative
Content-Type: text/html; charset=us-ascii
<p>HTML version.</p>
--inner-alternative--
Alternative epilogue.
--outer-mixed
Content-Type: message/rfc822
Content-Disposition: inline
From: Nested Sender <nested@example.com>
Subject: Nested message
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="nested-mixed"
--nested-mixed
Content-Type: text/plain; charset=us-ascii
Nested text.
--nested-mixed
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
AAECAw==
--nested-mixed--
--outer-mixed--
Outer epilogue.
+10
View File
@@ -0,0 +1,10 @@
Content-Type: multipart/mixed; boundary="BND"
--BND
Content-Type: text/plain
first part
--BND
Content-Type: text/plain
second part ends here--BND--
+9
View File
@@ -0,0 +1,9 @@
Content-Type: multipart/mixed; boundary="BND"
--BND
Content-Type: text/plain
first
--BNDX not a delimiter
last
--BND--
+8
View File
@@ -0,0 +1,8 @@
Content-Type: multipart/mixed; boundary="BND"
--BND
Content-Type: text/plain
visit --BND for details
SECRET
--BND--
+17
View File
@@ -0,0 +1,17 @@
From: Sender <sender@example.com>
To: Recipient <recipient@example.com>
Subject: Plain text with an inline image as its alternative
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alt"
--alt
Content-Type: text/plain; charset=us-ascii
The text version.
--alt
Content-Type: image/png
Content-Disposition: inline; filename="version.png"
Content-Transfer-Encoding: base64
iVBORw0KGgo=
--alt--
+57
View File
@@ -0,0 +1,57 @@
From: X <X@X.org>
To: Y <Y@Y.org>
Date: Mon, 13 Feb 2018 12:00:00 -0400
Subject: Example inline
Mime-Version: 1.0
Content-Type: multipart/related; boundary="_005_C4D89E21F64B_"
--_005_C4D89E21F64B_
Content-Type: multipart/alternative;
boundary="_000_C4D89E21F64B_"
--_000_C4D89E21F64B_
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
[cid:3302530593_302033]
[cid:3302530593_275216]
--_000_C4D89E21F64B_
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<IMG src=3D"cid:3302530593_302033" >
<IMG src=3D"cid:3302530593_275216" >
</BODY>
</HTML>
--_000_C4D89E21F64B_--
--_005_C4D89E21F64B_
Content-Type: image/jpeg
Content-Transfer-Encoding: plain
Content-Disposition: inline;
filename="image.jpg"
Content-Description: image.jpg
Content-ID: <3302530593_302033>
A
--_005_C4D89E21F64B_
Content-Type: image/jpeg
Content-Transfer-Encoding: plain
Content-Disposition: inline;
filename="image.jpg"
Content-Description: image.jpg
Content-ID: <3302530593_275216>
B
--_005_C4D89E21F64B_--
+11
View File
@@ -0,0 +1,11 @@
From: Art Vandelay <art@vandelay.com>
To: Colleagues <colleagues@vandelay.com>
Subject: HTML only alternative
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="festivus"
--festivus
Content-Type: text/html; charset="us-ascii"
<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?</p></html>
--festivus--
@@ -0,0 +1,6 @@
From: sender@example.com
To: one: a@b.c; two: d@e.f;
Subject: issue 98
Content-Type: text/plain
body
+6
View File
@@ -0,0 +1,6 @@
From: sender@example.com
To: first: a@b.c, d@e.f; <x@y.com>
Subject: issue 98
Content-Type: text/plain
body
+6
View File
@@ -0,0 +1,6 @@
From: sender@example.com
To: <x@y.com>, last: a@b.c;
Subject: issue 98
Content-Type: text/plain
body
+6
View File
@@ -0,0 +1,6 @@
From: sender@example.com
To: <x@y.com>, <x@y.com>
Subject: issue 98
Content-Type: text/plain
body
+6
View File
@@ -0,0 +1,6 @@
From: sender@example.com
To: <x@y.com>, group: (some text);, <x@y.com>
Subject: issue 98
Content-Type: text/plain
body
+207
View File
@@ -0,0 +1,207 @@
{
"messages": [
{
"id": 0,
"root": 0,
"container": null,
"source": "raw",
"text_body": [],
"html_body": [],
"attachments": [
0
],
"has_attachments": true
}
],
"parts": [
{
"id": 0,
"message": 0,
"parent": null,
"kind": "binary",
"encoding": "base64",
"flags": [],
"roles": [
"attachment"
],
"role": "attachment",
"offset_header": 0,
"offset_body": 578,
"offset_end": 2570,
"headers": [
{
"name": "From",
"value": {
"address": [
{
"mailbox": {
"name": "Doug Sauder",
"address": "doug@example.com"
}
}
]
},
"offset_field": 0,
"offset_start": 5,
"offset_end": 40
},
{
"name": "To",
"value": {
"address": [
{
"mailbox": {
"name": "Joe Blow",
"address": "jblow@example.com"
}
}
]
},
"offset_field": 40,
"offset_start": 43,
"offset_end": 76
},
{
"name": "Subject",
"value": {
"text": "Test message from Microsoft Outlook 00"
},
"offset_field": 76,
"offset_start": 84,
"offset_end": 125
},
{
"name": "Date",
"value": {
"date_time": {
"year": 2000,
"month": 5,
"day": 17,
"hour": 19,
"minute": 35,
"second": 5,
"tz_before_gmt": true,
"tz_hour": 4,
"tz_minute": 0
}
},
"offset_field": 125,
"offset_start": 130,
"offset_end": 164
},
{
"name": "Message-ID",
"value": {
"text_list": [
"NDBBIAKOPKHFGPLCODIGKEKECHAA.doug@example.com"
]
},
"offset_field": 164,
"offset_start": 175,
"offset_end": 225
},
{
"name": "MIME-Version",
"value": {
"text": "1.0"
},
"offset_field": 225,
"offset_start": 238,
"offset_end": 244
},
{
"name": "Content-Type",
"value": {
"content_type": {
"type": "image",
"subtype": "png",
"attributes": [
[
"name",
"redball.png"
]
]
}
},
"offset_field": 244,
"offset_start": 257,
"offset_end": 291
},
{
"name": "Content-Transfer-Encoding",
"value": {
"text": "base64"
},
"offset_field": 291,
"offset_start": 317,
"offset_end": 326
},
{
"name": "Content-Disposition",
"value": {
"content_type": {
"type": "attachment",
"subtype": null,
"attributes": [
[
"filename",
"redball.png"
]
]
}
},
"offset_field": 326,
"offset_start": 346,
"offset_end": 385
},
{
"name": "X-Priority",
"value": {
"text": "3 (Normal)"
},
"offset_field": 385,
"offset_start": 396,
"offset_end": 409
},
{
"name": "X-MSMail-Priority",
"value": {
"text": "Normal"
},
"offset_field": 409,
"offset_start": 427,
"offset_end": 436
},
{
"name": "X-Mailer",
"value": {
"text": "Microsoft Outlook IMO, Build 9.0.2416 (9.0.2910.0)"
},
"offset_field": 436,
"offset_start": 445,
"offset_end": 498
},
{
"name": "Importance",
"value": {
"text": "Normal"
},
"offset_field": 498,
"offset_start": 509,
"offset_end": 518
},
{
"name": "X-MimeOLE",
"value": {
"text": "Produced By Microsoft MimeOLE V5.00.2314.1300"
},
"offset_field": 518,
"offset_start": 528,
"offset_end": 576
}
],
"binary": "iVBORw0KGgoAAAANSUhEUgAAABsAAAAbCAMAAAC6CgRnAAADAFBMVEX///8AAAABAAALAAAVAAAaAAAXAAARAAAKAAADAAAcAAAyAABEAABNAABIAAA9AAAjAAAWAAAmAABhAAB7AACGAACHAAB9AAB0AABgAAA5AAAUAAAGAAAnAABLAABvAACQAAClAAC7AAC/AACrAAChAACMAABzAABbAAAuAAAIAABMAAB3AACZAAC0GRnKODjVPT3bKSndBQW4AACoAAB5AAAxAAAYAAAEAABFAACaAAC7JCTRYWHfhITmf3/mVlbqHx/SAAC5AACjAABdAABCAAAoAAAJAABnAAC6Dw/QVFTek5PlrKzpmZntZWXvJSXXAADBAACxAACcAABtAABTAAA2AAAbAAAFAABKAACBAADLICDdZ2fonJzrpqbtiorvUVHvFBTRAADDAAC2AAB4AABeAABAAAAiAABXAACSAADCAADaGxvoVVXseHjveHjvV1fvJibhAADOAAC3AACnAACVAABHAAArAAAPAACdAADFAADhBQXrKCjvPDzvNTXvGxvjAADQAADJAAC1AACXAACEAABsAABPAAASAAACAABiAADpAADvAgLnAADYAADLAAC6AACwAABwAAATAAAkAABYAADIAADTAADNAACzAACDAABuAAAeAAB+AADAAACkAACNAAB/AABpAABQAAAwAACRAACpAAC8AACqAACbAABlAABJAAAqAAAOAAA0AACsAACvAACtAACmAACJAAB6AABrAABaAAA+AAApAABqAACCAACfAACeAACWAACPAAB8AAAZAAAHAABVAACOAACKAAA4AAAQAAA/AAByAACAAABcAAA3AAAsAABmAABDAABWAAAgAAAzAAA8AAA6AAAfAAAMAAAdAAANAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8LtlFAAAAAXRSTlMAQObYZgAAABZ0RVh0U29mdHdhcmUAZ2lmMnBuZyAyLjAuMT1evmgAAAIISURBVHicY2CAg/8QwIABmJhZWFnZ2Dk4MaU5uLh5eHn5+LkFBDlQJf8zC/EIi4iKiUtI8koJScsgyf5nlpWTV1BUUlZRVVPX4NFk1UJIyghp6+jq6RsYGhmbKJgK85mZW8Dk/rNaSlhZ29ja2Ts4Ojkr6Li4urFDNf53N/Ow8vTy9vH18w8IDAoWDQkNC4+ASP5ni4wKio6JjYtPSExKTnFWSE1LF4A69n9GZlZ2Tm5efkFhUXFySWlZlEd5RSVY7j+TkGRVdU1tXX1DY1Ozcktpa1t7h2YnOAj+d7l1tyo79vT29SdNSJ44SbFVdHIo9xSIHNPUaWqTpifNSJrZnK00S0U1a/acUG5piNz/uXLzVJ2qm6dXz584S2WB1cJFi5cshZr539xVftnyFKUVTi2TVjqvyhJLXb1m7TqoHPt6F/HW0g0bN63crGqVtWXrtu07BJihcsw71+zanRW8Z89eq337RQ/Ip60xO3gIElX/LbikDm8T36KwbNmRo7O3zpHkPSZwHBqL//8flz1x2OOkyKJTi7aqbzutfUZI2gIuF8F2lr/D5dw2+fZdwpl8YVOlI+CJ4/9/joOyYed5QzMvhGqnm2V0WiClm///D0lfXHtJ6vLlK9w7rx7vQk5SQJbFtSms1y9evXid7QZacgOxmSxktNzdtSwwU+J/VICaCPFIYU3XAJhIOtjf5sfyAAAAJXRFWHRDb21tZW50AGNsaXAyZ2lmIHYuMC42IGJ5IFl2ZXMgUGlndWV0NnM7vAAAAABJRU5ErkJggg==",
"decode_problems": []
}
]
}

Some files were not shown because too many files have changed in this diff Show More