From a5a5d74ba0e0ffa0a129841e15780134bd93ffc7 Mon Sep 17 00:00:00 2001 From: Maurus Decimus <11444311+mdecimus@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:00:35 +0200 Subject: [PATCH] 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) --- .gitignore | 2 + CHANGELOG.md | 480 +- Cargo.toml | 40 +- README.md | 491 +- benches/kernels.rs | 197 + benches/resolve.rs | 113 + benches/support/corpus.rs | 647 ++ examples/custom_parser.rs | 134 +- examples/mailbox_iterate_maildir.rs | 50 +- examples/mailbox_parse_mbox.rs | 58 +- examples/message_parse.rs | 196 +- examples/message_write_attachments.rs | 59 +- flamegraph.sh | 4 - fuzz/Cargo.lock | 207 +- fuzz/Cargo.toml | 69 +- fuzz/fuzz_targets/charsets.rs | 8 + fuzz/fuzz_targets/fields.rs | 8 + fuzz/fuzz_targets/kernels.rs | 12 + fuzz/fuzz_targets/limits.rs | 25 + fuzz/fuzz_targets/mail_parser.rs | 76 - fuzz/fuzz_targets/mbox.rs | 8 + fuzz/fuzz_targets/parse.rs | 12 + fuzz/mime.dict | 194 + fuzz/src/charsets.rs | 237 + fuzz/src/fields.rs | 160 + fuzz/src/kernels.rs | 238 + fuzz/src/lib.rs | 41 + fuzz/src/mbox.rs | 109 + fuzz/src/walk/body.rs | 65 + fuzz/src/walk/headers.rs | 222 + fuzz/src/walk/mod.rs | 493 ++ fuzz/src/walk/values.rs | 209 + resources/address.json | 1768 +++-- resources/content_type.json | 228 + resources/date.json | 556 ++ resources/eml/issues/107-image-first.eml | 46 + resources/eml/issues/109-charset-quoted.eml | 23 + resources/eml/issues/109-charset.eml | 23 + resources/eml/issues/109-http-equiv-quot.eml | 23 + resources/eml/issues/109-http-equiv.eml | 23 + resources/eml/issues/109.eml | 24 + resources/eml/issues/127.eml | 41 + resources/eml/issues/156-fallback.eml | 10 + resources/eml/issues/156-suffix.eml | 9 + resources/eml/issues/156.eml | 8 + resources/eml/issues/67-alternative.eml | 17 + resources/eml/issues/70.eml | 57 + resources/eml/issues/73.eml | 11 + resources/eml/issues/98-adjacent-groups.eml | 6 + resources/eml/issues/98-group-first.eml | 6 + resources/eml/issues/98-group-last.eml | 6 + resources/eml/issues/98-list.eml | 6 + resources/eml/issues/98-mixed.eml | 6 + resources/eml/legacy/000.crlf.json | 1599 +---- resources/eml/legacy/000.json | 1599 +---- resources/eml/legacy/001.crlf.json | 140 +- resources/eml/legacy/001.json | 140 +- resources/eml/legacy/002.crlf.json | 124 +- resources/eml/legacy/002.json | 124 +- resources/eml/legacy/003.crlf.json | 208 +- resources/eml/legacy/003.json | 208 +- resources/eml/legacy/004.crlf.json | 120 +- resources/eml/legacy/004.json | 120 +- resources/eml/legacy/005.crlf.json | 134 +- resources/eml/legacy/005.json | 134 +- resources/eml/legacy/006.crlf.json | 3028 +------- resources/eml/legacy/006.json | 3028 +------- resources/eml/legacy/007.crlf.json | 134 +- resources/eml/legacy/007.json | 134 +- resources/eml/legacy/008.crlf.json | 4442 +----------- resources/eml/legacy/008.json | 4442 +----------- resources/eml/legacy/009.crlf.json | 136 +- resources/eml/legacy/009.json | 136 +- resources/eml/legacy/010.crlf.json | 124 +- resources/eml/legacy/010.json | 124 +- resources/eml/legacy/011.crlf.json | 118 +- resources/eml/legacy/011.json | 118 +- resources/eml/legacy/012.crlf.json | 134 +- resources/eml/legacy/012.json | 134 +- resources/eml/legacy/013.crlf.json | 134 +- resources/eml/legacy/013.json | 134 +- resources/eml/legacy/014.crlf.json | 218 +- resources/eml/legacy/014.json | 218 +- resources/eml/legacy/015.crlf.json | 5967 +--------------- resources/eml/legacy/015.json | 5967 +--------------- resources/eml/legacy/016.crlf.json | 3339 +-------- resources/eml/legacy/016.json | 3289 +-------- resources/eml/legacy/017.crlf.json | 4033 +---------- resources/eml/legacy/017.json | 3966 +---------- resources/eml/legacy/018.crlf.json | 3177 +-------- resources/eml/legacy/018.json | 3177 +-------- resources/eml/legacy/019.crlf.json | 3138 +-------- resources/eml/legacy/019.json | 3138 +-------- resources/eml/legacy/020.crlf.json | 134 +- resources/eml/legacy/020.json | 134 +- resources/eml/legacy/021.crlf.json | 4558 +----------- resources/eml/legacy/021.json | 4558 +----------- resources/eml/legacy/022.crlf.json | 134 +- resources/eml/legacy/022.json | 134 +- resources/eml/legacy/023.crlf.json | 1669 +---- resources/eml/legacy/023.json | 1669 +---- resources/eml/legacy/024.crlf.json | 3093 +-------- resources/eml/legacy/024.json | 3093 +-------- resources/eml/legacy/025.crlf.json | 5883 +--------------- resources/eml/legacy/025.json | 5883 +--------------- resources/eml/legacy/026.crlf.json | 300 +- resources/eml/legacy/026.json | 300 +- resources/eml/legacy/027.crlf.json | 134 +- resources/eml/legacy/027.json | 134 +- resources/eml/legacy/028.crlf.json | 3147 +-------- resources/eml/legacy/028.json | 3147 +-------- resources/eml/legacy/029.crlf.json | 124 +- resources/eml/legacy/029.json | 124 +- resources/eml/legacy/030.crlf.json | 2991 +------- resources/eml/legacy/030.json | 2991 +------- resources/eml/legacy/031.crlf.json | 3069 +------- resources/eml/legacy/031.json | 3069 +------- resources/eml/legacy/032.crlf.json | 3003 +------- resources/eml/legacy/032.json | 3003 +------- resources/eml/legacy/033.crlf.json | 126 +- resources/eml/legacy/033.json | 126 +- resources/eml/legacy/034.crlf.json | 118 +- resources/eml/legacy/034.json | 118 +- resources/eml/legacy/035.crlf.json | 6079 +--------------- resources/eml/legacy/035.json | 6079 +--------------- resources/eml/legacy/036.crlf.json | 106 +- resources/eml/legacy/036.json | 106 +- resources/eml/legacy/037.crlf.json | 1553 +---- resources/eml/legacy/037.json | 1553 +---- resources/eml/legacy/038.crlf.json | 118 +- resources/eml/legacy/038.json | 118 +- resources/eml/legacy/039.crlf.json | 5867 +--------------- resources/eml/legacy/039.json | 5867 +--------------- resources/eml/legacy/040.crlf.json | 118 +- resources/eml/legacy/040.json | 118 +- resources/eml/legacy/041.crlf.json | 1671 +---- resources/eml/legacy/041.json | 1671 +---- resources/eml/legacy/042.crlf.json | 232 +- resources/eml/legacy/042.json | 232 +- resources/eml/legacy/043.crlf.json | 202 +- resources/eml/legacy/043.json | 202 +- resources/eml/legacy/044.crlf.json | 4440 +----------- resources/eml/legacy/044.json | 4440 +----------- resources/eml/legacy/045.crlf.json | 231 +- resources/eml/legacy/045.json | 231 +- resources/eml/legacy/046.crlf.json | 118 +- resources/eml/legacy/046.json | 118 +- resources/eml/legacy/047.crlf.json | 232 +- resources/eml/legacy/047.json | 232 +- resources/eml/legacy/048.crlf.json | 6173 +---------------- resources/eml/legacy/048.json | 6075 +--------------- resources/eml/legacy/049.crlf.json | 110 +- resources/eml/legacy/049.json | 110 +- resources/eml/legacy/050.crlf.json | 3093 +-------- resources/eml/legacy/050.json | 3093 +-------- resources/eml/legacy/051.crlf.json | 5883 +--------------- resources/eml/legacy/051.json | 5883 +--------------- resources/eml/legacy/052.crlf.json | 112 +- resources/eml/legacy/052.json | 112 +- resources/eml/legacy/053.crlf.json | 134 +- resources/eml/legacy/053.json | 134 +- resources/eml/malformed/000.crlf.json | 191 +- resources/eml/malformed/000.json | 191 +- resources/eml/malformed/001.crlf.json | 155 +- resources/eml/malformed/001.json | 155 +- resources/eml/malformed/002.crlf.json | 55 +- resources/eml/malformed/002.json | 55 +- resources/eml/malformed/003.crlf.json | 140 +- resources/eml/malformed/003.json | 140 +- resources/eml/malformed/004.crlf.json | 142 +- resources/eml/malformed/004.json | 142 +- resources/eml/malformed/005.crlf.json | 136 +- resources/eml/malformed/005.json | 136 +- resources/eml/malformed/006.crlf.json | 140 +- resources/eml/malformed/006.json | 140 +- resources/eml/malformed/007.crlf.json | 128 +- resources/eml/malformed/007.json | 128 +- resources/eml/malformed/008.crlf.json | 183 +- resources/eml/malformed/008.json | 183 +- resources/eml/malformed/009.crlf.json | 219 +- resources/eml/malformed/009.json | 219 +- resources/eml/malformed/010.crlf.json | 200 +- resources/eml/malformed/010.json | 200 +- resources/eml/malformed/011.crlf.json | 219 +- resources/eml/malformed/011.json | 219 +- resources/eml/malformed/012.crlf.json | 413 +- resources/eml/malformed/012.json | 413 +- resources/eml/malformed/013.crlf.json | 361 +- resources/eml/malformed/013.json | 361 +- resources/eml/malformed/014.crlf.json | 97 +- resources/eml/malformed/014.json | 97 +- resources/eml/malformed/015.crlf.json | 217 +- resources/eml/malformed/015.json | 216 +- resources/eml/malformed/016.crlf.json | 280 +- resources/eml/malformed/016.json | 280 +- resources/eml/malformed/017.crlf.json | 152 +- resources/eml/malformed/017.json | 152 +- resources/eml/malformed/018.crlf.json | 70 +- resources/eml/malformed/018.json | 70 +- resources/eml/malformed/019.crlf.json | 516 +- resources/eml/malformed/019.json | 516 +- resources/eml/malformed/020.crlf.json | 289 +- resources/eml/malformed/020.json | 289 +- resources/eml/malformed/021.crlf.json | 289 +- resources/eml/malformed/021.json | 289 +- resources/eml/malformed/022.crlf.json | 167 +- resources/eml/malformed/022.json | 167 +- resources/eml/malformed/023.crlf.json | 77 + resources/eml/malformed/023.eml | 10 + resources/eml/malformed/023.json | 77 + resources/eml/malformed/COPYING | 3 + resources/eml/regressions/README.md | 69 + ...ternative-attachment-disposition.crlf.json | 137 + .../alternative-attachment-disposition.eml | 12 + .../alternative-attachment-disposition.json | 137 + .../alternative-dropped-footer.crlf.json | 225 + .../alternative-dropped-footer.eml | 23 + .../alternative-dropped-footer.json | 225 + .../alternative-named-html.crlf.json | 129 + .../regressions/alternative-named-html.eml | 11 + .../regressions/alternative-named-html.json | 129 + .../alternative-nested-dropped.crlf.json | 228 + .../alternative-nested-dropped.eml | 23 + .../alternative-nested-dropped.json | 228 + .../alternative-related-image.crlf.json | 193 + .../regressions/alternative-related-image.eml | 19 + .../alternative-related-image.json | 193 + .../regressions/boundary-of-dashes.crlf.json | 52 + .../eml/regressions/boundary-of-dashes.eml | 4 + .../eml/regressions/boundary-of-dashes.json | 52 + .../close-delimiter-first.crlf.json | 52 + .../eml/regressions/close-delimiter-first.eml | 4 + .../regressions/close-delimiter-first.json | 52 + .../close-delimiter-mid-line.crlf.json | 52 + .../regressions/close-delimiter-mid-line.eml | 5 + .../regressions/close-delimiter-mid-line.json | 52 + .../date-without-final-newline.crlf.json | 70 + .../date-without-final-newline.eml | 2 + .../date-without-final-newline.json | 70 + .../eml/regressions/date-zone-est.crlf.json | 68 + resources/eml/regressions/date-zone-est.eml | 4 + resources/eml/regressions/date-zone-est.json | 68 + .../regressions/date-zone-military.crlf.json | 68 + .../eml/regressions/date-zone-military.eml | 4 + .../eml/regressions/date-zone-military.json | 68 + .../eml/regressions/date-zone-ut.crlf.json | 59 + resources/eml/regressions/date-zone-ut.eml | 3 + resources/eml/regressions/date-zone-ut.json | 59 + .../eml/regressions/date-zone-z.crlf.json | 59 + resources/eml/regressions/date-zone-z.eml | 3 + resources/eml/regressions/date-zone-z.json | 59 + .../doubly-encoded-message.crlf.json | 148 + .../regressions/doubly-encoded-message.eml | 4 + .../regressions/doubly-encoded-message.json | 148 + .../empty-nested-message-base64.crlf.json | 61 + .../empty-nested-message-base64.eml | 4 + .../empty-nested-message-base64.json | 61 + .../empty-nested-message.crlf.json | 52 + .../eml/regressions/empty-nested-message.eml | 2 + .../eml/regressions/empty-nested-message.json | 52 + .../empty-part-then-cut-part.crlf.json | 111 + .../regressions/empty-part-then-cut-part.eml | 6 + .../regressions/empty-part-then-cut-part.json | 111 + .../empty-structured-fields.crlf.json | 70 + .../regressions/empty-structured-fields.eml | 6 + .../regressions/empty-structured-fields.json | 70 + .../empty-subject-blanks.crlf.json | 65 + .../eml/regressions/empty-subject-blanks.eml | 4 + .../eml/regressions/empty-subject-blanks.json | 65 + .../empty-subject-folded.crlf.json | 65 + .../eml/regressions/empty-subject-folded.eml | 5 + .../eml/regressions/empty-subject-folded.json | 65 + .../eml/regressions/empty-subject.crlf.json | 65 + resources/eml/regressions/empty-subject.eml | 4 + resources/eml/regressions/empty-subject.json | 65 + .../fallback-delimiter-after-text.crlf.json | 91 + .../fallback-delimiter-after-text.eml | 8 + .../fallback-delimiter-after-text.json | 91 + .../garbage-line-before-fold.crlf.json | 49 + .../regressions/garbage-line-before-fold.eml | 4 + .../regressions/garbage-line-before-fold.json | 49 + .../header-name-blanks-before-colon.crlf.json | 72 + .../header-name-blanks-before-colon.eml | 4 + .../header-name-blanks-before-colon.json | 72 + .../header-name-colons-and-blanks.crlf.json | 65 + .../header-name-colons-and-blanks.eml | 4 + .../header-name-colons-and-blanks.json | 65 + .../header-name-form-feed.crlf.json | 65 + .../eml/regressions/header-name-form-feed.eml | 4 + .../regressions/header-name-form-feed.json | 65 + .../header-name-leading-colon.crlf.json | 65 + .../regressions/header-name-leading-colon.eml | 4 + .../header-name-leading-colon.json | 65 + .../eml/regressions/header-name-nul.crlf.json | 65 + resources/eml/regressions/header-name-nul.eml | Bin 0 -> 41 bytes .../eml/regressions/header-name-nul.json | 65 + .../header-name-smuggled-subject.crlf.json | 58 + .../header-name-smuggled-subject.eml | 4 + .../header-name-smuggled-subject.json | 58 + .../regressions/header-name-space.crlf.json | 65 + .../eml/regressions/header-name-space.eml | 4 + .../eml/regressions/header-name-space.json | 65 + .../inline-text-with-filename.crlf.json | 143 + .../regressions/inline-text-with-filename.eml | 12 + .../inline-text-with-filename.json | 143 + ...r-headers-cut-by-outer-delimiter.crlf.json | 126 + .../inner-headers-cut-by-outer-delimiter.eml | 8 + .../inner-headers-cut-by-outer-delimiter.json | 126 + .../eml/regressions/mixed-calendar.crlf.json | 124 + resources/eml/regressions/mixed-calendar.eml | 11 + resources/eml/regressions/mixed-calendar.json | 124 + .../regressions/mixed-disposition.crlf.json | 264 + .../eml/regressions/mixed-disposition.eml | 23 + .../eml/regressions/mixed-disposition.json | 264 + .../mixed-image-attachment.crlf.json | 142 + .../regressions/mixed-image-attachment.eml | 12 + .../regressions/mixed-image-attachment.json | 142 + .../regressions/mixed-image-inline.crlf.json | 139 + .../eml/regressions/mixed-image-inline.eml | 12 + .../eml/regressions/mixed-image-inline.json | 139 + .../eml/regressions/mixed-image.crlf.json | 125 + resources/eml/regressions/mixed-image.eml | 11 + resources/eml/regressions/mixed-image.json | 125 + .../mixed-message-inline.crlf.json | 180 + .../eml/regressions/mixed-message-inline.eml | 14 + .../eml/regressions/mixed-message-inline.json | 180 + .../eml/regressions/mixed-message.crlf.json | 166 + resources/eml/regressions/mixed-message.eml | 13 + resources/eml/regressions/mixed-message.json | 166 + .../regressions/mixed-pdf-inline.crlf.json | 138 + .../eml/regressions/mixed-pdf-inline.eml | 12 + .../eml/regressions/mixed-pdf-inline.json | 138 + resources/eml/regressions/mixed-pdf.crlf.json | 124 + resources/eml/regressions/mixed-pdf.eml | 11 + resources/eml/regressions/mixed-pdf.json | 124 + .../mixed-text-image-html.crlf.json | 161 + .../eml/regressions/mixed-text-image-html.eml | 15 + .../regressions/mixed-text-image-html.json | 161 + .../nested-headers-cut-by-delimiter.crlf.json | 130 + .../nested-headers-cut-by-delimiter.eml | 7 + .../nested-headers-cut-by-delimiter.json | 130 + .../no-delimiter-close-mid-line.crlf.json | 53 + .../no-delimiter-close-mid-line.eml | 4 + .../no-delimiter-close-mid-line.json | 53 + .../eml/regressions/readme-example.crlf.json | 401 ++ resources/eml/regressions/readme-example.eml | 39 + resources/eml/regressions/readme-example.json | 401 ++ ...related-cid-image-no-disposition.crlf.json | 150 + .../related-cid-image-no-disposition.eml | 13 + .../related-cid-image-no-disposition.json | 150 + .../related-cid-inline-image.crlf.json | 249 + .../regressions/related-cid-inline-image.eml | 23 + .../regressions/related-cid-inline-image.json | 249 + .../regressions/related-disposition.crlf.json | 241 + .../eml/regressions/related-disposition.eml | 23 + .../eml/regressions/related-disposition.json | 241 + .../root-attachment-disposition.crlf.json | 65 + .../root-attachment-disposition.eml | 2 + .../root-attachment-disposition.json | 65 + .../eml/regressions/single-text.crlf.json | 49 + resources/eml/regressions/single-text.eml | 3 + resources/eml/regressions/single-text.json | 49 + .../regressions/unopened-multiparts.crlf.json | 163 + .../eml/regressions/unopened-multiparts.eml | 15 + .../eml/regressions/unopened-multiparts.json | 163 + .../regressions/unstructured-fields.crlf.json | 67 + .../eml/regressions/unstructured-fields.eml | 6 + .../eml/regressions/unstructured-fields.json | 67 + .../unterminated-alternative.crlf.json | 93 + .../regressions/unterminated-alternative.eml | 6 + .../regressions/unterminated-alternative.json | 93 + .../regressions/utf16-dangling-byte.crlf.json | 139 + .../eml/regressions/utf16-dangling-byte.eml | Bin 0 -> 156 bytes .../eml/regressions/utf16-dangling-byte.json | 139 + .../regressions/utf7-terminators.crlf.json | 299 + .../eml/regressions/utf7-terminators.eml | 27 + .../eml/regressions/utf7-terminators.json | 299 + resources/eml/rfc/000.crlf.json | 551 +- resources/eml/rfc/000.json | 551 +- resources/eml/rfc/001.crlf.json | 574 +- resources/eml/rfc/001.json | 566 +- resources/eml/rfc/002.crlf.json | 1102 ++- resources/eml/rfc/002.json | 1102 ++- resources/eml/rfc/003.crlf.json | 264 +- resources/eml/rfc/003.json | 263 +- resources/eml/rfc/004.crlf.json | 488 +- resources/eml/rfc/004.json | 488 +- resources/eml/rfc/005.crlf.json | 164 +- resources/eml/rfc/005.json | 164 +- resources/eml/rfc/006.crlf.json | 198 +- resources/eml/rfc/006.json | 198 +- resources/eml/rfc/007.crlf.json | 743 +- resources/eml/rfc/007.json | 743 +- resources/eml/rfc/008.crlf.json | 603 +- resources/eml/rfc/008.json | 603 +- resources/eml/rfc/009.crlf.json | 351 +- resources/eml/rfc/009.json | 351 +- resources/eml/thirdparty/000.crlf.json | 146 +- resources/eml/thirdparty/000.json | 146 +- resources/eml/thirdparty/001.crlf.json | 185 +- resources/eml/thirdparty/001.json | 185 +- resources/eml/thirdparty/002.crlf.json | 208 +- resources/eml/thirdparty/002.json | 208 +- resources/eml/thirdparty/003.crlf.json | 305 +- resources/eml/thirdparty/003.json | 305 +- resources/eml/thirdparty/004.crlf.json | 368 +- resources/eml/thirdparty/004.json | 368 +- resources/eml/thirdparty/005.crlf.json | 309 +- resources/eml/thirdparty/005.json | 307 +- resources/eml/thirdparty/006.crlf.json | 316 +- resources/eml/thirdparty/006.json | 316 +- resources/eml/thirdparty/007.crlf.json | 658 +- resources/eml/thirdparty/007.json | 658 +- resources/eml/thirdparty/008.crlf.json | 665 +- resources/eml/thirdparty/008.json | 665 +- resources/eml/thirdparty/009.crlf.json | 415 +- resources/eml/thirdparty/009.json | 409 +- resources/eml/thirdparty/010.crlf.json | 121 +- resources/eml/thirdparty/010.json | 121 +- resources/eml/thirdparty/011.crlf.json | 3600 +--------- resources/eml/thirdparty/011.json | 3600 +--------- resources/eml/thirdparty/012.crlf.json | 438 +- resources/eml/thirdparty/012.json | 438 +- resources/eml/thirdparty/013.crlf.json | 360 +- resources/eml/thirdparty/013.json | 360 +- resources/eml/thirdparty/014.crlf.json | 401 +- resources/eml/thirdparty/014.json | 401 +- resources/eml/thirdparty/015.crlf.json | 1718 +++-- resources/eml/thirdparty/015.json | 1718 +++-- resources/eml/thirdparty/016.crlf.json | 475 +- resources/eml/thirdparty/016.json | 475 +- resources/eml/thirdparty/017.crlf.json | 567 +- resources/eml/thirdparty/017.json | 567 +- resources/eml/thirdparty/018.crlf.json | 737 +- resources/eml/thirdparty/018.json | 737 +- resources/eml/thirdparty/019.crlf.json | 829 +-- resources/eml/thirdparty/019.json | 829 +-- resources/id.json | 126 + resources/list.json | 192 + resources/received.json | 186 +- resources/sieve/alternative.eml | 77 + resources/sieve/headers.eml | 83 + resources/sieve/html.eml | 187 + resources/sieve/mixed-attachment.eml | 53 + resources/sieve/nested.eml | 100 + resources/sieve/plain.eml | 37 + resources/unstructured.json | 104 +- scripts/corpora.sha256 | 334 + scripts/fetch-corpora.sh | 173 + src/core/address.rs | 148 - src/core/body.rs | 55 - src/core/builder.rs | 209 - src/core/header.rs | 943 --- src/core/message.rs | 507 -- src/core/mod.rs | 13 - src/core/rkyv.rs | 337 - src/datetime.rs | 324 + src/decoders/base64.rs | 588 -- src/decoders/charsets/ascii.rs | 46 + src/decoders/charsets/label.rs | 632 ++ src/decoders/charsets/map.rs | 336 - src/decoders/charsets/mod.rs | 813 ++- src/decoders/charsets/multi_byte.rs | 248 +- src/decoders/charsets/single_byte.rs | 1147 +-- src/decoders/charsets/tables.rs | 504 ++ src/decoders/charsets/utf.rs | 165 - src/decoders/charsets/utf16.rs | 140 + src/decoders/charsets/utf7.rs | 209 + src/decoders/charsets/utf8.rs | 94 + src/decoders/encoded_word.rs | 172 - src/decoders/hex.rs | 96 - src/decoders/{html.rs => html/entities.rs} | 346 +- src/decoders/html/meta.rs | 135 + src/decoders/html/mod.rs | 266 + src/decoders/html/text.rs | 316 + src/decoders/mod.rs | 312 +- src/decoders/prefix.rs | 117 + src/decoders/preview.rs | 308 + src/decoders/quoted_printable.rs | 451 -- src/fields/address.rs | 969 +++ src/fields/content_type.rs | 1079 +++ src/fields/date.rs | 762 ++ src/fields/id.rs | 165 + src/fields/list.rs | 288 + src/fields/mod.rs | 436 ++ src/fields/raw.rs | 27 + src/fields/received.rs | 1228 ++++ src/fields/tests.rs | 178 + src/{parsers => }/fields/thread.rs | 135 +- src/fields/unstructured.rs | 324 + src/header_name.rs | 930 +++ src/lib.rs | 773 +-- src/mailbox/maildir.rs | 19 +- src/mailbox/mbox.rs | 453 +- src/mailbox/mod.rs | 8 + src/parser/builder.rs | 1176 ++++ src/parser/classify.rs | 254 + src/parser/delimiter.rs | 156 + src/parser/header_block.rs | 424 ++ src/parser/mod.rs | 310 + src/parser/tests.rs | 878 +++ src/parsers/fields/address.rs | 501 -- src/parsers/fields/content_type.rs | 547 -- src/parsers/fields/date.rs | 569 -- src/parsers/fields/id.rs | 92 - src/parsers/fields/list.rs | 132 - src/parsers/fields/mod.rs | 72 - src/parsers/fields/raw.rs | 121 - src/parsers/fields/received.rs | 858 --- src/parsers/fields/unstructured.rs | 108 - src/parsers/header.rs | 215 - src/parsers/message.rs | 678 -- src/parsers/mime.rs | 167 - src/parsers/mod.rs | 152 - src/parsers/preview.rs | 181 - src/scan/lib_memchr.rs | 21 + src/scan/mod.rs | 204 + src/scan/neon.rs | 144 + src/scan/scalar.rs | 23 + src/scan/set.rs | 177 + src/scan/simd.rs | 335 + src/scan/swar.rs | 96 + src/scan/tests.rs | 317 + src/scan/x86.rs | 343 + src/store/mod.rs | 660 ++ src/store/str.rs | 200 + src/store/table.rs | 177 + src/view/address.rs | 248 + src/view/content_type.rs | 120 + src/view/headers.rs | 766 ++ src/view/message.rs | 753 ++ src/view/mod.rs | 108 + src/view/part.rs | 655 ++ src/view/received.rs | 332 + src/view/serialize.rs | 295 + tests/api.rs | 357 + tests/classification.rs | 139 + tests/integration_test.rs | 265 +- tests/issue_109.rs | 121 + tests/issues.rs | 475 ++ tests/review_fields.rs | 240 + tests/review_structure.rs | 417 ++ tests/structure.rs | 203 + tests/support/mod.rs | 85 + tests/text_prefix.rs | 252 + 545 files changed, 80143 insertions(+), 212803 deletions(-) create mode 100644 benches/kernels.rs create mode 100644 benches/resolve.rs create mode 100644 benches/support/corpus.rs delete mode 100755 flamegraph.sh create mode 100644 fuzz/fuzz_targets/charsets.rs create mode 100644 fuzz/fuzz_targets/fields.rs create mode 100644 fuzz/fuzz_targets/kernels.rs create mode 100644 fuzz/fuzz_targets/limits.rs delete mode 100644 fuzz/fuzz_targets/mail_parser.rs create mode 100644 fuzz/fuzz_targets/mbox.rs create mode 100644 fuzz/fuzz_targets/parse.rs create mode 100644 fuzz/mime.dict create mode 100644 fuzz/src/charsets.rs create mode 100644 fuzz/src/fields.rs create mode 100644 fuzz/src/kernels.rs create mode 100644 fuzz/src/lib.rs create mode 100644 fuzz/src/mbox.rs create mode 100644 fuzz/src/walk/body.rs create mode 100644 fuzz/src/walk/headers.rs create mode 100644 fuzz/src/walk/mod.rs create mode 100644 fuzz/src/walk/values.rs create mode 100644 resources/eml/issues/107-image-first.eml create mode 100644 resources/eml/issues/109-charset-quoted.eml create mode 100644 resources/eml/issues/109-charset.eml create mode 100644 resources/eml/issues/109-http-equiv-quot.eml create mode 100644 resources/eml/issues/109-http-equiv.eml create mode 100644 resources/eml/issues/109.eml create mode 100644 resources/eml/issues/127.eml create mode 100644 resources/eml/issues/156-fallback.eml create mode 100644 resources/eml/issues/156-suffix.eml create mode 100644 resources/eml/issues/156.eml create mode 100644 resources/eml/issues/67-alternative.eml create mode 100644 resources/eml/issues/70.eml create mode 100644 resources/eml/issues/73.eml create mode 100644 resources/eml/issues/98-adjacent-groups.eml create mode 100644 resources/eml/issues/98-group-first.eml create mode 100644 resources/eml/issues/98-group-last.eml create mode 100644 resources/eml/issues/98-list.eml create mode 100644 resources/eml/issues/98-mixed.eml create mode 100644 resources/eml/malformed/023.crlf.json create mode 100644 resources/eml/malformed/023.eml create mode 100644 resources/eml/malformed/023.json create mode 100644 resources/eml/regressions/README.md create mode 100644 resources/eml/regressions/alternative-attachment-disposition.crlf.json create mode 100644 resources/eml/regressions/alternative-attachment-disposition.eml create mode 100644 resources/eml/regressions/alternative-attachment-disposition.json create mode 100644 resources/eml/regressions/alternative-dropped-footer.crlf.json create mode 100644 resources/eml/regressions/alternative-dropped-footer.eml create mode 100644 resources/eml/regressions/alternative-dropped-footer.json create mode 100644 resources/eml/regressions/alternative-named-html.crlf.json create mode 100644 resources/eml/regressions/alternative-named-html.eml create mode 100644 resources/eml/regressions/alternative-named-html.json create mode 100644 resources/eml/regressions/alternative-nested-dropped.crlf.json create mode 100644 resources/eml/regressions/alternative-nested-dropped.eml create mode 100644 resources/eml/regressions/alternative-nested-dropped.json create mode 100644 resources/eml/regressions/alternative-related-image.crlf.json create mode 100644 resources/eml/regressions/alternative-related-image.eml create mode 100644 resources/eml/regressions/alternative-related-image.json create mode 100644 resources/eml/regressions/boundary-of-dashes.crlf.json create mode 100644 resources/eml/regressions/boundary-of-dashes.eml create mode 100644 resources/eml/regressions/boundary-of-dashes.json create mode 100644 resources/eml/regressions/close-delimiter-first.crlf.json create mode 100644 resources/eml/regressions/close-delimiter-first.eml create mode 100644 resources/eml/regressions/close-delimiter-first.json create mode 100644 resources/eml/regressions/close-delimiter-mid-line.crlf.json create mode 100644 resources/eml/regressions/close-delimiter-mid-line.eml create mode 100644 resources/eml/regressions/close-delimiter-mid-line.json create mode 100644 resources/eml/regressions/date-without-final-newline.crlf.json create mode 100644 resources/eml/regressions/date-without-final-newline.eml create mode 100644 resources/eml/regressions/date-without-final-newline.json create mode 100644 resources/eml/regressions/date-zone-est.crlf.json create mode 100644 resources/eml/regressions/date-zone-est.eml create mode 100644 resources/eml/regressions/date-zone-est.json create mode 100644 resources/eml/regressions/date-zone-military.crlf.json create mode 100644 resources/eml/regressions/date-zone-military.eml create mode 100644 resources/eml/regressions/date-zone-military.json create mode 100644 resources/eml/regressions/date-zone-ut.crlf.json create mode 100644 resources/eml/regressions/date-zone-ut.eml create mode 100644 resources/eml/regressions/date-zone-ut.json create mode 100644 resources/eml/regressions/date-zone-z.crlf.json create mode 100644 resources/eml/regressions/date-zone-z.eml create mode 100644 resources/eml/regressions/date-zone-z.json create mode 100644 resources/eml/regressions/doubly-encoded-message.crlf.json create mode 100644 resources/eml/regressions/doubly-encoded-message.eml create mode 100644 resources/eml/regressions/doubly-encoded-message.json create mode 100644 resources/eml/regressions/empty-nested-message-base64.crlf.json create mode 100644 resources/eml/regressions/empty-nested-message-base64.eml create mode 100644 resources/eml/regressions/empty-nested-message-base64.json create mode 100644 resources/eml/regressions/empty-nested-message.crlf.json create mode 100644 resources/eml/regressions/empty-nested-message.eml create mode 100644 resources/eml/regressions/empty-nested-message.json create mode 100644 resources/eml/regressions/empty-part-then-cut-part.crlf.json create mode 100644 resources/eml/regressions/empty-part-then-cut-part.eml create mode 100644 resources/eml/regressions/empty-part-then-cut-part.json create mode 100644 resources/eml/regressions/empty-structured-fields.crlf.json create mode 100644 resources/eml/regressions/empty-structured-fields.eml create mode 100644 resources/eml/regressions/empty-structured-fields.json create mode 100644 resources/eml/regressions/empty-subject-blanks.crlf.json create mode 100644 resources/eml/regressions/empty-subject-blanks.eml create mode 100644 resources/eml/regressions/empty-subject-blanks.json create mode 100644 resources/eml/regressions/empty-subject-folded.crlf.json create mode 100644 resources/eml/regressions/empty-subject-folded.eml create mode 100644 resources/eml/regressions/empty-subject-folded.json create mode 100644 resources/eml/regressions/empty-subject.crlf.json create mode 100644 resources/eml/regressions/empty-subject.eml create mode 100644 resources/eml/regressions/empty-subject.json create mode 100644 resources/eml/regressions/fallback-delimiter-after-text.crlf.json create mode 100644 resources/eml/regressions/fallback-delimiter-after-text.eml create mode 100644 resources/eml/regressions/fallback-delimiter-after-text.json create mode 100644 resources/eml/regressions/garbage-line-before-fold.crlf.json create mode 100644 resources/eml/regressions/garbage-line-before-fold.eml create mode 100644 resources/eml/regressions/garbage-line-before-fold.json create mode 100644 resources/eml/regressions/header-name-blanks-before-colon.crlf.json create mode 100644 resources/eml/regressions/header-name-blanks-before-colon.eml create mode 100644 resources/eml/regressions/header-name-blanks-before-colon.json create mode 100644 resources/eml/regressions/header-name-colons-and-blanks.crlf.json create mode 100644 resources/eml/regressions/header-name-colons-and-blanks.eml create mode 100644 resources/eml/regressions/header-name-colons-and-blanks.json create mode 100644 resources/eml/regressions/header-name-form-feed.crlf.json create mode 100644 resources/eml/regressions/header-name-form-feed.eml create mode 100644 resources/eml/regressions/header-name-form-feed.json create mode 100644 resources/eml/regressions/header-name-leading-colon.crlf.json create mode 100644 resources/eml/regressions/header-name-leading-colon.eml create mode 100644 resources/eml/regressions/header-name-leading-colon.json create mode 100644 resources/eml/regressions/header-name-nul.crlf.json create mode 100644 resources/eml/regressions/header-name-nul.eml create mode 100644 resources/eml/regressions/header-name-nul.json create mode 100644 resources/eml/regressions/header-name-smuggled-subject.crlf.json create mode 100644 resources/eml/regressions/header-name-smuggled-subject.eml create mode 100644 resources/eml/regressions/header-name-smuggled-subject.json create mode 100644 resources/eml/regressions/header-name-space.crlf.json create mode 100644 resources/eml/regressions/header-name-space.eml create mode 100644 resources/eml/regressions/header-name-space.json create mode 100644 resources/eml/regressions/inline-text-with-filename.crlf.json create mode 100644 resources/eml/regressions/inline-text-with-filename.eml create mode 100644 resources/eml/regressions/inline-text-with-filename.json create mode 100644 resources/eml/regressions/inner-headers-cut-by-outer-delimiter.crlf.json create mode 100644 resources/eml/regressions/inner-headers-cut-by-outer-delimiter.eml create mode 100644 resources/eml/regressions/inner-headers-cut-by-outer-delimiter.json create mode 100644 resources/eml/regressions/mixed-calendar.crlf.json create mode 100644 resources/eml/regressions/mixed-calendar.eml create mode 100644 resources/eml/regressions/mixed-calendar.json create mode 100644 resources/eml/regressions/mixed-disposition.crlf.json create mode 100644 resources/eml/regressions/mixed-disposition.eml create mode 100644 resources/eml/regressions/mixed-disposition.json create mode 100644 resources/eml/regressions/mixed-image-attachment.crlf.json create mode 100644 resources/eml/regressions/mixed-image-attachment.eml create mode 100644 resources/eml/regressions/mixed-image-attachment.json create mode 100644 resources/eml/regressions/mixed-image-inline.crlf.json create mode 100644 resources/eml/regressions/mixed-image-inline.eml create mode 100644 resources/eml/regressions/mixed-image-inline.json create mode 100644 resources/eml/regressions/mixed-image.crlf.json create mode 100644 resources/eml/regressions/mixed-image.eml create mode 100644 resources/eml/regressions/mixed-image.json create mode 100644 resources/eml/regressions/mixed-message-inline.crlf.json create mode 100644 resources/eml/regressions/mixed-message-inline.eml create mode 100644 resources/eml/regressions/mixed-message-inline.json create mode 100644 resources/eml/regressions/mixed-message.crlf.json create mode 100644 resources/eml/regressions/mixed-message.eml create mode 100644 resources/eml/regressions/mixed-message.json create mode 100644 resources/eml/regressions/mixed-pdf-inline.crlf.json create mode 100644 resources/eml/regressions/mixed-pdf-inline.eml create mode 100644 resources/eml/regressions/mixed-pdf-inline.json create mode 100644 resources/eml/regressions/mixed-pdf.crlf.json create mode 100644 resources/eml/regressions/mixed-pdf.eml create mode 100644 resources/eml/regressions/mixed-pdf.json create mode 100644 resources/eml/regressions/mixed-text-image-html.crlf.json create mode 100644 resources/eml/regressions/mixed-text-image-html.eml create mode 100644 resources/eml/regressions/mixed-text-image-html.json create mode 100644 resources/eml/regressions/nested-headers-cut-by-delimiter.crlf.json create mode 100644 resources/eml/regressions/nested-headers-cut-by-delimiter.eml create mode 100644 resources/eml/regressions/nested-headers-cut-by-delimiter.json create mode 100644 resources/eml/regressions/no-delimiter-close-mid-line.crlf.json create mode 100644 resources/eml/regressions/no-delimiter-close-mid-line.eml create mode 100644 resources/eml/regressions/no-delimiter-close-mid-line.json create mode 100644 resources/eml/regressions/readme-example.crlf.json create mode 100644 resources/eml/regressions/readme-example.eml create mode 100644 resources/eml/regressions/readme-example.json create mode 100644 resources/eml/regressions/related-cid-image-no-disposition.crlf.json create mode 100644 resources/eml/regressions/related-cid-image-no-disposition.eml create mode 100644 resources/eml/regressions/related-cid-image-no-disposition.json create mode 100644 resources/eml/regressions/related-cid-inline-image.crlf.json create mode 100644 resources/eml/regressions/related-cid-inline-image.eml create mode 100644 resources/eml/regressions/related-cid-inline-image.json create mode 100644 resources/eml/regressions/related-disposition.crlf.json create mode 100644 resources/eml/regressions/related-disposition.eml create mode 100644 resources/eml/regressions/related-disposition.json create mode 100644 resources/eml/regressions/root-attachment-disposition.crlf.json create mode 100644 resources/eml/regressions/root-attachment-disposition.eml create mode 100644 resources/eml/regressions/root-attachment-disposition.json create mode 100644 resources/eml/regressions/single-text.crlf.json create mode 100644 resources/eml/regressions/single-text.eml create mode 100644 resources/eml/regressions/single-text.json create mode 100644 resources/eml/regressions/unopened-multiparts.crlf.json create mode 100644 resources/eml/regressions/unopened-multiparts.eml create mode 100644 resources/eml/regressions/unopened-multiparts.json create mode 100644 resources/eml/regressions/unstructured-fields.crlf.json create mode 100644 resources/eml/regressions/unstructured-fields.eml create mode 100644 resources/eml/regressions/unstructured-fields.json create mode 100644 resources/eml/regressions/unterminated-alternative.crlf.json create mode 100644 resources/eml/regressions/unterminated-alternative.eml create mode 100644 resources/eml/regressions/unterminated-alternative.json create mode 100644 resources/eml/regressions/utf16-dangling-byte.crlf.json create mode 100644 resources/eml/regressions/utf16-dangling-byte.eml create mode 100644 resources/eml/regressions/utf16-dangling-byte.json create mode 100644 resources/eml/regressions/utf7-terminators.crlf.json create mode 100644 resources/eml/regressions/utf7-terminators.eml create mode 100644 resources/eml/regressions/utf7-terminators.json create mode 100644 resources/sieve/alternative.eml create mode 100644 resources/sieve/headers.eml create mode 100644 resources/sieve/html.eml create mode 100644 resources/sieve/mixed-attachment.eml create mode 100644 resources/sieve/nested.eml create mode 100644 resources/sieve/plain.eml create mode 100644 scripts/corpora.sha256 create mode 100755 scripts/fetch-corpora.sh delete mode 100644 src/core/address.rs delete mode 100644 src/core/body.rs delete mode 100644 src/core/builder.rs delete mode 100644 src/core/header.rs delete mode 100644 src/core/message.rs delete mode 100644 src/core/mod.rs delete mode 100644 src/core/rkyv.rs create mode 100644 src/datetime.rs delete mode 100644 src/decoders/base64.rs create mode 100644 src/decoders/charsets/ascii.rs create mode 100644 src/decoders/charsets/label.rs delete mode 100644 src/decoders/charsets/map.rs create mode 100644 src/decoders/charsets/tables.rs delete mode 100644 src/decoders/charsets/utf.rs create mode 100644 src/decoders/charsets/utf16.rs create mode 100644 src/decoders/charsets/utf7.rs create mode 100644 src/decoders/charsets/utf8.rs delete mode 100644 src/decoders/encoded_word.rs delete mode 100644 src/decoders/hex.rs rename src/decoders/{html.rs => html/entities.rs} (80%) create mode 100644 src/decoders/html/meta.rs create mode 100644 src/decoders/html/mod.rs create mode 100644 src/decoders/html/text.rs create mode 100644 src/decoders/prefix.rs create mode 100644 src/decoders/preview.rs delete mode 100644 src/decoders/quoted_printable.rs create mode 100644 src/fields/address.rs create mode 100644 src/fields/content_type.rs create mode 100644 src/fields/date.rs create mode 100644 src/fields/id.rs create mode 100644 src/fields/list.rs create mode 100644 src/fields/mod.rs create mode 100644 src/fields/raw.rs create mode 100644 src/fields/received.rs create mode 100644 src/fields/tests.rs rename src/{parsers => }/fields/thread.rs (85%) create mode 100644 src/fields/unstructured.rs create mode 100644 src/header_name.rs create mode 100644 src/parser/builder.rs create mode 100644 src/parser/classify.rs create mode 100644 src/parser/delimiter.rs create mode 100644 src/parser/header_block.rs create mode 100644 src/parser/mod.rs create mode 100644 src/parser/tests.rs delete mode 100644 src/parsers/fields/address.rs delete mode 100644 src/parsers/fields/content_type.rs delete mode 100644 src/parsers/fields/date.rs delete mode 100644 src/parsers/fields/id.rs delete mode 100644 src/parsers/fields/list.rs delete mode 100644 src/parsers/fields/mod.rs delete mode 100644 src/parsers/fields/raw.rs delete mode 100644 src/parsers/fields/received.rs delete mode 100644 src/parsers/fields/unstructured.rs delete mode 100644 src/parsers/header.rs delete mode 100644 src/parsers/message.rs delete mode 100644 src/parsers/mime.rs delete mode 100644 src/parsers/mod.rs delete mode 100644 src/parsers/preview.rs create mode 100644 src/scan/lib_memchr.rs create mode 100644 src/scan/mod.rs create mode 100644 src/scan/neon.rs create mode 100644 src/scan/scalar.rs create mode 100644 src/scan/set.rs create mode 100644 src/scan/simd.rs create mode 100644 src/scan/swar.rs create mode 100644 src/scan/tests.rs create mode 100644 src/scan/x86.rs create mode 100644 src/store/mod.rs create mode 100644 src/store/str.rs create mode 100644 src/store/table.rs create mode 100644 src/view/address.rs create mode 100644 src/view/content_type.rs create mode 100644 src/view/headers.rs create mode 100644 src/view/message.rs create mode 100644 src/view/mod.rs create mode 100644 src/view/part.rs create mode 100644 src/view/received.rs create mode 100644 src/view/serialize.rs create mode 100644 tests/api.rs create mode 100644 tests/classification.rs create mode 100644 tests/issue_109.rs create mode 100644 tests/issues.rs create mode 100644 tests/review_fields.rs create mode 100644 tests/review_structure.rs create mode 100644 tests/structure.rs create mode 100644 tests/support/mod.rs create mode 100644 tests/text_prefix.rs diff --git a/.gitignore b/.gitignore index 6873570..c86de22 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ perf.* *.svg Cargo.lock +.ignore +*.failed diff --git a/CHANGELOG.md b/CHANGELOG.md index d07cbf0..3878127 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,238 +1,484 @@ -mail-parser 0.11.9 -================================ +# 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.0] - Unreleased + +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 `` charset declarations rewritten to UTF-8, looking only before `` 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()` and `decode_append()`, and `decoders::charsets::decode()` and `decode_append()`. +- `PartId` and `MessageId`, and `From 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`; `date()` and `resent_date()` return `Option`; `comments()` and `mime_version()` return `Option<&str>`; `in_reply_to()`, `references()`, `keywords()`, `resent_message_id()` and `return_path()` return `Option`; `received()` returns `Option`. +- `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` | +| `date()` (`Option<&DateTime>`), `resent_date()` (`&HeaderValue`) | `Option` | +| `in_reply_to()`, `references()`, `keywords()`, `resent_message_id()`, `return_path()` (`&HeaderValue`) | `Option` | +| `list_archive()` to `list_unsubscribe()` (`&HeaderValue`) | `Option` | +| `comments()`, `mime_version()` (`&HeaderValue`) | `Option<&str>` | +| `received()` (`Option<&Received>`) | `Option` | +| `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` | +| `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)` | `HeaderValue::Text(&str)` | +| `HeaderValue::TextList(Vec>)` | `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)` | `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`) | `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. -mail-parser 0.11.8 -================================ -- Fix: `HeaderName` breaks rkyv serialization from <= 0.11.6. +## [0.11.8] - 2026-08-22 -mail-parser 0.11.7 -================================ +### Fixed +- `HeaderName` breaks rkyv serialization from <= 0.11.6. + +## [0.11.7] - 2026-08-20 + +### Added - Added more IANA headers. -- Fix: `DateTime::to_timezone` corrupting non-whole-hour offsets by storing leftover seconds in `tz_minute` (#158) -mail-parser 0.11.6 -================================ -- Fix: Missing whitespace between a quoted name and a following encoded word (#150) -- Fix: `panic` when a `Received` header ends with a folded line (#155) -- Fix: `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) -- Fix: Multi-word display names followed by a comment no longer produce a fabricated address (#153) +### Fixed +- `DateTime::to_timezone` corrupting non-whole-hour offsets by storing leftover seconds in `tz_minute` (#158) -mail-parser 0.11.5 -================================ -- Fix: Address names containing LF are not parsed correctly (#149) -- Fix: Decode the `iso-8859-1` label as `windows-1252` per the WHATWG Encoding Standard (#131) -- Fix: `panic` with messages containing corrupted eml attachments (#120). +## [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. -mail-parser 0.11.4 -================================ +### 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. -- `parse_date()` doesn't handle UTC+12 and greater (#148) - Leniently decode quoted-printable bodies with invalid `=` escapes (#144) -mail-parser 0.11.3 -================================ +### 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) -mail-parser 0.11.2 -================================ +## [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) -mail-parser 0.11.1 -================================ +## [0.11.1] - 2025-08-18 + +### Fixed - Fix `DateTime::from_timestamp` to handle negative timestamps correctly. -mail-parser 0.11.0 -================================ +## [0.11.0] - 2025-05-11 + +### Added - `rkyv` zero-copy deserialization support. + +### Changed - Changed `usize` to `u32` types. - Renamed `serde_support` feature to `serde`. -- Fix: Parsing of headers without LFs (#102) -mail-parser 0.10.2 -================================ +### Fixed +- Parsing of headers without LFs (#102) + +## [0.10.2] - 2025-01-28 + +### Fixed - Fixed `HeaderName` enum order to avoid breaking bincode serialization. -mail-parser 0.10.1 -================================ +## [0.10.1] - 2025-01-26 + +### Fixed - Fixed `HeaderName::parse` function. -mail-parser 0.10.0 -================================ +## [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. -- Added `DkimSignature`, `ArcAuthenticationResults`, `ArcMessageSignature` and `ArcSeal` headers. - `HeaderName` is non-exhaustive. - Parse obsolete timezones (#95). -- Fix: Folding ws between "Content-Type:" and "plain/text" leads to empty header (#96). -- Fix: Multiline quoted continuations (closes #92). -- Fix: Deserialize (#93). - 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. -mail-parser 0.9.4 -================================ +### 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). -mail-parser 0.9.3 -================================ +## [0.9.3] - 2024-03-28 + +### Fixed - Fixed parsing of address names containing @ (#80) -mail-parser 0.9.2 -================================ +## [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. -mail-parser 0.9.1 -================================ -- Fixed panic when Content-Disposition is empty (#63) -- Removed `content_type()` and `address()` functions that could `panic!`. Use `as_content_type()` and `as_address()` instead. +## [0.9.1] - 2023-09-22 + +### Changed - Updated Rust edition to 2021. -mail-parser 0.9.0 -================================ +### 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. -- Parsing is now done using `MessageParser`, which allows to customize the parsing process. +### Added - Added parser for `Received` headers. - Added `MessageParser::parse_headers` function to parse only the headers of a message. -- Removed `RfcHeader` enum, now all headers are represented using `HeaderName`. + +### 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. -mail-parser 0.8.2 -================================ -- Fix: Parsing address name with \ characters (#41) -- Fix: Missing space when folded header begins with RFC2047 word (#43) +### Removed +- Removed `RfcHeader` enum, now all headers are represented using `HeaderName`. -mail-parser 0.8.1 -================================ +## [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. -mail-parser 0.8.0 -================================ +## [0.8.0] - 2022-12-01 + +### Changed - Removed get_() prefixes (#31). - Maildir import: Use modified time instead of created time (#32) -mail-parser 0.7.0 -================================ -- Base64/QuotedPrintable decoding optimizations. +## [0.7.0] - 2022-10-21 + +### Added - 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. + +### Changed +- Base64/QuotedPrintable decoding optimizations. +- Refactoring or ``MessageStream`` to use iterators more efficiently. + +### Fixed - Fixed support for empty messages. - Fixed raw offsets of multipart/* parts to include MIME epilogue. - 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). - Add support for gb2312 charsets (#30). -mail-parser 0.6.0 -================================ +## [0.6.0] - 2022-08-21 + +### Added - Maildir parsing support. -- Headers and attributes are now stored in a `Vec` instead of a `HashMap` for a tiny performance enhancement. - 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. -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. - Improved `MessagePart` API. - Nested base64/quoted-printable encoded message/rfc822 parts are automatically parsed when calling `get_message`. - 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) -mail-parser 0.4.7 -================================ +## [0.4.7] - 2022-06-03 + +### Added - Retrieving message headers in order (#19) - 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. - Support for malformed Return-Path headers. - Support for ks_c_5601 charsets (#20) -mail-parser 0.4.6 -================================ +## [0.4.6] + +### Fixed - DateTime is_valid() fix (#15) - -mail-parser 0.4.5 -================================ + +## [0.4.5] - 2022-03-14 + +### Added - DateTime to UNIX timestamp conversion. - Ord, PartialOrd support for DateTime (#13). + +### Fixed - 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. - Text and HTML message body preview. + +### Changed - 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). - 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 `MimeHeader::get_attachment_name` for simplified access to a MIME attachment file name. -mail-parser 0.4.1 -================================ -- Lazy parsing of nested e-mail messages. +## [0.4.1] - 2021-12-16 + +### Added - 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. - Improved API. - Parts are now generics. -mail-parser 0.3.1 -================================ +## [0.3.1] - 2021-12-15 + +### Added - Support for non-standard headers. + +### Changed - Raw message offsets are stored in the message object. - Message body structure is now stored in the message object. -mail-parser 0.3 -================================ -- Improved API, now `Message::parse` returns `Option` to indicate when parsing was successful. -- Headers are now stored internally in a `HashMap` instead of `struct` fields. +## [0.3.0] - 2021-11-08 + +### Added - Added support for new RFCs: - [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 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) -mail-parser 0.2.1 -================================ +### Changed +- Improved API, now `Message::parse` returns `Option` 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. -mail-parser 0.2 -================================ -- 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.2.0] - 2021-11-03 + +### Added - 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. -mail-parser 0.1 -================================ +## [0.1.0] - 2021-11-01 + +### Added - Initial release with plenty of `unsafe` code to speed things up. - - - - - - diff --git a/Cargo.toml b/Cargo.toml index 3fc4492..2156996 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,9 @@ [package] name = "mail-parser" description = "Fast and robust e-mail parsing library for Rust" -version = "0.11.9" +version = "1.0.0" edition = "2024" +rust-version = "1.98" authors = [ "Stalwart Labs "] license = "Apache-2.0 OR MIT" repository = "https://github.com/stalwartlabs/mail-parser" @@ -10,31 +11,42 @@ homepage = "https://github.com/stalwartlabs/mail-parser" keywords = ["email", "mail", "parser", "parse", "mime"] categories = ["email", "parser-implementations"] readme = "README.md" -resolver = "2" [dependencies] -hashify = { version = "0.3" } -memchr = { version = "2.7", optional = true } +hashify = "0.3" +memchr = "2.8" +simdutf8 = "0.1" +encodify = { path = "../encodify" } encoding_rs = { version = "0.8", optional = true } serde = { version = "1.0", features = ["derive"], optional = true } -rkyv = { version = "0.8", optional = true } [dev-dependencies] -mail-parser = { path = ".", features = ["serde", "full_encoding"] } -serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -bincode = "1.3.3" chrono = "0.4" +criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support"] } [features] default = [] -full_encoding = ["encoding_rs"] +full_encoding = ["dep:encoding_rs"] serde = ["dep:serde"] -rkyv = ["dep:rkyv"] -base64_slice = ["dep:memchr"] + +[[bench]] +name = "kernels" +harness = false + +[[bench]] +name = "resolve" +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] debug = true - -[lib] -doctest = false diff --git a/README.md b/README.md index 8a7d56a..500da7f 100644 --- a/README.md +++ b/README.md @@ -3,38 +3,40 @@ [![crates.io](https://img.shields.io/crates/v/mail-parser)](https://crates.io/crates/mail-parser) [![build](https://github.com/stalwartlabs/mail-parser/actions/workflows/rust.yml/badge.svg)](https://github.com/stalwartlabs/mail-parser/actions/workflows/rust.yml) [![docs.rs](https://img.shields.io/docsrs/mail-parser)](https://docs.rs/mail-parser) +[![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) -_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). +_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). -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). +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). -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. +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. -Unlike other e-mail parsing libraries that return nested representations of the different MIME parts in a message, this library -conforms to [RFC 8621, Section 4.1.4](https://datatracker.ietf.org/doc/html/rfc8621#section-4.1.4) and provides a more human-friendly -representation of the message contents consisting of just text body parts, html body parts and attachments. Additionally, conversion to/from -HTML and plain text inline body parts is done automatically when the _alternative_ version is missing. +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. -Performance and memory safety were two important factors while designing _mail-parser_: +## Features -- **Zero-copy**: Practically all strings returned by this library are `Cow` references to the input raw message. -- **High performance Base64 decoding** based on Chromium's decoder ([the fastest non-SIMD decoder](https://github.com/lemire/fastbase64)). -- **Fast parsing** of message header fields, character set names and HTML entities using [perfect hashing](https://en.wikipedia.org/wiki/Perfect_hash_function). -- Written in **100% safe** Rust with no external dependencies. -- Every function in the library has been [fuzzed](#testing-fuzzing--benchmarking) and thoroughly [tested with MIRI](#testing-fuzzing--benchmarking). +- **Fast parsing**: + - Boundaries and header fields are found by SIMD kernels (NEON on aarch64, AVX2 and SSE2 on x86-64, `memchr` on every other target). + - Base64 and quoted-printable are decoded by the SIMD codecs of [encodify](https://github.com/stalwartlabs/encodify) + - UTF-8 is validated by [simdutf8](https://crates.io/crates/simdutf8) + - Header names, charset labels and HTML entities are looked up with perfect hashing through [hashify](https://crates.io/crates/hashify). +- **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. +- **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 - let input = br#"From: Art Vandelay (Vandelay Industries) +use mail_parser::{Address, MessageParser, PartKind}; + +let input = br#"From: Art Vandelay (Vandelay Industries) To: "Colleagues": "James Smythe" ; Friends: jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= ; Date: Sat, 20 Nov 2021 14:22:01 -0800 @@ -75,126 +77,294 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 --festivus-- "#; - let message = MessageParser::default().parse(input).unwrap(); +let message = MessageParser::default().parse(input).expect("a message"); - // Parses addresses (including comments), lists and groups - assert_eq!( - message.from().unwrap().first().unwrap(), - &Addr::new( - "Art Vandelay (Vandelay Industries)".into(), - "art@vandelay.com" - ) - ); +let sender = message.from().and_then(|from| from.first()).expect("a sender"); +assert_eq!(sender.name(), Some("Art Vandelay (Vandelay Industries)")); +assert_eq!(sender.address(), Some("art@vandelay.com")); - assert_eq!( - message.to().unwrap().as_group().unwrap(), - &[ - 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"), - ] - ) - ] - ); +let to = message.to().expect("recipients"); +let addresses: Vec<_> = to.mailboxes().filter_map(|mailbox| mailbox.address()).collect(); +assert_eq!(addresses, ["james@vandelay.com", "jane@example.com", "john@example.com"]); +let Some(Address::Group(friends)) = to.iter().nth(1) else { + panic!("the second item is a group"); +}; +assert_eq!(friends.name(), Some("Friends")); +assert_eq!(friends.mailboxes().nth(1).and_then(|mailbox| mailbox.name()), Some("John Smîth")); - assert_eq!( - message.date().unwrap().to_rfc3339(), - "2021-11-20T14:22:01-08:00" - ); +assert_eq!(message.date().expect("a date").to_rfc3339(), "2021-11-20T14:22:01-08:00"); +assert_eq!(message.subject(), Some("Why not both importing AND exporting? ☺")); - // RFC2047 support for encoded text in message readers - assert_eq!( - message.subject().unwrap(), - "Why not both importing AND exporting? ☺" - ); +assert_eq!( + message.body_html(0).as_deref(), + Some(concat!( + "

I was thinking about quitting the “exporting” to ", + "focus just on the “importing”,

but then I thought,", + " why not do both? ☺

" + )) +); +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 - assert_eq!( - message.body_html(0).unwrap(), - concat!( - "

I was thinking about quitting the “exporting” to ", - "focus just on the “importing”,

but then I thought,", - " why not do both? ☺

" - ) - ); +let nested = message + .attachments() + .find_map(|part| part.nested()) + .expect("a nested message"); +assert_eq!(nested.subject(), Some("Exporting my book about coffee tables")); +assert_eq!(nested.body_text(0).as_deref(), Some("ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!")); +assert_eq!( + nested.body_html(0).as_deref(), + Some("ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!") +); - // HTML parts are converted to plain text (and viceversa) when missing - assert_eq!( - message.body_text(0).unwrap(), - concat!( - "I was thinking about quitting the “exporting” to focus just on the", - " “importing”,\nbut then I thought, why not do both? ☺\n" - ) - ); - - // Supports nested messages as well as multipart/digest - let nested_message = 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(), - "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!" - ); - - 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()); +let image = nested.attachments().next().expect("an attachment"); +assert_eq!(image.attachment_name(), Some("Book about ☕ tables.gif")); +assert!(matches!(image.kind(), PartKind::Binary)); +assert_eq!(image.decoded_len(), 42); ``` -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", + "

Hello

\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"

Hello

"); + +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 , 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: \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 + +**[PLACEHOLDER: performance section, to be written after the final benchmarks against 0.11 and against other Rust and C/C++ parsers.]** + +## 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 -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 - $ cargo test --all-features + $ cargo test --features full_encoding,serde ``` -or, to run the testsuite with MIRI: +and without optional features: ```bash - $ cargo +nightly miri test --all-features + $ cargo test ``` -To fuzz the library with `cargo-fuzz`: +**[PLACEHOLDER: fuzzing and Miri commands, to be written after the final fuzzing and Miri runs.]** + +To run the micro-benchmarks of the SIMD kernels and of string resolution: ```bash - $ cargo +nightly fuzz run mail_parser -``` - -and, to run the benchmarks: - -```bash - $ cargo +nightly bench --all-features + $ cargo bench --bench kernels + $ cargo bench --bench resolve ``` ## Conformed RFCs @@ -215,63 +385,70 @@ and, to run the benchmarks: - [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 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 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 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) ## 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-16, UTF-16BE, UTF-16LE - UTF-7 - US-ASCII -- ISO-8859-1 -- ISO-8859-2 -- ISO-8859-3 -- ISO-8859-4 -- ISO-8859-5 -- ISO-8859-6 -- ISO-8859-7 -- ISO-8859-8 -- ISO-8859-9 -- ISO-8859-10 -- ISO-8859-13 -- ISO-8859-14 -- ISO-8859-15 +- ISO-8859-1 +- ISO-8859-2 +- ISO-8859-3 +- ISO-8859-4 +- ISO-8859-5 +- ISO-8859-6 +- ISO-8859-7 +- ISO-8859-8 +- ISO-8859-9 +- ISO-8859-10 +- ISO-8859-13 +- ISO-8859-14 +- ISO-8859-15 - ISO-8859-16 -- CP1250 -- CP1251 -- CP1252 -- CP1253 -- CP1254 -- CP1255 -- CP1256 -- CP1257 -- CP1258 +- windows-1250 +- windows-1251 +- windows-1252 +- windows-1253 +- windows-1254 +- windows-1255 +- windows-1256 +- windows-1257 +- windows-1258 - KOI8-R -- KOI8_U -- MACINTOSH +- KOI8-U +- Macintosh (Mac OS Roman) - IBM850 - TIS-620 - -Supported character sets via the optional dependency [encoding_rs](https://crates.io/crates/encoding_rs): - -- SHIFT_JIS -- BIG5 -- EUC-JP -- EUC-KR + +With the `full_encoding` feature, through [encoding_rs](https://crates.io/crates/encoding_rs): + +- Shift_JIS +- EUC-JP +- ISO-2022-JP +- Big5 +- GBK (GB2312) - GB18030 -- GBK -- ISO-2022-JP -- WINDOWS-874 -- IBM-866 +- EUC-KR +- windows-874 +- IBM866 +- x-mac-cyrillic +- x-user-defined ## License Licensed under either of - * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + * Apache License, Version 2.0 ([LICENSES/Apache-2.0.txt](LICENSES/Apache-2.0.txt) or ) + * MIT license ([LICENSES/MIT.txt](LICENSES/MIT.txt) or ) at your option. diff --git a/benches/kernels.rs b/benches/kernels.rs new file mode 100644 index 0000000..655e95a --- /dev/null +++ b/benches/kernels.rs @@ -0,0 +1,197 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * 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::scan::Kernel; +use memchr::{memchr_iter, memmem}; +use std::{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 { + 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)> { + 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> { + 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 { + 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 { + 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> = 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::() + }) + }); + 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::() + }) + }, + ); + } + } + group.finish(); +} + +fn field_split(c: &mut Criterion) { + let mut group = c.benchmark_group("field_split"); + let blocks: Vec> = 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::() + }) + }); + } + 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 +} +criterion_main!(benches); diff --git a/benches/resolve.rs b/benches/resolve.rs new file mode 100644 index 0000000..7dee2bc --- /dev/null +++ b/benches/resolve.rs @@ -0,0 +1,113 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * 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::() + } + HeaderValue::Empty | HeaderValue::DateTime(_) | HeaderValue::Received(_) => 0, + }; + } + } + total +} + +fn corpora() -> Vec { + 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> = 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::() + }) + }); + 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::() + }) + }); + } + 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); diff --git a/benches/support/corpus.rs b/benches/support/corpus.rs new file mode 100644 index 0000000..249aa89 --- /dev/null +++ b/benches/support/corpus.rs @@ -0,0 +1,647 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * 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 { + 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, +} + +#[derive(Debug, Clone)] +pub struct Corpus { + pub name: String, + pub samples: Vec, +} + +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) -> 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 { + 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 { + 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) -> Vec { + 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 { + 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 { + 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 { + 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 { + (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( + "\n\n\n\n", + ); + while out.len() < target { + match rng.below(6) { + 0 => { + let _ = writeln!(out, "", rng.below(1000)); + } + 1 => { + let _ = writeln!( + out, + "
{}
", + sentence(rng, 12) + ); + } + 2 => { + let _ = writeln!( + out, + "{}", + rng.next(), + rng.next(), + sentence(rng, 3) + ); + } + 3 => out.push_str("
\n-----\n"), + _ => { + let _ = writeln!(out, "

{}

", sentence(rng, 20)); + } + } + } + out.push_str("\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 ; 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 {}\" \nTo: Recipient , \"Another Person\" \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 { + [(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: \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 { + (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: \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 { + (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: , \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 { + (1..=6) + .map(|depth| Sample { + name: format!("forwarded-{depth}"), + bytes: nested_message(rng, depth).into_bytes(), + }) + .collect() +} + +fn dashes(rng: &mut Rng) -> Vec { + 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 { + 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 { + 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

html

\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\ntwo\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() +} diff --git a/examples/custom_parser.rs b/examples/custom_parser.rs index ffb3c00..94209fc 100644 --- a/examples/custom_parser.rs +++ b/examples/custom_parser.rs @@ -4,71 +4,81 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ -use mail_parser::{HeaderName, MessageParser}; +use mail_parser::{HeaderForm, HeaderName, MessageParser}; -const MESSAGE: &str = r#"From: Art Vandelay (Vandelay Industries) -To: "Colleagues": "James Smythe" ; Friends: - jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= ; -Date: Sat, 20 Nov 2021 14:22:01 -0800 -Subject: Why not both importing AND exporting? =?utf-8?b?4pi6?= -Content-Type: multipart/mixed; boundary="festivus"; - ---festivus -Content-Type: text/html; charset="us-ascii" -Content-Transfer-Encoding: base64 - -PGh0bWw+PHA+SSB3YXMgdGhpbmtpbmcgYWJvdXQgcXVpdHRpbmcgdGhlICZsZHF1bztle -HBvcnRpbmcmcmRxdW87IHRvIGZvY3VzIGp1c3Qgb24gdGhlICZsZHF1bztpbXBvcnRpbm -cmcmRxdW87LDwvcD48cD5idXQgdGhlbiBJIHRob3VnaHQsIHdoeSBub3QgZG8gYm90aD8 -gJiN4MjYzQTs8L3A+PC9odG1sPg== ---festivus -Content-Type: message/rfc822 - -From: "Cosmo Kramer" -Subject: Exporting my book about coffee tables -Content-Type: multipart/mixed; boundary="giddyup"; - ---giddyup -Content-Type: text/plain; charset="utf-16" -Content-Transfer-Encoding: quoted-printable - -=FF=FE=0C!5=D8"=DD5=D8)=DD5=D8-=DD =005=D8*=DD5=D8"=DD =005=D8"= -=DD5=D85=DD5=D8-=DD5=D8,=DD5=D8/=DD5=D81=DD =005=D8*=DD5=D86=DD = -=005=D8=1F=DD5=D8,=DD5=D8,=DD5=D8(=DD =005=D8-=DD5=D8)=DD5=D8"= -=DD5=D8=1E=DD5=D80=DD5=D8"=DD!=00 ---giddyup -Content-Type: image/gif; name*1="about "; name*0="Book "; - name*2*=utf-8''%e2%98%95 tables.gif -Content-Transfer-Encoding: Base64 -Content-Disposition: attachment - -R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 ---giddyup-- ---festivus-- -"#; +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 \r\n\ +To: jane@example.com\r\n\ +Subject: Latex imports\r\n\ +X-Sender: Kel Varnsen \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() { - // Parse only the message headers - let _headers = MessageParser::new() + 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) - .unwrap() - .headers(); + .expect("the header block parses"); + println!( + "\nparse_headers: {} header fields, body at byte {}", + headers_only.headers().len(), + headers_only.root_part().offset_body() + ); - // Parse only the message body, ignoring all headers (except MIME headers, which are required to parse the body) - let _message = MessageParser::new() - .with_mime_headers() - .default_header_ignore() - .parse(MESSAGE) - .unwrap(); - - // Parse only To, From, Date, and Subject headers. All other headers are parsed as raw. - let _message = MessageParser::new() - .with_mime_headers() - .header_text(HeaderName::Subject) - .header_address(HeaderName::From) - .header_address(HeaderName::To) - .header_date(HeaderName::Date) - .default_header_raw() - .parse(MESSAGE) - .unwrap(); + println!("\nHeader values parsed on their own:"); + let addresses = + HeaderForm::Addresses.parse(b" Ann , 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" \r\n \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()); } diff --git a/examples/mailbox_iterate_maildir.rs b/examples/mailbox_iterate_maildir.rs index 5ca5593..467d1f4 100644 --- a/examples/mailbox_iterate_maildir.rs +++ b/examples/mailbox_iterate_maildir.rs @@ -4,31 +4,35 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ -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() { - // Iterates a Maildir++ structure printing the results to stdout. - for folder in FolderIterator::new( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("resources") - .join("maildir"), - ".".into(), - ) - .unwrap() - { - let folder = folder.unwrap(); - println!("------\nMailbox: {:?}", folder.name().unwrap_or("INBOX")); - - for message in folder { - let message = message.unwrap(); - println!( - "Message with internal date {}, flags {:?} and content {:?}.", - message.internal_date(), - message.flags(), - String::from_utf8_lossy(message.contents()) +fn main() -> io::Result<()> { + let maildir = env::args_os().nth(1).map_or_else( + || PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/maildir"), + PathBuf::from, + ); + let parser = MessageParser::new(); + let mut buffers = MessageBuffers::new(); + for folder in FolderIterator::new(maildir, Some("."))? { + let folder = folder?; + println!("Folder {}", folder.name().unwrap_or("INBOX")); + for entry in folder { + let entry = entry?; + print!( + " {}, flags {:?}, {} bytes: ", + entry.path().display(), + entry.flags(), + entry.contents().len() ); + 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(()) } diff --git a/examples/mailbox_parse_mbox.rs b/examples/mailbox_parse_mbox.rs index b9e51f6..8fd9551 100644 --- a/examples/mailbox_parse_mbox.rs +++ b/examples/mailbox_parse_mbox.rs @@ -4,16 +4,56 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ -use mail_parser::{MessageParser, mailbox::mbox::MessageIterator}; +use mail_parser::{MessageBuffers, MessageParser, mailbox::mbox::MessageIterator}; +use std::{ + env, + fs::File, + io::{self, BufRead, BufReader}, +}; -fn main() { - // Reads an MBox mailbox from stdin and prints each message as JSON. - for raw_message in MessageIterator::new(std::io::stdin().lock()) { - let raw_message = raw_message.unwrap(); - let message = MessageParser::default() - .parse(raw_message.contents()) - .unwrap(); +const SAMPLE: &[u8] = b"From ann@example.com Sat Jan 3 01:05:34 1996\n\ +From: Ann \n\ +Subject: First message\n\ +\n\ +>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 \n\ +Subject: Second message\n\ +\n\ +Hello.\n"; - println!("{}", serde_json::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(()) +} diff --git a/examples/message_parse.rs b/examples/message_parse.rs index 1b450f6..fca2d62 100644 --- a/examples/message_parse.rs +++ b/examples/message_parse.rs @@ -4,10 +4,9 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ -use mail_parser::*; +use mail_parser::{Address, Mailbox, MessageParser, MessagePart, PartKind}; -fn main() { - let input = br#"From: Art Vandelay (Vandelay Industries) +const MESSAGE: &[u8] = br#"From: Art Vandelay (Vandelay Industries) To: "Colleagues": "James Smythe" ; Friends: jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= ; Date: Sat, 20 Nov 2021 14:22:01 -0800 @@ -48,92 +47,125 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 --festivus-- "#; - let message = MessageParser::default().parse(input).unwrap(); +fn main() { + let message = MessageParser::new() + .parse(MESSAGE) + .expect("the message parses"); - // Parses addresses (including comments), lists and groups - assert_eq!( - message.from().unwrap().first().unwrap(), - &Addr::new( - "Art Vandelay (Vandelay Industries)".into(), - "art@vandelay.com" - ) - ); + println!("Subject: {}", message.subject().unwrap_or_default()); + if let Some(date) = message.date() { + println!("Date: {}", date.to_rfc3339()); + } + for sender in message.from().into_iter().flat_map(|from| from.mailboxes()) { + 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!( - message.to().unwrap().as_group().unwrap(), - &[ - 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"), - ] - ) - ] - ); + println!("\nHeader fields as written, with their parsed values:"); + for header in message.headers().iter() { + println!(" {}: {:?}", header.raw_name(), header.value()); + } - assert_eq!( - message.date().unwrap().to_rfc3339(), - "2021-11-20T14:22:01-08:00" - ); + println!("\nText body (HTML converted to text):"); + for text in message.text_bodies() { + println!("{text}"); + } + println!("\nHTML body:"); + for html in message.html_bodies() { + println!("{html}"); + } - // RFC2047 support for encoded text in message readers - assert_eq!( - message.subject().unwrap(), - "Why not both importing AND exporting? ☺" - ); + println!("\nEvery part of every message, in document order:"); + for part in message.parts() { + describe(part); + } - // HTML and text body parts are returned conforming to RFC8621, Section 4.1.4 - assert_eq!( - message.body_html(0).unwrap(), - concat!( - "

I was thinking about quitting the “exporting” to ", - "focus just on the “importing”,

but then I thought,", - " why not do both? ☺

" - ) - ); + if let Some(multipart) = message.part_by_boundary("giddyup") { + println!( + "\nThe boundary \"giddyup\" belongs to part {}, which has {} children", + multipart.id(), + multipart.children().len() + ); + } - // HTML parts are converted to plain text (and viceversa) when missing - assert_eq!( - message.body_text(0).unwrap(), - concat!( - "I was thinking about quitting the “exporting” to focus just on the", - " “importing”,\nbut then I thought, why not do both? ☺\n" - ) - ); - - // Supports nested messages as well as multipart/digest - let nested_message = message.attachment(0).unwrap().message().unwrap(); + for attachment in message.attachments() { + let PartKind::Message(nested) = attachment.kind() else { + continue; + }; + println!( + "\nNested message {}: {}", + nested.id(), + nested.subject().unwrap_or_default() + ); + for text in nested.text_bodies() { + println!(" text: {text}"); + } + for file in nested.attachments() { + println!( + " attachment {:?}: {} bytes", + file.attachment_name().unwrap_or_default(), + file.decoded_len() + ); + } + } +} - assert_eq!( - nested_message.subject().unwrap(), - "Exporting my book about coffee tables" - ); +fn display(mailbox: Mailbox<'_>) -> String { + let address = mailbox.address().unwrap_or_default(); + match mailbox.name() { + Some(name) => format!("{name} <{address}>"), + None => address.to_string(), + } +} - // Handles UTF-* as well as many legacy encodings - assert_eq!( - nested_message.body_text(0).unwrap(), - "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!" +fn describe(part: MessagePart<'_>) { + let content_type = part + .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(), - "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!" - ); - - 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()); } diff --git a/examples/message_write_attachments.rs b/examples/message_write_attachments.rs index eb143f6..ab34c0c 100644 --- a/examples/message_write_attachments.rs +++ b/examples/message_write_attachments.rs @@ -4,10 +4,13 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ -use mail_parser::*; +use mail_parser::{MessageParser, MessagePart}; +use std::{ + env, fs, io, + path::{Path, PathBuf}, +}; -fn main() { - let input = br#"From: Art Vandelay (Vandelay Industries) +const MESSAGE: &[u8] = br#"From: Art Vandelay (Vandelay Industries) To: "Colleagues": "James Smythe" ; Friends: jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= ; Date: Sat, 20 Nov 2021 14:22:01 -0800 @@ -24,7 +27,7 @@ cmcmRxdW87LDwvcD48cD5idXQgdGhlbiBJIHRob3VnaHQsIHdoeSBub3QgZG8gYm90aD8 gJiN4MjYzQTs8L3A+PC9odG1sPg== --festivus 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 From: "Cosmo Kramer" @@ -50,19 +53,41 @@ R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 --festivus-- "#; - write_attachments(&MessageParser::default().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) { - for attachment in message.attachments() { - if !attachment.is_message() { - std::fs::write( - attachment.attachment_name().unwrap_or("Untitled"), - attachment.contents(), - ) - .unwrap(); - } else { - write_attachments(attachment.message().unwrap()); - } - } +fn file_name(part: MessagePart<'_>) -> PathBuf { + let name = part + .attachment_name() + .map(str::to_string) + .or_else(|| { + part.nested() + .and_then(|nested| nested.subject()) + .map(|subject| format!("{subject}.eml")) + }) + .unwrap_or_default(); + Path::new(&name).file_name().map_or_else( + || PathBuf::from(format!("part-{}", part.id())), + PathBuf::from, + ) } diff --git a/flamegraph.sh b/flamegraph.sh deleted file mode 100755 index 7f61c57..0000000 --- a/flamegraph.sh +++ /dev/null @@ -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 diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 64b211b..f8e4e91 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -4,36 +4,78 @@ version = 4 [[package]] name = "arbitrary" -version = "1.0.2" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "577b08a4acd7b99869f863c50011b01eb73424ccc798ecd996f2e24817adfca7" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" [[package]] name = "cc" -version = "1.0.71" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79c2681d6594606957bbb8631c4b90a7fcaaa72cdb714743a437b156d6a7eedd" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] [[package]] name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "core_detect" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "encodify" +version = "1.0.0" +dependencies = [ + "memchr", + "simdutf8", +] [[package]] name = "encoding_rs" -version = "0.8.29" +version = "0.8.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a74ea89a0a1b98f6332de42c95baff457ada66d1cb4030f9ff151b2041a1c746" +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.2.6" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f208758247e68e239acaa059e72e4ce1f30f2a4b6523f19c1b923d25b7e9cceb" +checksum = "66f5a65bf7824ada2de4a2cf9fa0981dabffc5392bb8550767c3c3d71ed52e4d" dependencies = [ "proc-macro2", "quote", @@ -41,61 +83,168 @@ dependencies = [ ] [[package]] -name = "libfuzzer-sys" -version = "0.4.2" +name = "itoa" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36a9a84a6e8b55dfefb04235e55edb2b9a2a18488fcae777a6bdaa6f06f1deb3" +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 = [ "arbitrary", "cc", - "once_cell", ] [[package]] name = "mail-parser" -version = "0.10.2" +version = "1.0.0" dependencies = [ + "encodify", "encoding_rs", "hashify", + "memchr", + "serde", + "simdutf8", ] [[package]] name = "mail-parser-fuzz" version = "0.0.0" dependencies = [ + "encodify", "libfuzzer-sys", "mail-parser", + "memchr", + "serde_json", ] [[package]] -name = "once_cell" -version = "1.8.0" +name = "memchr" +version = "2.8.3" 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.93" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.38" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] [[package]] -name = "syn" -version = "2.0.98" +name = "r-efi" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" +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", @@ -104,6 +253,12 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.17" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00e2473a93778eb0bad35909dff6a10d28e63f792f16ed15e404fca9d5eeedbe" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 055c34e..cf2e5cf 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -1,25 +1,78 @@ [package] name = "mail-parser-fuzz" version = "0.0.0" -authors = ["Automatically generated"] publish = false -edition = "2018" +edition = "2024" [package.metadata] cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" +memchr = "2.8" +serde_json = "1.0" +encodify = { path = "../../encodify" } +mail-parser = { path = "..", features = ["serde"] } -[dependencies.mail-parser] -path = ".." +[features] +default = ["full_encoding"] +full_encoding = ["mail-parser/full_encoding"] -# Prevent this from interfering with workspaces [workspace] members = ["."] -[[bin]] -name = "mail_parser" -path = "fuzz_targets/mail_parser.rs" +[lib] +path = "src/lib.rs" test = 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 diff --git a/fuzz/fuzz_targets/charsets.rs b/fuzz/fuzz_targets/charsets.rs new file mode 100644 index 0000000..e58a4cf --- /dev/null +++ b/fuzz/fuzz_targets/charsets.rs @@ -0,0 +1,8 @@ +#![no_main] + +use libfuzzer_sys::fuzz_target; +use mail_parser_fuzz::charsets; + +fuzz_target!(|data: &[u8]| { + charsets::check(data); +}); diff --git a/fuzz/fuzz_targets/fields.rs b/fuzz/fuzz_targets/fields.rs new file mode 100644 index 0000000..eba2e1c --- /dev/null +++ b/fuzz/fuzz_targets/fields.rs @@ -0,0 +1,8 @@ +#![no_main] + +use libfuzzer_sys::fuzz_target; +use mail_parser_fuzz::fields; + +fuzz_target!(|data: &[u8]| { + fields::check(data); +}); diff --git a/fuzz/fuzz_targets/kernels.rs b/fuzz/fuzz_targets/kernels.rs new file mode 100644 index 0000000..4b202f3 --- /dev/null +++ b/fuzz/fuzz_targets/kernels.rs @@ -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); +}); diff --git a/fuzz/fuzz_targets/limits.rs b/fuzz/fuzz_targets/limits.rs new file mode 100644 index 0000000..702e4eb --- /dev/null +++ b/fuzz/fuzz_targets/limits.rs @@ -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)); +}); diff --git a/fuzz/fuzz_targets/mail_parser.rs b/fuzz/fuzz_targets/mail_parser.rs deleted file mode 100644 index c575251..0000000 --- a/fuzz/fuzz_targets/mail_parser.rs +++ /dev/null @@ -1,76 +0,0 @@ -#![no_main] -use libfuzzer_sys::fuzz_target; - -use mail_parser::{ - decoders::{ - base64::base64_decode, - charsets::map::charset_decoder, - 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, MessageParser, -}; - -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(&MessageParser::default(), &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); - - // Fuzz the entire library - MessageParser::default().parse(data); - } -}); - -fn into_alphabet(data: &[u8], alphabet: &[u8]) -> Vec { - data.iter() - .map(|&byte| alphabet[byte as usize % alphabet.len()]) - .collect() -} diff --git a/fuzz/fuzz_targets/mbox.rs b/fuzz/fuzz_targets/mbox.rs new file mode 100644 index 0000000..6286a53 --- /dev/null +++ b/fuzz/fuzz_targets/mbox.rs @@ -0,0 +1,8 @@ +#![no_main] + +use libfuzzer_sys::fuzz_target; +use mail_parser_fuzz::mbox; + +fuzz_target!(|data: &[u8]| { + mbox::check(data); +}); diff --git a/fuzz/fuzz_targets/parse.rs b/fuzz/fuzz_targets/parse.rs new file mode 100644 index 0000000..8d25b77 --- /dev/null +++ b/fuzz/fuzz_targets/parse.rs @@ -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 = LazyLock::new(MessageParser::new); + +fuzz_target!(|data: &[u8]| { + walk::run(&PARSER, data, None); +}); diff --git a/fuzz/mime.dict b/fuzz/mime.dict new file mode 100644 index 0000000..e8a02bd --- /dev/null +++ b/fuzz/mime.dict @@ -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\" " +"" +"a@b.c" +"mailto:" +"Re: " +"Fwd: " +"Fw: " +"[list] " +"(fwd)" +"" +"" +"" +"
" +"
" +"

" +"

" +"" +"" +"", - "
World
" - ); - let output = html_to_text(input); - assert!(!output.contains("body{color:red}")); - assert!(!output.contains("alert('x')")); - assert!(output.contains("Hello")); - assert!(output.contains("World")); - } - - #[test] - fn html_to_text_removes_template_content() { - let input = concat!( - "
Hello
", - "", - "
World
" - ); - let output = html_to_text(input); - assert!(!output.contains("Hidden")); - assert!(!output.contains(".x{}")); - assert!(output.contains("Hello")); - assert!(output.contains("World")); - } -} diff --git a/src/decoders/html/meta.rs b/src/decoders/html/meta.rs new file mode 100644 index 0000000..5f146af --- /dev/null +++ b/src/decoders/html/meta.rs @@ -0,0 +1,135 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use std::{borrow::Cow, ops::Range}; + +use memchr::{memchr, memchr_iter, memchr2_iter}; + +const UTF_8: &str = "utf-8"; +const BODY: &[u8] = b"body"; +const META: &[u8] = b"meta"; +const CHARSET: &[u8] = b"charset"; +const QUOTE_ENTITY: &[u8] = b"""; + +/// Rewrites the charset of the `` and `` declarations before `caf\u{e9}"#; +/// assert_eq!( +/// strip_charset_meta(html), +/// r#"caf\u{e9}"# +/// ); +/// ``` +pub fn strip_charset_meta(html: &str) -> Cow<'_, str> { + let bytes = html.as_bytes(); + let mut result: Option = None; + let mut copied = 0; + for tag_start in memchr_iter(b'<', bytes) { + let name = bytes.get(tag_start + 1..).unwrap_or_default(); + if starts_with_ignore_case(name, BODY) { + break; + } + if !is_meta_tag(name) { + continue; + } + let tag_end = memchr(b'>', name).map_or(bytes.len(), |end| tag_start + 1 + end); + for value in charset_values(bytes, tag_start..tag_end) { + if value.start < copied { + continue; + } + let out = result.get_or_insert_with(|| String::with_capacity(html.len())); + out.push_str(html.get(copied..value.start).unwrap_or_default()); + out.push_str(UTF_8); + copied = value.end; + } + } + match result { + Some(mut out) => { + out.push_str(html.get(copied..).unwrap_or_default()); + Cow::Owned(out) + } + None => Cow::Borrowed(html), + } +} + +fn is_meta_tag(name: &[u8]) -> bool { + starts_with_ignore_case(name, META) + && name + .get(META.len()) + .is_none_or(|&byte| byte.is_ascii_whitespace() || byte == b'/' || byte == b'>') +} + +fn charset_values(bytes: &[u8], tag: Range) -> impl Iterator> { + let tag_bytes = bytes.get(tag.clone()).unwrap_or_default(); + memchr2_iter(b'c', b'C', tag_bytes).filter_map(move |offset| { + let name_end = offset + CHARSET.len(); + if !tag_bytes + .get(offset..name_end) + .is_some_and(|name| name.eq_ignore_ascii_case(CHARSET)) + { + return None; + } + let value = value_range(tag_bytes, name_end)?; + let text = tag_bytes.get(value.clone())?; + (!text.is_empty() + && !text.eq_ignore_ascii_case(b"utf-8") + && !text.eq_ignore_ascii_case(b"utf8")) + .then_some(tag.start + value.start..tag.start + value.end) + }) +} + +fn value_range(tag: &[u8], name_end: usize) -> Option> { + let after_name = skip_whitespace(tag, name_end); + let rest = tag.get(after_name..)?.strip_prefix(b"=")?; + let start = skip_whitespace(tag, tag.len() - rest.len()); + let rest = tag.get(start..)?; + Some(match rest { + [quote @ (b'"' | b'\''), value @ ..] => { + start + 1..start + 1 + memchr(*quote, value).unwrap_or(value.len()) + } + _ if starts_with_ignore_case(rest, QUOTE_ENTITY) => { + let value = rest.get(QUOTE_ENTITY.len()..).unwrap_or_default(); + let len = value + .iter() + .position(|&byte| byte == b'&') + .filter(|&end| { + starts_with_ignore_case(value.get(end..).unwrap_or_default(), QUOTE_ENTITY) + }) + .unwrap_or_else(|| unquoted_len(value)); + start + QUOTE_ENTITY.len()..start + QUOTE_ENTITY.len() + len + } + _ => start..start + unquoted_len(rest), + }) +} + +fn unquoted_len(value: &[u8]) -> usize { + value + .iter() + .position(|&byte| { + byte.is_ascii_whitespace() || matches!(byte, b';' | b'"' | b'\'' | b'>' | b'/' | b'&') + }) + .unwrap_or(value.len()) +} + +fn skip_whitespace(bytes: &[u8], from: usize) -> usize { + from + bytes + .get(from..) + .unwrap_or_default() + .iter() + .take_while(|byte| byte.is_ascii_whitespace()) + .count() +} + +fn starts_with_ignore_case(bytes: &[u8], prefix: &[u8]) -> bool { + bytes + .get(..prefix.len()) + .is_some_and(|start| start.eq_ignore_ascii_case(prefix)) +} diff --git a/src/decoders/html/mod.rs b/src/decoders/html/mod.rs new file mode 100644 index 0000000..0f2455a --- /dev/null +++ b/src/decoders/html/mod.rs @@ -0,0 +1,266 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +//! HTML to text, text to HTML, and HTML charset declarations. + +mod entities; +mod meta; +mod text; + +use std::char::REPLACEMENT_CHARACTER; + +use memchr::{memchr_iter, memchr2, memchr3}; + +pub use meta::strip_charset_meta; +pub(crate) use text::html_to_text_prefix; + +const HTML_PREFIX: &str = ""; +const HTML_SUFFIX: &str = ""; +const LINE_BREAK: &str = "
"; + +/// Converts HTML to plain text: tags are removed, entities decoded and +/// white space collapsed; `
` and `

` become line breaks; the content +/// of ``, `", + "this is the actual text" + ), + "this is the actual text", + ), + ( + " < p > hello < / p > < p > world < / p > !!! < br > ", + "hello\nworld\n!!!\n", + ), + ( + "

please unsubscribe here.

", + "please unsubscribe here.\n", + ), + ]; + + for input in inputs { + assert_eq!(html_to_text(input.0), input.1, "Failed for '{:?}'", input.0); + } + } + + #[test] + fn convert_html_entity() { + let inputs = [ + ("<", "<"), + (" ", " "), + (" ", " "), + (" ", "\u{a0}"), + ("∳", "∳"), + ("↷", "↷"), + ("→", "→"), + ("�", "�"), + ("&hmmm", "&hmmm"), + ]; + + for input in inputs { + let mut result = String::with_capacity(input.0.len()); + add_html_token(&mut result, input.0.as_bytes(), false); + assert_eq!(result, input.1, "Failed for '{:?}", input.0); + } + } + + #[test] + fn html_to_text_removes_style_content() { + let input = "
Hello
"; + let output = html_to_text(input); + assert!(!output.contains("body{color:red}")); + assert!(output.contains("Hello")); + } + + #[test] + fn html_to_text_removes_script_content() { + let input = concat!( + "", + "
Hello
", + "", + "
World
" + ); + let output = html_to_text(input); + assert!(!output.contains("body{color:red}")); + assert!(!output.contains("alert('x')")); + assert!(output.contains("Hello")); + assert!(output.contains("World")); + } + + #[test] + fn html_to_text_removes_template_content() { + let input = concat!( + "
Hello
", + "", + "
World
" + ); + let output = html_to_text(input); + assert!(!output.contains("Hidden")); + assert!(!output.contains(".x{}")); + assert!(output.contains("Hello")); + assert!(output.contains("World")); + } + + #[test] + fn charset_meta_is_rewritten() { + for (html, expected) in [ + ( + "\u{2014}", + "\u{2014}", + ), + ( + "\u{2014}", + "\u{2014}", + ), + ( + "\u{2014}", + "\u{2014}", + ), + ( + "\u{2014}", + "\u{2014}", + ), + ] { + assert_eq!(strip_charset_meta(html), expected); + } + for html in [ + "x", + "", + "plain text", + ] { + assert!(matches!(strip_charset_meta(html), Cow::Borrowed(_))); + } + } +} diff --git a/src/decoders/html/text.rs b/src/decoders/html/text.rs new file mode 100644 index 0000000..b1df415 --- /dev/null +++ b/src/decoders/html/text.rs @@ -0,0 +1,316 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use memchr::{memchr, memchr2}; + +use super::decode_entity; + +const COMMENT_OPEN: &[u8] = b"--"; +const COMMENT_CLOSE_DASHES: usize = 2; +const NAMED_TAG: usize = 1; + +static TEXT_DELIMITERS: [bool; 256] = delimiters(b"<&; \t\r\n"); +static TAG_DELIMITERS: [bool; 256] = delimiters(b"<>/ \t\r\n"); + +const fn delimiters(bytes: &[u8]) -> [bool; 256] { + let mut table = [false; 256]; + let mut index = 0; + while index < bytes.len() { + table[bytes[index] as usize] = true; + index += 1; + } + table +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + Complete, + Preview { limit: usize }, +} + +pub(super) fn html_to_text(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + convert(input, &mut out, Mode::Complete); + out +} + +pub(crate) fn html_to_text_prefix(input: &str, limit: usize, out: &mut String) -> bool { + convert(input, out, Mode::Preview { limit }) +} + +fn convert(input: &str, out: &mut String, mode: Mode) -> bool { + let bytes = input.as_bytes(); + let mut sink = Sink { + input, + bytes, + out, + mode, + pending_start: 0, + pending_end: 0, + }; + let mut in_tag = false; + let mut in_head = false; + let mut in_style = false; + let mut in_script = false; + let mut in_template = false; + let mut is_token_start = true; + let mut is_after_space = false; + let mut is_tag_close = false; + let mut is_new_line = true; + let mut token_start = 0; + let mut token_end = 0; + let mut tag_token_pos = 0; + let mut pos = 0; + + loop { + let hidden = in_head || in_style || in_script || in_template; + if in_tag { + if tag_token_pos > NAMED_TAG { + pos = find(bytes, pos, |rest| memchr2(b'<', b'>', rest)); + } else if !is_token_start { + let run = run_until(bytes, pos, &TAG_DELIMITERS); + if run > 0 { + pos += run; + token_end = pos - 1; + } + } + } else if hidden { + pos = find(bytes, pos, |rest| memchr(b'<', rest)); + } else { + let run = run_until(bytes, pos, &TEXT_DELIMITERS); + if run > 0 { + if is_token_start { + token_start = pos; + is_token_start = false; + } + pos += run; + token_end = pos - 1; + } + } + let Some(&ch) = bytes.get(pos) else { + break; + }; + match ch { + b'<' => { + if !in_tag && !hidden && !is_token_start { + if sink.emit(token_start, token_end + 1, is_after_space) { + return true; + } + is_after_space = false; + } + tag_token_pos = 0; + in_tag = true; + is_token_start = true; + is_tag_close = false; + pos += 1; + continue; + } + b'>' if in_tag => { + if tag_token_pos == NAMED_TAG + && let Some(tag) = bytes.get(token_start..token_end + 1) + { + if tag.eq_ignore_ascii_case(b"br") + || (is_tag_close && tag.eq_ignore_ascii_case(b"p")) + { + if sink.newline() { + return true; + } + is_after_space = false; + is_new_line = true; + } else if tag.eq_ignore_ascii_case(b"head") { + in_head = !is_tag_close; + } else if tag.eq_ignore_ascii_case(b"style") { + in_style = !is_tag_close; + } else if tag.eq_ignore_ascii_case(b"script") { + in_script = !is_tag_close; + } else if tag.eq_ignore_ascii_case(b"template") { + in_template = !is_tag_close; + } + } + in_tag = false; + is_token_start = true; + pos += 1; + continue; + } + b'/' if in_tag => { + if tag_token_pos == 0 { + is_tag_close = true; + } + pos += 1; + continue; + } + b'!' if in_tag + && tag_token_pos == 0 + && bytes.get(pos + 1..pos + 1 + COMMENT_OPEN.len()) == Some(COMMENT_OPEN) => + { + let Some(close) = comment_close(bytes, pos + 1) else { + break; + }; + in_tag = false; + is_token_start = true; + pos = close + 1; + continue; + } + b' ' | b'\t' | b'\r' | b'\n' => { + if !in_tag && !hidden { + if !is_token_start { + if sink.emit(token_start, token_end + 1, is_after_space && !is_new_line) { + return true; + } + is_new_line = false; + } + is_after_space = true; + } + is_token_start = true; + pos += 1; + continue; + } + b'&' if !in_tag && !is_token_start && !in_head => { + if in_style || in_script || in_template { + pos += 1; + continue; + } + if sink.emit(token_start, token_end + 1, is_after_space && !is_new_line) { + return true; + } + is_new_line = false; + is_token_start = true; + is_after_space = false; + } + b';' if !in_tag && !is_token_start && !in_head => { + if in_style || in_script || in_template { + pos += 1; + continue; + } + if sink.emit(token_start, pos + 1, is_after_space && !is_new_line) { + return true; + } + is_token_start = true; + is_after_space = false; + is_new_line = false; + pos += 1; + continue; + } + _ => (), + } + if is_token_start { + token_start = pos; + is_token_start = false; + if in_tag { + tag_token_pos += 1; + } + } + token_end = pos; + pos += 1; + } + + if !in_tag && !is_token_start && !(in_head || in_style || in_script || in_template) { + sink.emit(token_start, token_end + 1, is_after_space && !is_new_line); + } + sink.flush(); + false +} + +fn find(bytes: &[u8], pos: usize, search: impl Fn(&[u8]) -> Option) -> usize { + bytes + .get(pos..) + .and_then(search) + .map_or(bytes.len(), |offset| pos + offset) +} + +fn run_until(bytes: &[u8], pos: usize, delimiters: &[bool; 256]) -> usize { + let rest = bytes.get(pos..).unwrap_or_default(); + rest.iter() + .position(|&byte| delimiters[usize::from(byte)]) + .unwrap_or(rest.len()) +} + +fn comment_close(bytes: &[u8], comment_start: usize) -> Option { + let mut pos = comment_start; + loop { + let close = pos + memchr(b'>', bytes.get(pos..)?)?; + let dashes = bytes + .get(comment_start..close) + .unwrap_or_default() + .iter() + .rev() + .take(COMMENT_CLOSE_DASHES + 1) + .take_while(|&&byte| byte == b'-') + .count(); + if dashes == COMMENT_CLOSE_DASHES { + return Some(close); + } + pos = close + 1; + } +} + +struct Sink<'x, 'o> { + input: &'x str, + bytes: &'x [u8], + out: &'o mut String, + mode: Mode, + pending_start: usize, + pending_end: usize, +} + +impl Sink<'_, '_> { + fn emit(&mut self, start: usize, end: usize, add_space: bool) -> bool { + let Some(token) = self.input.get(start..end) else { + return false; + }; + if let Some(ch) = decode_entity(token) { + self.flush(); + if add_space { + self.out.push(' '); + } + if ch != '\r' || self.mode == Mode::Complete { + self.out.push(ch); + } + return self.limit_reached(); + } + let span_start = match start.checked_sub(1) { + Some(space) if add_space && self.bytes.get(space) == Some(&b' ') => space, + _ if add_space => { + self.flush(); + self.out.push(' '); + start + } + _ => start, + }; + if self.pending_start < self.pending_end && self.pending_end == span_start { + self.pending_end = end; + } else { + self.flush(); + self.pending_start = span_start; + self.pending_end = end; + } + self.limit_reached() + } + + fn newline(&mut self) -> bool { + self.flush(); + self.out.push('\n'); + self.limit_reached() + } + + fn limit_reached(&mut self) -> bool { + let Mode::Preview { limit } = self.mode else { + return false; + }; + let reached = self.out.len() + (self.pending_end - self.pending_start) > limit; + if reached { + self.flush(); + } + reached + } + + fn flush(&mut self) { + if let Some(pending) = self.input.get(self.pending_start..self.pending_end) { + self.out.push_str(pending); + } + self.pending_start = self.pending_end; + } +} diff --git a/src/decoders/mod.rs b/src/decoders/mod.rs index e5f8a28..36df74a 100644 --- a/src/decoders/mod.rs +++ b/src/decoders/mod.rs @@ -4,16 +4,310 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ +//! Decoders the parser uses that are also useful on their own: charset +//! conversion, HTML to text and text to HTML, and body previews. Transfer +//! encodings (base64, quoted-printable, hex) are decoded by encodify; use +//! it directly for those. + +pub mod charsets; +pub mod html; +mod prefix; +pub mod preview; + +use crate::Encoding; +use charsets::Charset; +use encodify::{base64, qp}; use std::borrow::Cow; -use crate::parsers::MessageStream; +pub(crate) use prefix::{Limit, TextPrefix, text_prefix}; -pub mod base64; -pub mod charsets; -pub mod encoded_word; -pub mod hex; -pub mod html; -pub mod quoted_printable; +const KNOWN_TRANSFER_ENCODINGS: [&[u8]; 5] = + [b"7bit", b"8bit", b"binary", b"base64", b"quoted-printable"]; -pub type DecodeFnc<'x> = fn(&mut MessageStream<'x>, &[u8]) -> (usize, Cow<'x, [u8]>); -pub type DecodeWordFnc<'x> = fn(&mut MessageStream<'x>) -> Option>; +pub(crate) fn transfer_decode(bytes: &[u8], encoding: Encoding) -> Cow<'_, [u8]> { + match encoding { + Encoding::None => Cow::Borrowed(bytes), + Encoding::QuotedPrintable => qp::BODY.decode(bytes).unwrap_or(Cow::Borrowed(bytes)), + Encoding::Base64 => { + let mut out = Vec::new(); + transfer_decode_append(bytes, encoding, &mut out); + Cow::Owned(out) + } + } +} + +pub(crate) fn transfer_decode_checked(bytes: &[u8], encoding: Encoding) -> (Cow<'_, [u8]>, bool) { + match encoding { + Encoding::None => (Cow::Borrowed(bytes), false), + Encoding::QuotedPrintable => match qp::BODY.strict().decode(bytes) { + Ok(decoded) => (decoded, false), + Err(_) => (transfer_decode(bytes, encoding), true), + }, + Encoding::Base64 => { + let mut out = Vec::new(); + let malformed = base64::MIME.decode_append(bytes, &mut out).is_err(); + if malformed { + base64_tolerant(bytes, &mut out); + } + (Cow::Owned(out), malformed) + } + } +} + +pub(crate) fn is_known_transfer_encoding(value: &[u8]) -> bool { + let token = value + .split(|&byte| byte == b'(') + .next() + .unwrap_or_default() + .trim_ascii(); + KNOWN_TRANSFER_ENCODINGS + .iter() + .any(|known| token.eq_ignore_ascii_case(known)) +} + +pub(crate) fn transfer_decode_append(bytes: &[u8], encoding: Encoding, out: &mut Vec) { + match encoding { + Encoding::None => out.extend_from_slice(bytes), + Encoding::QuotedPrintable => { + if qp::BODY.decode_append(bytes, out).is_err() { + out.extend_from_slice(bytes); + } + } + Encoding::Base64 => { + if base64::MIME.decode_append(bytes, out).is_err() { + base64_tolerant(bytes, out); + } + } + } +} + +pub(crate) fn transfer_decoded_len(bytes: &[u8], encoding: Encoding) -> usize { + match encoding { + Encoding::None => bytes.len(), + Encoding::Base64 => base64::MIME.decoded_len(bytes).unwrap_or_else(|_| { + let mut out = Vec::new(); + base64_tolerant(bytes, &mut out); + out.len() + }), + Encoding::QuotedPrintable => qp::BODY.decoded_len(bytes).unwrap_or(bytes.len()), + } +} + +fn base64_tolerant(rest: &[u8], out: &mut Vec) { + base64_feed(rest, out).finish(out); +} + +fn base64_feed(mut rest: &[u8], out: &mut Vec) -> base64::Decoder { + let mut decoder = base64::MIME.decoder(); + loop { + rest = rest + .get(decoder.decode_symbols(rest, out)..) + .unwrap_or_default(); + match rest.split_first() { + None => return decoder, + Some((b'=', tail)) => { + decoder.pad(out); + rest = tail; + } + Some((_, tail)) => rest = tail, + } + } +} + +pub(crate) fn charset(label: Option<&str>) -> Charset { + label + .and_then(|label| Charset::from_label(label.as_bytes())) + .unwrap_or_default() +} + +pub(crate) fn rewrite<'x>( + text: Cow<'x, str>, + rewrite: impl for<'a> FnOnce(&'a str) -> Cow<'a, str>, +) -> Cow<'x, str> { + match text { + Cow::Borrowed(text) => rewrite(text), + Cow::Owned(text) => { + let rewritten = match rewrite(&text) { + Cow::Owned(rewritten) => Some(rewritten), + Cow::Borrowed(same) if same.len() == text.len() => None, + Cow::Borrowed(other) => Some(other.to_owned()), + }; + Cow::Owned(rewritten.unwrap_or(text)) + } + } +} + +pub(crate) fn to_text<'x>(bytes: Cow<'x, [u8]>, charset: Charset) -> Cow<'x, str> { + match bytes { + Cow::Borrowed(bytes) => charset.decode(bytes), + Cow::Owned(bytes) => Cow::Owned(charset.decode_owned(bytes)), + } +} + +pub(crate) fn to_text_checked<'x>(bytes: Cow<'x, [u8]>, charset: Charset) -> (Cow<'x, str>, bool) { + match bytes { + Cow::Borrowed(bytes) => charset.decode_checked(bytes), + Cow::Owned(bytes) => { + let (text, malformed) = charset.decode_owned_checked(bytes); + (Cow::Owned(text), malformed) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scan::tests::Rng; + + #[test] + fn qp_matches_codec() { + let alphabet = b"ab \t\r\n=\xc3\xa9"; + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for _ in 0..20_000 { + let len = rng.below(24); + let input: Vec = (0..len) + .map(|_| { + alphabet + .get(rng.below(alphabet.len())) + .copied() + .unwrap_or(b'a') + }) + .collect(); + let mut decoded = Vec::new(); + qp::BODY + .decode_append(&input, &mut decoded) + .expect("never fails"); + let borrowed = transfer_decode(&input, Encoding::QuotedPrintable); + assert_eq!(borrowed.as_ref(), decoded.as_slice(), "{input:?}"); + if matches!(borrowed, Cow::Borrowed(_)) { + assert_eq!(decoded, input); + } + assert_eq!( + transfer_decoded_len(&input, Encoding::QuotedPrintable), + decoded.len() + ); + } + assert!(matches!( + transfer_decode(b"plain text\r\nline two\nend", Encoding::QuotedPrintable), + Cow::Borrowed(_) + )); + assert!(matches!( + transfer_decode(b"trailing \r\n", Encoding::QuotedPrintable), + Cow::Owned(_) + )); + } + + #[test] + fn base64_best_effort() { + assert_eq!( + transfer_decode(b"SGVs\r\nbG8=", Encoding::Base64).as_ref(), + b"Hello" + ); + assert_eq!( + transfer_decode(b"SGVs-bG8=", Encoding::Base64).as_ref(), + b"Hello" + ); + assert_eq!( + transfer_decode(b"VGVzdA", Encoding::Base64).as_ref(), + b"Test" + ); + assert_eq!(transfer_decoded_len(b"SGVs-bG8=", Encoding::Base64), 5); + assert_eq!(transfer_decoded_len(b"SGVsbG8=", Encoding::Base64), 5); + } + + #[test] + fn checked_transfer_decoding() { + let alphabet = b"ab \t\r\n=\xc3\xa9AZ09+/-"; + let mut rng = Rng(0x7ab5_c0de_1234_9876); + for _ in 0..20_000 { + let len = rng.below(24); + let input: Vec = (0..len) + .map(|_| { + alphabet + .get(rng.below(alphabet.len())) + .copied() + .unwrap_or(b'a') + }) + .collect(); + for encoding in [Encoding::None, Encoding::QuotedPrintable, Encoding::Base64] { + let (checked, malformed) = transfer_decode_checked(&input, encoding); + assert_eq!(checked, transfer_decode(&input, encoding), "{input:?}"); + let expected = match encoding { + Encoding::None => false, + Encoding::QuotedPrintable => qp::BODY.strict().decoded_len(&input).is_err(), + Encoding::Base64 => base64::MIME.decoded_len(&input).is_err(), + }; + assert_eq!(malformed, expected, "{encoding:?} {input:?}"); + } + } + for (input, encoding, decoded, malformed) in [ + (&b"SGVs\r\nbG8="[..], Encoding::Base64, &b"Hello"[..], false), + (b"SGVs-bG8=", Encoding::Base64, b"Hello", true), + (b"VGVzdA", Encoding::Base64, b"Test", false), + ( + b"caf=C3=A9", + Encoding::QuotedPrintable, + b"caf\xc3\xa9", + false, + ), + ( + b"soft=\r\nbreak", + Encoding::QuotedPrintable, + b"softbreak", + false, + ), + (b"a=ZZb", Encoding::QuotedPrintable, b"a=ZZb", true), + (b"end=4", Encoding::QuotedPrintable, b"end=4", true), + (b"as is=", Encoding::None, b"as is=", false), + ] { + let (checked, problem) = transfer_decode_checked(input, encoding); + assert_eq!( + (checked.as_ref(), problem), + (decoded, malformed), + "{input:?}" + ); + } + } + + #[test] + fn known_transfer_encodings() { + for value in [ + &b"7bit"[..], + b" 8BIT\r\n", + b"binary (comment)", + b"\r\n base64\r\n", + b" Quoted-Printable", + ] { + assert!(is_known_transfer_encoding(value), "{value:?}"); + } + for value in [ + &b"x-uuencode"[..], + b"", + b" base64;", + b"7-bit", + b"\"base64\"", + ] { + assert!(!is_known_transfer_encoding(value), "{value:?}"); + } + } + + #[test] + fn text_conversion() { + assert!(matches!( + to_text(Cow::Borrowed(b"caf\xc3\xa9"), charset(Some("utf-8"))), + Cow::Borrowed("café") + )); + assert_eq!( + to_text(Cow::Borrowed(b"caf\xe9"), charset(Some("iso-8859-1"))), + "café" + ); + assert_eq!( + to_text(Cow::Owned(b"caf\xe9".to_vec()), charset(None)), + "caf\u{fffd}" + ); + assert_eq!( + to_text(Cow::Owned(b"caf\xe9".to_vec()), charset(Some("x-unknown"))), + "caf\u{fffd}" + ); + } +} diff --git a/src/decoders/prefix.rs b/src/decoders/prefix.rs new file mode 100644 index 0000000..e0901ae --- /dev/null +++ b/src/decoders/prefix.rs @@ -0,0 +1,117 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{base64_feed, charsets::Charset, to_text, transfer_decode}; +use crate::Encoding; +use encodify::qp; +use memchr::memrchr; +use std::borrow::Cow; + +const MAX_BYTES_PER_CHAR: usize = 4; +const RAW_BYTES_PER_TEXT_BYTE: usize = 2; +const INITIAL_SLACK: usize = 256; +const GROWTH: usize = 4; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Limit { + Chars(usize), + Bytes(usize), +} + +pub(crate) struct TextPrefix<'x> { + pub(crate) text: Cow<'x, str>, + pub(crate) complete: bool, +} + +pub(crate) fn text_prefix( + raw: &[u8], + encoding: Encoding, + charset: Charset, + limit: Limit, +) -> TextPrefix<'_> { + let mut window = match limit { + Limit::Chars(chars) => chars.saturating_mul(MAX_BYTES_PER_CHAR), + Limit::Bytes(bytes) => bytes.saturating_mul(RAW_BYTES_PER_TEXT_BYTE), + } + .saturating_add(INITIAL_SLACK); + loop { + let whole = window >= raw.len(); + let text = if whole { + to_text(transfer_decode(raw, encoding), charset) + } else { + let prefix = raw.get(..window).unwrap_or(raw); + decode_prefix(transfer_prefix(prefix, encoding), charset) + }; + match limit { + Limit::Chars(chars) => { + if let Some(end) = char_start(&text, chars) { + return TextPrefix { + text: truncate(text, end), + complete: false, + }; + } + } + Limit::Bytes(bytes) if text.len() > bytes => { + return TextPrefix { + text, + complete: whole, + }; + } + Limit::Bytes(_) => (), + } + if whole { + return TextPrefix { + text, + complete: true, + }; + } + window = window.saturating_mul(GROWTH); + } +} + +fn char_start(text: &str, index: usize) -> Option { + if index >= text.len() { + None + } else if text.as_bytes().get(..index).is_some_and(<[u8]>::is_ascii) { + Some(index) + } else { + text.char_indices().nth(index).map(|(start, _)| start) + } +} + +fn transfer_prefix(raw: &[u8], encoding: Encoding) -> Cow<'_, [u8]> { + match encoding { + Encoding::None => Cow::Borrowed(raw), + Encoding::QuotedPrintable => { + let lines = raw + .get(..memrchr(b'\n', raw).map_or(0, |end| end + 1)) + .unwrap_or_default(); + qp::BODY.decode(lines).unwrap_or(Cow::Borrowed(lines)) + } + Encoding::Base64 => { + let mut out = Vec::with_capacity(raw.len() / 4 * 3 + 3); + base64_feed(raw, &mut out); + Cow::Owned(out) + } + } +} + +fn decode_prefix(bytes: Cow<'_, [u8]>, charset: Charset) -> Cow<'_, str> { + match bytes { + Cow::Borrowed(bytes) => charset.decode_prefix(bytes), + Cow::Owned(bytes) => Cow::Owned(charset.decode_prefix(&bytes).into_owned()), + } +} + +fn truncate(text: Cow<'_, str>, end: usize) -> Cow<'_, str> { + match text { + Cow::Borrowed(text) => Cow::Borrowed(text.get(..end).unwrap_or(text)), + Cow::Owned(mut text) => { + text.truncate(end); + Cow::Owned(text) + } + } +} diff --git a/src/decoders/preview.rs b/src/decoders/preview.rs new file mode 100644 index 0000000..db4c4cb --- /dev/null +++ b/src/decoders/preview.rs @@ -0,0 +1,308 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +//! Previews and truncation of text and HTML bodies. + +use std::borrow::Cow; + +use memchr::memchr; + +use super::html::html_to_text_prefix; + +const ELLIPSIS: &str = "..."; +const MIN_LEN_WITH_ELLIPSIS: usize = 7; +const COMMENT_OPEN: &[u8] = b"!--"; +const COMMENT_CLOSE: &[u8] = b"--"; +const LOOKAHEAD: usize = 4; +const PREVIEW_SLACK: usize = 64; + +/// At most `max_len` bytes of `text`, carriage returns removed. Longer +/// text is cut at a character boundary and, when `max_len` is 7 or more, +/// ends with `...` (counted in `max_len`). Borrowed when the text fits and +/// has no carriage return. +/// +/// ``` +/// use mail_parser::preview_text; +/// +/// assert_eq!(preview_text("Hello,\r\nworld", 20), "Hello,\nworld"); +/// assert_eq!(preview_text("Hello, world", 8), "Hello..."); +/// ``` +pub fn preview_text(text: &str, max_len: usize) -> Cow<'_, str> { + match strip_cr_prefix(text, max_len.saturating_add(1)) { + Stripped::Complete(text) if text.len() <= max_len => text, + Stripped::Complete(text) | Stripped::Prefix(text) => Cow::Owned(match text { + Cow::Borrowed(text) => truncate_chars(text, max_len), + Cow::Owned(text) => truncate_owned(text, max_len), + }), + } +} + +/// A text preview of an HTML document: [`crate::html_to_text`] of the +/// document cut like [`preview_text`]. Only the part of the document that +/// the preview needs is converted. +pub fn preview_html(html: &str, max_len: usize) -> String { + preview_html_prefix(html, max_len, true).unwrap_or_default() +} + +pub(crate) fn preview_html_prefix(html: &str, max_len: usize, complete: bool) -> Option { + let mut text = String::with_capacity(max_len.saturating_add(PREVIEW_SLACK).min(html.len())); + if !html_to_text_prefix(html, max_len, &mut text) && !complete { + return None; + } + if text.len() > max_len { + let (keep, ellipsis) = cut(max_len); + text.truncate(text.floor_char_boundary(keep)); + text.extend(ellipsis); + } + Some(text) +} + +/// Truncates text for display; the same as [`preview_text`]. +pub fn truncate_text(text: &str, max_len: usize) -> Cow<'_, str> { + preview_text(text, max_len) +} + +/// At most `max_len` bytes of an HTML document, carriage returns removed. +/// A longer document is cut before a tag rather than inside one and, when +/// `max_len` is 7 or more, ends with `...`. Borrowed when the document fits +/// and has no carriage return. +pub fn truncate_html(html: &str, max_len: usize) -> Cow<'_, str> { + match strip_cr_prefix(html, max_len.saturating_add(LOOKAHEAD)) { + Stripped::Complete(html) if html.len() <= max_len => html, + Stripped::Complete(html) | Stripped::Prefix(html) => { + Cow::Owned(truncate_markup(&html, max_len)) + } + } +} + +enum Stripped<'x> { + Complete(Cow<'x, str>), + Prefix(Cow<'x, str>), +} + +fn strip_cr_prefix(text: &str, needed: usize) -> Stripped<'_> { + let window = text.as_bytes().get(..needed).unwrap_or(text.as_bytes()); + if memchr(b'\r', window).is_none() { + return if text.len() < needed { + Stripped::Complete(Cow::Borrowed(text)) + } else { + Stripped::Prefix(Cow::Borrowed(text)) + }; + } + let mut stripped = String::with_capacity(needed.min(text.len())); + let mut rest = text; + while stripped.len() < needed { + let missing = needed - stripped.len(); + let window = rest.as_bytes().get(..missing).unwrap_or(rest.as_bytes()); + match memchr(b'\r', window) { + Some(cr) => { + let (segment, tail) = rest.split_at(cr); + stripped.push_str(segment); + rest = tail.get(1..).unwrap_or_default(); + } + None if rest.len() <= missing => { + stripped.push_str(rest); + return Stripped::Complete(Cow::Owned(stripped)); + } + None => { + stripped.push_str( + rest.get(..rest.ceil_char_boundary(missing)) + .unwrap_or_default(), + ); + return Stripped::Prefix(Cow::Owned(stripped)); + } + } + } + Stripped::Prefix(Cow::Owned(stripped)) +} + +fn cut(max_len: usize) -> (usize, Option<&'static str>) { + if max_len >= MIN_LEN_WITH_ELLIPSIS { + (max_len - ELLIPSIS.len(), Some(ELLIPSIS)) + } else { + (max_len, None) + } +} + +fn truncate_chars(text: &str, max_len: usize) -> String { + let (keep, ellipsis) = cut(max_len); + let kept = text + .get(..text.floor_char_boundary(keep)) + .unwrap_or_default(); + let mut result = String::with_capacity(kept.len() + ELLIPSIS.len()); + result.push_str(kept); + result.extend(ellipsis); + result +} + +fn truncate_owned(mut text: String, max_len: usize) -> String { + let (keep, ellipsis) = cut(max_len); + text.truncate(text.floor_char_boundary(keep)); + text.extend(ellipsis); + text +} + +fn truncate_markup(html: &str, max_len: usize) -> String { + let (keep, ellipsis) = cut(max_len); + let bytes = html.as_bytes(); + let mut in_tag = false; + let mut in_comment = false; + let mut last_tag_end = 0; + let mut end = html.len(); + for (pos, ch) in html.char_indices() { + let mut tag_boundary = 0; + match ch { + '<' if !in_tag => { + in_tag = true; + if bytes.get(pos + 1..pos + 1 + COMMENT_OPEN.len()) == Some(COMMENT_OPEN) { + in_comment = true; + } + tag_boundary = pos; + } + '>' if in_tag => { + if !in_comment { + in_tag = false; + tag_boundary = pos + 1; + } else if pos + .checked_sub(COMMENT_CLOSE.len()) + .and_then(|start| bytes.get(start..pos)) + == Some(COMMENT_CLOSE) + { + in_comment = false; + in_tag = false; + tag_boundary = pos + 1; + } + } + _ => (), + } + if ch.len_utf8() + pos > keep { + end = if (in_tag || tag_boundary > 0) && last_tag_end > 0 { + last_tag_end + } else { + pos + }; + break; + } else if tag_boundary > 0 { + last_tag_end = tag_boundary; + } + } + let kept = html.get(..end).unwrap_or_default(); + let mut result = String::with_capacity(kept.len() + ELLIPSIS.len()); + result.push_str(kept); + result.extend(ellipsis); + result +} + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + #[test] + fn text_preview() { + let text_1 = concat!( + "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", + "\u{2014} Antoine de Saint-Exupéry, Citadelle (1948)" + ); + let text_2 = concat!( + "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」", + "子路曰:「為孔丘。」曰:「是魯孔丘與?」曰:「是也。」曰:「是知津矣。」問於桀溺,", + "桀溺曰:「子為誰?」曰:「為仲由。」曰:「是魯孔丘之徒與?」對曰:「然。", + "」曰:「滔滔者天下皆是也,而誰以易之?且而與其從辟人之士也,豈若從", + "辟世之士哉?」耰而不輟。子路行以告。夫子憮然曰:「鳥獸不可與同群,吾非斯人之徒", + "與而誰與?天下有道,丘不與易也。」", + "子路從而後,遇丈人,以杖荷蓧。子路問曰:「子見夫子乎?」丈人曰:「四體不勤,", + "五穀不分。孰為夫子?」植其杖而芸。子路拱而立。止子路宿,殺雞為黍而食之,見其二", + "子焉。明日,子路行以告。子曰:「隱者也。」使子路反見之。至則行矣。子路曰:「", + "不仕無義。長幼之節,不可廢也;君臣之義,如之何其廢之?欲潔其身,而亂大倫。君", + "子之仕也,行其義也。道之不行,已知之矣。」" + ); + + assert_eq!( + super::truncate_text(text_1, 110), + "J'interdis aux marchands de vanter trop leurs marchandises. Car ils se fontvite pédagogues et t'enseignent..." + ); + + assert_eq!( + super::truncate_text(text_2, 110), + "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」子..." + ); + } + + #[test] + fn html_truncate() { + for (html, expected_result) in [ + ( + "hello
world
", + "hello
world...", + ), + ("using <>
", "using <>
..."), + ( + "test tag
test tag
", + "test tag...", + ), + ( + "<>< >>hello world< br \n />", + "<>< >>hello ...", + ), + ( + concat!( + "ignore headxyz", + "

<body>

" + ), + "ignore he...", + ), + ( + concat!( + "<p>what is ♥?</p><p>ßĂΒγ ", + "don't hurt me.</p>" + ), + "<p>what is ♥...", + ), + ( + "<!-- <> < < < -->the actual<!--> text", + "<!-- <> < < < -->the a...", + ), + ( + " < p > hello < / p > < p > world < / p > !!! < br > ", + " < p > hello ...", + ), + ( + " <p>please unsubscribe <a href=#>here</a>.</p> ", + " <p>please unsubscribe...", + ), + ] { + assert_eq!(super::truncate_html(html, 25), expected_result); + } + } + + #[test] + fn carriage_returns_are_stripped() { + assert_eq!( + super::preview_text("hello\r\nworld\r\n", 100), + "hello\nworld\n" + ); + assert_eq!(super::preview_text("hello\r\nworld", 8), "hello..."); + assert_eq!(super::preview_text("ab\r\rcd", 4), "abcd"); + assert_eq!(super::preview_text("ab\r\rcde", 4), "abcd"); + assert!(matches!( + super::preview_text("short", 10), + Cow::Borrowed("short") + )); + assert_eq!( + super::preview_html("<p>a b</p>\r\n<p>c</p>", 100), + "ab\n c\n" + ); + assert_eq!(super::preview_html("<p>hello world</p>", 8), "hello..."); + assert_eq!( + super::truncate_html("<p>\r\nhello</p>", 100), + "<p>\nhello</p>" + ); + } +} diff --git a/src/decoders/quoted_printable.rs b/src/decoders/quoted_printable.rs deleted file mode 100644 index b41dfa5..0000000 --- a/src/decoders/quoted_printable.rs +++ /dev/null @@ -1,451 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::borrow::Cow; - -use crate::parsers::MessageStream; - -#[derive(PartialEq, Debug)] -enum QuotedPrintableState { - None, - Eq, - Hex1, -} - -pub fn quoted_printable_decode(bytes: &[u8]) -> Option<Vec<u8>> { - let mut buf = Vec::with_capacity(bytes.len()); - - let mut state = QuotedPrintableState::None; - let mut hex1 = 0; - let mut ws_count = 0; - let mut crlf = b"\n".as_ref(); - - for &ch in bytes { - match ch { - b'=' => { - if let QuotedPrintableState::None = state { - state = QuotedPrintableState::Eq - } else { - return None; - } - } - b'\n' => { - if QuotedPrintableState::Eq == state { - state = QuotedPrintableState::None; - } else { - if ws_count > 0 { - buf.truncate(buf.len() - ws_count); - } - buf.extend_from_slice(crlf); - } - ws_count = 0; - } - b'\r' => { - crlf = b"\r\n".as_ref(); - } - _ => match state { - QuotedPrintableState::None => { - if ch.is_ascii_whitespace() { - ws_count += 1; - } else { - ws_count = 0; - } - buf.push(ch); - } - QuotedPrintableState::Eq => { - hex1 = HEX_MAP[ch as usize]; - - if hex1 != -1 { - state = QuotedPrintableState::Hex1; - } else if !ch.is_ascii_whitespace() { - return None; - } - } - QuotedPrintableState::Hex1 => { - let hex2 = HEX_MAP[ch as usize]; - - state = QuotedPrintableState::None; - if hex2 != -1 { - buf.push(((hex1 as u8) << 4) | hex2 as u8); - ws_count = 0; - } else { - return None; - } - } - }, - } - } - - buf.into() -} - -#[inline(always)] -pub fn quoted_printable_decode_char(hex1: u8, hex2: u8) -> Option<u8> { - let hex1 = HEX_MAP[hex1 as usize]; - let hex2 = HEX_MAP[hex2 as usize]; - - (hex1 != -1 && hex2 != -1).then_some(((hex1 as u8) << 4) | hex2 as u8) -} - -impl<'x> MessageStream<'x> { - pub fn decode_quoted_printable_mime(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) { - let mut buf = Vec::with_capacity(128); - - let mut state = QuotedPrintableState::None; - let mut hex1 = 0; - let mut last_ch = 0; - let mut before_last_ch = 0; - let mut ws_count = 0; - let mut end_pos = self.offset(); - let mut crlf = b"\n".as_ref(); - - self.checkpoint(); - - while let Some(&ch) = self.next() { - match ch { - b'=' => { - if let QuotedPrintableState::None = state { - state = QuotedPrintableState::Eq - } else { - self.restore(); - return (usize::MAX, b""[..].into()); - } - } - b'\n' => { - end_pos = if last_ch == b'\r' { - self.offset() - 2 - } else { - self.offset() - 1 - }; - if QuotedPrintableState::Eq == state { - state = QuotedPrintableState::None; - } else { - if ws_count > 0 { - buf.truncate(buf.len() - ws_count); - } - buf.extend_from_slice(crlf); - } - ws_count = 0; - } - b'\r' => { - crlf = b"\r\n".as_ref(); - } - b'-' if !boundary.is_empty() && last_ch == b'-' && self.try_skip(boundary) => { - if before_last_ch == b'\n' { - buf.truncate(buf.len() - (crlf.len() + 1)); - } else { - buf.truncate(buf.len() - 1); - end_pos = self.offset() - boundary.len() - 2; - } - - return (end_pos, buf.into()); - } - _ => match state { - QuotedPrintableState::None => { - if ch.is_ascii_whitespace() { - ws_count += 1; - } else { - ws_count = 0; - } - buf.push(ch); - } - QuotedPrintableState::Eq => { - hex1 = HEX_MAP[ch as usize]; - if hex1 != -1 { - state = QuotedPrintableState::Hex1; - } else if !ch.is_ascii_whitespace() { - state = QuotedPrintableState::None; - buf.push(b'='); - buf.push(ch); - ws_count = 0; - } - } - QuotedPrintableState::Hex1 => { - let hex2 = HEX_MAP[ch as usize]; - - state = QuotedPrintableState::None; - if hex2 != -1 { - buf.push(((hex1 as u8) << 4) | hex2 as u8); - ws_count = 0; - } else { - buf.push(b'='); - buf.push(last_ch); - buf.push(ch); - ws_count = 0; - } - } - }, - } - - before_last_ch = last_ch; - last_ch = ch; - } - - ( - if boundary.is_empty() { - self.offset() - } else { - self.restore(); - usize::MAX - }, - buf.into(), - ) - } - - pub fn decode_quoted_printable_word(&mut self) -> Option<Vec<u8>> { - let mut buf = Vec::with_capacity(64); - - let mut state = QuotedPrintableState::None; - let mut hex1 = 0; - - while let Some(&ch) = self.next() { - match ch { - b'=' => { - if let QuotedPrintableState::None = state { - state = QuotedPrintableState::Eq - } else { - break; - } - } - b'?' => { - if let Some(b'=') = self.peek() { - self.next(); - return buf.into(); - } else { - buf.push(b'?'); - } - } - b'\n' => { - if let Some(b' ' | b'\t') = self.peek() { - loop { - self.next(); - if !self.peek_next_is_space() { - break; - } - } - } else { - break; - } - } - b'_' => { - buf.push(b' '); - } - b'\r' => (), - _ => match state { - QuotedPrintableState::None => { - buf.push(ch); - } - QuotedPrintableState::Eq => { - hex1 = HEX_MAP[ch as usize]; - if hex1 != -1 { - state = QuotedPrintableState::Hex1; - } else { - // Failed - break; - } - } - QuotedPrintableState::Hex1 => { - let hex2 = HEX_MAP[ch as usize]; - state = QuotedPrintableState::None; - if hex2 != -1 { - buf.push(((hex1 as u8) << 4) | hex2 as u8); - } else { - // Failed - break; - } - } - }, - } - } - - None - } -} - -/* - * Adapted from Daniel Lemire's source: - * https://github.com/lemire/Code-used-on-Daniel-Lemire-s-blog/blob/master/2019/04/17/hexparse.cpp - * - */ - -pub static HEX_MAP: &[i8] = &[ - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, - 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -]; - -#[cfg(test)] -mod tests { - use crate::parsers::MessageStream; - - #[test] - fn decode_quoted_printable() { - for (encoded_str, expected_result) in [ - ( - concat!( - "J'interdis aux marchands de vanter trop leurs marchandises. ", - "Car ils se font=\nvite p=C3=A9dagogues et t'enseignent comme but ce ", - "qui n'est par essence qu=\n'un moyen, et te trompant ainsi sur la route ", - "=C3=A0 suivre les voil=C3=\n=A0 bient=C3=B4t qui te d=C3=A9gradent, car ", - "si leur musique est vulgaire il=\ns te fabriquent pour te la vendre une ", - "=C3=A2me vulgaire.\n=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry, ", - "Citadelle (1948)" - ), - concat!( - "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", - "— Antoine de Saint-Exupéry, Citadelle (1948)" - ), - ), - ( - "=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry", - "— Antoine de Saint-Exupéry", - ), - ( - concat!( - "Die Hasen klagten einst uber ihre Lage; \"wir ", - "leben\", sprach ein=\r\n Redner, \"in steter Furcht vor Menschen", - " und Tieren, eine Beute der Hunde,=\r\n der\n" - ), - concat!( - "Die Hasen klagten einst uber ihre Lage; \"wir leben\", ", - "sprach ein Redner, \"in steter Furcht vor Menschen und ", - "Tieren, eine Beute der Hunde, der\r\n" - ), - ), - ( - concat!( - "hello \r\nbar=\r\n\r\nfoo\t=\r\nbar\r\nfoo\t \t= \r\n=62\r\nfoo = ", - "\t\r\nbar\r\nfoo =\r\n=62\r\nfoo \r\nbar=\r\n\r\nfoo_bar\r\n" - ), - "hello\r\nbar\r\nfoo\tbar\r\nfoo\t \tb\r\nfoo bar\r\nfoo b\r\nfoo\r\nbar\r\nfoo_bar\r\n", - ), - ("\n\n", "\n\n"), - ] { - assert_eq!( - String::from_utf8( - super::quoted_printable_decode(encoded_str.as_bytes()).unwrap_or_default() - ) - .unwrap(), - expected_result, - "Failed for {encoded_str:?}", - ); - } - } - - #[test] - fn decode_quoted_printable_mime() { - for (encoded_str, expected_result) in [ - ( - "<meta content=\"text/html; charset=utf-8\"> h=C3=B6\n--boundary", - "<meta content=\"text/html; charset=utf-8\"> hö", - ), - ("first=AZ second\n--boundary", "first=AZ second"), - ( - "=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--boundary", - "— Antoine de Saint-Exupéry", - ), - ( - "=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--\n--boundary", - "— Antoine de Saint-Exupéry\n--", - ), - ( - "=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry=\n--\n--boundary", - "— Antoine de Saint-Exupéry--", - ), - ( - concat!( - "J'interdis aux marchands de vanter trop leurs marchandises. ", - "Car ils se font=\nvite p=C3=A9dagogues et t'enseignent comme but ce ", - "qui n'est par essence qu=\n'un moyen, et te trompant ainsi sur la route ", - "=C3=A0 suivre les voil=C3=\n=A0 bient=C3=B4t qui te d=C3=A9gradent, car ", - "si leur musique est vulgaire il=\ns te fabriquent pour te la vendre une ", - "=C3=A2me vulgaire.\n=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry, ", - "Citadelle (1948)\r\n--boundary--" - ), - concat!( - "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", - "— Antoine de Saint-Exupéry, Citadelle (1948)" - ), - ), - ( - "=E2=80=94=E2=80=89Antoine de Saint-Exup=C3=A9ry\n--\n--boundary", - "— Antoine de Saint-Exupéry\n--", - ), - ( - concat!( - "Die Hasen klagten einst uber ihre Lage; \"wir ", - "leben\", sprach ein=\r\n Redner, \"in steter Furcht vor Menschen", - " und Tieren, eine Beute der Hunde,=\r\n der\r\n\r\n--boundary \n" - ), - concat!( - "Die Hasen klagten einst uber ihre Lage; \"wir leben\", ", - "sprach ein Redner, \"in steter Furcht vor Menschen und ", - "Tieren, eine Beute der Hunde, der\r\n" - ), - ), - ( - concat!( - "hello \r\nbar=\r\n\r\nfoo\t=\r\nbar\r\nfoo\t \t= \r\n=62\r\nfoo = ", - "\t\r\nbar\r\nfoo =\r\n=62\r\nfoo \r\nbar=\r\n\r\nfoo_bar\r\n\r\n--boundary" - ), - "hello\r\nbar\r\nfoo\tbar\r\nfoo\t \tb\r\nfoo bar\r\nfoo b\r\nfoo\r\nbar\r\nfoo_bar\r\n", - ), - ] { - let mut s = MessageStream::new(encoded_str.as_bytes()); - let (bytes_read, result) = s.decode_quoted_printable_mime(b"boundary"); - assert_ne!(bytes_read, usize::MAX); - assert_eq!( - std::str::from_utf8(result.as_ref()).unwrap(), - expected_result, - "Failed for {encoded_str:?}", - ); - } - } - - #[test] - fn decode_quoted_printable_word() { - for (encoded_str, expected_result) in [ - ("this=20is=20some=20text?=", "this is some text"), - ("this=20is=20\n some=20text?=", "this is some text"), - ("this is some text?=", "this is some text"), - ("Keith_Moore?=", "Keith Moore"), - ("=2=123?=", ""), - ("= 20?=", ""), - ("=====?=", ""), - ("=20=20=XX?=", ""), - ("=AX?=", ""), - ("=\n=\n==?=", ""), - ("=\r=1z?=", ""), - ("=|?=", ""), - ("????????=", "???????"), - ("\n\n", ""), - ] { - let mut s = MessageStream::new(encoded_str.as_bytes()); - - assert_eq!( - s.decode_quoted_printable_word().unwrap_or_default(), - expected_result.as_bytes(), - "Failed for {encoded_str:?}", - ); - } - } -} diff --git a/src/fields/address.rs b/src/fields/address.rs new file mode 100644 index 0000000..55b4f17 --- /dev/null +++ b/src/fields/address.rs @@ -0,0 +1,969 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{FieldCtx, GroupMark, push_utf8_lossy}; +use crate::{ + decoders::charsets, + scan::{ByteSet, Kernel}, + store::{Str, Value}, +}; +use encodify::rfc2047::EncodedWord; +use std::ops::Range; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[repr(u8)] +enum State { + Name = 1, + Address = 2, + Quote = 4, + Comment = 8, +} + +const IN_NAME: u8 = State::Name as u8; +const IN_ADDRESS: u8 = State::Address as u8; +const IN_QUOTE: u8 = State::Quote as u8; +const IN_COMMENT: u8 = State::Comment as u8; +const EVERYWHERE: u8 = IN_NAME | IN_ADDRESS | IN_QUOTE | IN_COMMENT; + +static STOPS: [u8; 256] = { + let mut table = [0; 256]; + table[b'\n' as usize] = EVERYWHERE; + table[b'\r' as usize] = EVERYWHERE; + table[b' ' as usize] = EVERYWHERE; + table[b'\t' as usize] = EVERYWHERE; + table[b'=' as usize] = EVERYWHERE; + table[b'"' as usize] = IN_NAME | IN_QUOTE; + table[b'(' as usize] = IN_NAME | IN_ADDRESS | IN_COMMENT; + table[b'\\' as usize] = IN_ADDRESS | IN_QUOTE | IN_COMMENT; + table[b',' as usize] = IN_NAME; + table[b'<' as usize] = IN_NAME; + table[b'@' as usize] = IN_NAME; + table[b':' as usize] = IN_NAME; + table[b';' as usize] = IN_NAME; + table[b'>' as usize] = IN_ADDRESS; + table[b')' as usize] = IN_COMMENT; + table +}; + +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>\\(="); + +fn is_blank(byte: u8) -> bool { + byte == b' ' || byte == b'\t' +} + +fn skip_space(bytes: &[u8], mut at: usize) -> usize { + loop { + match bytes.get(at) { + Some(b' ' | b'\t' | b'\r') => at += 1, + Some(b'\n') if bytes.get(at + 1).copied().is_some_and(is_blank) => at += 2, + _ => return at, + } + } +} + +fn trimmed_len(bytes: &[u8]) -> usize { + bytes + .iter() + .rposition(|&byte| !is_blank(byte)) + .map_or(0, |last| last + 1) +} + +type SimpleShape = (Option<Range<usize>>, Option<Range<usize>>, usize); + +#[derive(Clone, Copy)] +struct Item<'x> { + kernel: Kernel, + src: &'x [u8], + start: usize, + end: usize, +} + +impl Item<'_> { + fn bytes(&self) -> &[u8] { + self.src.get(self.start..self.end).unwrap_or_default() + } + + fn find(&self, set: &ByteSet, from: usize) -> Option<usize> { + self.kernel + .first_in_set(set, self.src, self.start + from, self.end) + .map(|pos| pos - self.start) + } + + fn shape(&self) -> Option<SimpleShape> { + let bytes = self.bytes(); + let first = skip_space(bytes, 0); + let rest = bytes.get(first..)?; + if rest.first() == Some(&b'"') { + let close = self.find(&SIMPLE_QUOTED, first + 1)?; + if close == first + 1 || bytes.get(close) != Some(&b'"') { + return None; + } + let open = skip_space(bytes, close + 1); + if bytes.get(open) != Some(&b'<') { + return None; + } + let (address, after) = self.angle(open + 1)?; + return Some((Some(first + 1..close), Some(address), after)); + } + let found = self + .kernel + .stop_in_set(&SIMPLE_NAME, self.src, self.start + first, self.end); + let stop = found.at.map_or(bytes.len(), |pos| pos - self.start); + let run = bytes.get(first..stop)?; + let name_len = trimmed_len(run); + let name = first..first + name_len; + match bytes.get(stop) { + Some(b'<') => { + let (address, after) = self.angle(stop + 1)?; + Some(((name_len > 0).then_some(name), Some(address), after)) + } + None | Some(b',' | b';' | b'\r' | b'\n') if name_len > 0 => { + if found.marked { + Some((None, Some(name), first + name_len)) + } else { + Some((Some(name), None, first + name_len)) + } + } + _ => None, + } + } + + fn angle(&self, open: usize) -> Option<(Range<usize>, usize)> { + let close = self.angle_end(open)?; + let content = self.bytes().get(open..close)?; + let lead = content.iter().position(|&byte| !is_blank(byte))?; + Some((open + lead..open + trimmed_len(content), close + 1)) + } + + fn angle_end(&self, open: usize) -> Option<usize> { + let bytes = self.bytes(); + let mut from = open; + loop { + let stop = self.find(&SIMPLE_ADDRESS, from)?; + match bytes.get(stop) { + Some(b'>') => return Some(stop), + Some(b'=') + if stop > open + && stop + .checked_sub(1) + .and_then(|previous| bytes.get(previous)) + .is_some_and(|&previous| !is_blank(previous)) => + { + from = stop + 1 + } + _ => return None, + } + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum List { + Name, + Mail, + Comment, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Origin { + Source, + Decoded, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct Piece { + origin: Origin, + start: usize, + end: usize, + space: bool, +} + +const RECORD_LEN: usize = 16; +const TAG_SHIFT: u32 = 56; +const START_MASK: u128 = (1 << TAG_SHIFT) - 1; +const LIST_MASK: u128 = 0b11; +const DECODED_FLAG: u128 = 0b100; +const SPACE_FLAG: u128 = 0b1000; +const END_SHIFT: u32 = 64; + +impl Piece { + const EMPTY: Piece = Piece { + origin: Origin::Source, + start: 0, + end: 0, + space: false, + }; + + fn record(self, list: List) -> [u8; RECORD_LEN] { + let mut tag = list as u128; + if self.origin == Origin::Decoded { + tag |= DECODED_FLAG; + } + if self.space { + tag |= SPACE_FLAG; + } + let start = self.start as u128 & START_MASK; + let end = (self.end as u128) << END_SHIFT; + (start | (tag << TAG_SHIFT) | end).to_le_bytes() + } + + fn from_record(record: &[u8; RECORD_LEN]) -> (u128, Piece) { + let value = u128::from_le_bytes(*record); + let tag = value >> TAG_SHIFT; + ( + tag & LIST_MASK, + Piece { + origin: if tag & DECODED_FLAG != 0 { + Origin::Decoded + } else { + Origin::Source + }, + start: (value & START_MASK) as usize, + end: (value >> END_SHIFT) as usize, + space: tag & SPACE_FLAG != 0, + }, + ) + } +} + +enum PieceText<'a> { + Text(&'a str), + Bytes(&'a [u8]), +} + +#[derive(Clone, Copy, Debug)] +struct Acc { + count: usize, + first: Piece, +} + +impl Acc { + const EMPTY: Acc = Acc { + count: 0, + first: Piece::EMPTY, + }; +} + +#[derive(Clone, Copy, Debug)] +struct PendingWord<'x> { + list: List, + space: bool, + charset: &'x [u8], +} + +#[derive(Clone, Copy, Debug)] +struct OpenGroup { + empty_name: Option<Str>, + name: Option<Str>, + marker: Option<GroupMark>, +} + +struct Parser<'x> { + src: &'x [u8], + end: usize, + state: State, + outer: State, + depth: usize, + token: Option<(usize, usize)>, + email: bool, + token_start: bool, + escaped: bool, + last_encoded: bool, + name: Acc, + mail: Acc, + comment: Acc, + records: usize, + raw: Vec<u8>, + text: String, + pending: Option<PendingWord<'x>>, + group: Option<OpenGroup>, +} + +pub(crate) fn parse_address(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + let mark = ctx.address_mark(); + let src = ctx.src(); + let mut parser = Parser { + src, + end: value.end.min(src.len()), + state: State::Name, + outer: State::Name, + depth: 0, + token: None, + email: false, + token_start: true, + escaped: false, + last_encoded: true, + name: Acc::EMPTY, + mail: Acc::EMPTY, + comment: Acc::EMPTY, + records: 0, + raw: ctx.take_bytes_scratch(), + text: ctx.take_text_scratch(), + pending: None, + group: None, + }; + parser.run(ctx, value.start); + parser.add_token(); + parser.add_address(ctx); + parser.close_group(ctx); + ctx.put_bytes_scratch(parser.raw); + ctx.put_text_scratch(parser.text); + ctx.address_list(mark) +} + +impl<'x> Parser<'x> { + fn run(&mut self, ctx: &mut FieldCtx<'_>, start: usize) { + let src = self.src; + let mut pos = start; + let mut item_start = true; + loop { + if item_start { + item_start = false; + if !self.escaped + && let Some(next) = self.simple_item(ctx, pos) + { + pos = next; + } + } + let rest = src.get(pos..self.end).unwrap_or_default(); + let mask = self.state as u8; + let Some(run) = rest + .iter() + .position(|&byte| STOPS[usize::from(byte)] & mask != 0) + else { + if !rest.is_empty() { + self.extend(pos, self.end); + } + return; + }; + if run > 0 { + self.extend(pos, pos + run); + pos += run; + } + let Some((&byte, after)) = rest.get(run..).and_then(<[u8]>::split_first) else { + return; + }; + match byte { + b'\n' => { + self.add_token(); + if !matches!(after.first(), Some(b' ' | b'\t')) { + return; + } + if self.state == State::Quote { + pos += 1; + } else { + self.token_start = true; + pos += 2; + } + } + b' ' | b'\t' => { + let blanks = 1 + after.iter().take_while(|&&byte| is_blank(byte)).count(); + self.token_start = true; + self.escaped = false; + if self.state == State::Quote { + let first = self.token.map_or(pos, |(first, _)| first); + self.token = Some((first, pos + blanks)); + } + pos += blanks; + } + b'\r' => pos += 1, + b'\\' if !self.escaped => { + if let Some((first, _)) = self.token { + if self.state == State::Quote { + self.token = Some((first, pos)); + } + self.add_token(); + } + self.escaped = true; + pos += 1; + } + b'=' if self.token_start && !self.escaped && after.first() == Some(&b'?') => { + match self.encoded_word(pos) { + Some(consumed) => pos += consumed, + None => { + self.extend(pos, pos + 1); + pos += 1; + } + } + } + b',' => { + self.add_token(); + self.add_address(ctx); + pos += 1; + item_start = true; + } + b'<' => { + self.email = false; + self.add_token(); + self.state = State::Address; + pos += 1; + } + b'>' => { + self.add_token(); + self.state = State::Name; + pos += 1; + } + b'"' if !self.escaped && self.state == State::Name => { + self.state = State::Quote; + self.add_token(); + pos += 1; + } + b'"' if !self.escaped => { + self.add_token(); + self.state = State::Name; + pos += 1; + } + b'@' => { + self.email = true; + self.extend(pos, pos + 1); + pos += 1; + } + b'(' if !self.escaped && self.state == State::Comment => { + self.depth += 1; + self.extend(pos, pos + 1); + pos += 1; + } + b'(' if !self.escaped => { + self.add_token(); + self.outer = self.state; + self.state = State::Comment; + self.depth = 1; + self.last_encoded = false; + pos += 1; + } + b')' if !self.escaped && self.depth > 1 => { + self.depth -= 1; + self.extend(pos, pos + 1); + pos += 1; + } + b')' if !self.escaped => { + self.add_token(); + self.depth = 0; + self.state = self.outer; + self.last_encoded = false; + pos += 1; + } + b':' if !self.escaped => { + self.close_group(ctx); + self.add_token(); + self.open_group(ctx); + pos += 1; + item_start = true; + } + b';' => { + self.add_token(); + self.add_address(ctx); + self.close_group(ctx); + pos += 1; + item_start = true; + } + _ => { + self.extend(pos, pos + 1); + pos += 1; + } + } + } + } + + fn extend(&mut self, start: usize, end: usize) { + self.escaped = false; + self.token_start = false; + self.token = Some((self.token.map_or(start, |(first, _)| first), end)); + } + + fn acc(&self, list: List) -> &Acc { + match list { + List::Name => &self.name, + List::Mail => &self.mail, + List::Comment => &self.comment, + } + } + + fn acc_mut(&mut self, list: List) -> &mut Acc { + match list { + List::Name => &mut self.name, + List::Mail => &mut self.mail, + List::Comment => &mut self.comment, + } + } + + fn add_piece(&mut self, list: List, piece: Piece) { + if self.acc(list).count == 0 { + self.acc_mut(list).first = piece; + } else { + let at = self.records.min(self.raw.len()); + self.raw.splice(at..at, piece.record(list)); + self.records = at + RECORD_LEN; + } + self.acc_mut(list).count += 1; + } + + fn add_token(&mut self) { + let Some((start, end)) = self.token.take() else { + return; + }; + let (list, separated) = match self.state { + State::Name if !self.email => (List::Name, true), + State::Name | State::Address => (List::Mail, false), + State::Quote => (List::Name, false), + State::Comment => (List::Comment, true), + }; + self.flush_word(self.raw.len()); + let space = separated && self.acc(list).count > 0; + self.add_piece( + list, + Piece { + origin: Origin::Source, + start, + end, + space, + }, + ); + self.email = false; + self.token_start = true; + self.escaped = false; + self.last_encoded = false; + } + + fn encoded_word(&mut self, at: usize) -> Option<usize> { + let (word, consumed) = EncodedWord::parse(self.src.get(at..self.end)?)?; + let list = match self.state { + State::Comment => List::Comment, + _ => List::Name, + }; + let joinable = self.token.is_none() + && self.last_encoded + && self.pending.is_some_and(|pending| { + pending.list == list && pending.charset.eq_ignore_ascii_case(word.charset) + }); + let split = self.raw.len(); + word.decode_append(&mut self.raw).ok()?; + if !joinable { + self.flush_word(split); + self.add_token(); + let space = + !self.last_encoded && self.state != State::Quote && self.acc(list).count > 0; + self.pending = Some(PendingWord { + list, + space, + charset: word.charset, + }); + } + self.last_encoded = true; + Some(consumed) + } + + fn flush_word(&mut self, split: usize) { + let Some(word) = self.pending.take() else { + return; + }; + let from = self.records.min(self.raw.len()); + let split = split.clamp(from, self.raw.len()); + let start = self.text.len(); + charsets::decode_append( + word.charset, + self.raw.get(from..split).unwrap_or_default(), + &mut self.text, + ); + let end = self.text.len(); + self.raw.drain(from..split); + self.add_piece( + word.list, + Piece { + origin: Origin::Decoded, + start, + end, + space: word.space, + }, + ); + } + + fn pieces(&self, list: List) -> impl Iterator<Item = Piece> { + let acc = self.acc(list); + let records: &[u8] = match acc.count { + 0 | 1 => &[], + _ => self.raw.get(..self.records).unwrap_or_default(), + }; + let (records, _) = records.as_chunks::<RECORD_LEN>(); + (acc.count > 0).then_some(acc.first).into_iter().chain( + records + .iter() + .map(Piece::from_record) + .filter_map(move |(id, piece)| (id == list as u128).then_some(piece)), + ) + } + + fn piece_text(&self, piece: Piece) -> PieceText<'_> { + match piece.origin { + Origin::Source => { + PieceText::Bytes(self.src.get(piece.start..piece.end).unwrap_or_default()) + } + Origin::Decoded => { + PieceText::Text(self.text.get(piece.start..piece.end).unwrap_or_default()) + } + } + } + + fn write_list(&self, out: &mut String, list: List) { + for piece in self.pieces(list) { + if piece.space { + out.push(' '); + } + match self.piece_text(piece) { + PieceText::Text(text) => out.push_str(text), + PieceText::Bytes(bytes) => push_utf8_lossy(out, bytes), + } + } + } + + fn has_whitespace(&self, list: List) -> bool { + self.pieces(list).any(|piece| { + piece.space + || match self.piece_text(piece) { + PieceText::Text(text) => text.chars().any(char::is_whitespace), + PieceText::Bytes(bytes) => bytes + .utf8_chunks() + .any(|chunk| chunk.valid().chars().any(char::is_whitespace)), + } + }) + } + + fn list_str(&self, ctx: &mut FieldCtx<'_>, list: List) -> Option<Str> { + let acc = self.acc(list); + match acc.count { + 0 => None, + 1 => Some(match self.piece_text(acc.first) { + PieceText::Text(text) => ctx.push_str(text), + PieceText::Bytes(_) => ctx.borrow(acc.first.start..acc.first.end), + }), + _ => Some(ctx.push_with(|pool| self.write_list(pool, list))), + } + } + + fn with_comment(&self, ctx: &mut FieldCtx<'_>, write: impl Fn(&Self, &mut String)) -> Str { + ctx.push_with(|pool| { + write(self, pool); + pool.push_str(" ("); + self.write_list(pool, List::Comment); + pool.push(')'); + }) + } + + fn reset_lists(&mut self) { + self.name = Acc::EMPTY; + self.mail = Acc::EMPTY; + self.comment = Acc::EMPTY; + self.records = 0; + self.raw.clear(); + self.text.clear(); + } + + fn add_address(&mut self, ctx: &mut FieldCtx<'_>) { + self.flush_word(self.raw.len()); + let name_only = |parser: &Self, pool: &mut String| parser.write_list(pool, List::Name); + let (name, address) = match ( + self.mail.count > 0, + self.name.count > 0, + self.comment.count > 0, + ) { + (true, true, true) => ( + Some(self.with_comment(ctx, name_only)), + self.list_str(ctx, List::Mail), + ), + (true, true, false) => ( + self.list_str(ctx, List::Name), + self.list_str(ctx, List::Mail), + ), + (true, false, true) => ( + self.list_str(ctx, List::Comment), + self.list_str(ctx, List::Mail), + ), + (true, false, false) => (None, self.list_str(ctx, List::Mail)), + (false, true, true) if self.has_whitespace(List::Name) => { + (Some(self.with_comment(ctx, name_only)), None) + } + (false, true, true) => ( + self.list_str(ctx, List::Comment), + self.list_str(ctx, List::Name), + ), + (false, true, false) => (self.list_str(ctx, List::Name), None), + (false, false, true) => (self.list_str(ctx, List::Comment), None), + (false, false, false) => return, + }; + self.reset_lists(); + self.push_member(ctx, name, address); + } + + fn push_member(&mut self, ctx: &mut FieldCtx<'_>, name: Option<Str>, address: Option<Str>) { + if let Some(group) = self.group.as_mut() + && group.marker.is_none() + { + group.marker = Some(ctx.push_group(group.name)); + } + ctx.push_mailbox(name, address); + } + + fn simple_item(&mut self, ctx: &mut FieldCtx<'_>, start: usize) -> Option<usize> { + let item = Item { + kernel: ctx.kernel(), + src: self.src, + start, + end: self.end, + }; + let bytes = item.bytes(); + let (name, address, after) = item.shape()?; + if !matches!( + bytes.get(skip_space(bytes, after)), + None | Some(b',' | b';' | b'\n') + ) { + return None; + } + let name = name.map(|range| ctx.borrow(start + range.start..start + range.end)); + let address = address.map(|range| ctx.borrow(start + range.start..start + range.end)); + self.push_member(ctx, name, address); + self.last_encoded = false; + Some(start + after) + } + + fn write_group_name(&self, out: &mut String) { + self.write_list(out, List::Name); + if self.name.count > 0 && self.mail.count > 0 { + out.push(' '); + } + self.write_list(out, List::Mail); + } + + fn open_group(&mut self, ctx: &mut FieldCtx<'_>) { + self.flush_word(self.raw.len()); + let empty_name = match (self.name.count > 0, self.mail.count > 0) { + (true, true) => Some(ctx.push_with(|pool| self.write_group_name(pool))), + (true, false) => self.list_str(ctx, List::Name), + (false, true) => self.list_str(ctx, List::Mail), + (false, false) => None, + }; + let name = match (empty_name, self.comment.count > 0) { + (Some(_), true) => Some(self.with_comment(ctx, Self::write_group_name)), + (Some(name), false) => Some(name), + (None, true) => self.list_str(ctx, List::Comment), + (None, false) => None, + }; + self.reset_lists(); + self.group = Some(OpenGroup { + empty_name, + name, + marker: None, + }); + } + + fn close_group(&mut self, ctx: &mut FieldCtx<'_>) { + match self.group.take() { + Some(OpenGroup { + marker: Some(marker), + .. + }) => ctx.end_group(marker), + Some(OpenGroup { + empty_name: Some(name), + .. + }) => { + let marker = ctx.push_group(Some(name)); + ctx.end_group(marker); + } + _ => (), + } + } +} + +/// The local part of an address (before the first `@`), when it is ASCII +/// and both sides of the `@` are non-empty. +pub fn parse_address_local_part(addr: &str) -> Option<&str> { + let (local, domain) = addr.split_once('@')?; + (!local.is_empty() && local.is_ascii() && !domain.is_empty()).then_some(local) +} + +/// The domain of an address (after the first `@`), when the local part is +/// ASCII and both sides of the `@` are non-empty. +pub fn parse_address_domain(addr: &str) -> Option<&str> { + let (local, domain) = addr.split_once('@')?; + (!local.is_empty() && local.is_ascii() && !domain.is_empty()).then_some(domain) +} + +/// The user of a subaddress (RFC 5233): the local part up to the first `+`. +pub fn parse_address_user_part(addr: &str) -> Option<&str> { + let (local, domain) = addr.split_once('@')?; + let user = local.split_once('+').map_or(local, |(user, _)| user); + (!user.is_empty() && user.is_ascii() && !domain.is_empty()).then_some(user) +} + +/// The detail of a subaddress (RFC 5233): the local part after its last `+`. +pub fn parse_address_detail_part(addr: &str) -> Option<&str> { + let (local, domain) = addr.split_once('@')?; + let (_, detail) = local.rsplit_once('+')?; + (local.is_ascii() && !domain.is_empty()).then_some(detail) +} + +#[cfg(test)] +mod tests { + use super::{ + parse_address_detail_part, parse_address_domain, parse_address_local_part, + parse_address_user_part, + }; + use crate::{Address, HeaderForm, HeaderValue, fields::tests::load_tests}; + use serde_json::{Value as Json, json}; + + fn mailbox_json(name: Option<&str>, address: Option<&str>) -> Json { + json!({"name": name, "address": address}) + } + + fn address_json(value: HeaderValue<'_>) -> Json { + match value.as_address() { + Some(list) => Json::Array( + list.iter() + .map(|item| match item { + Address::Mailbox(mailbox) => { + json!({"mailbox": mailbox_json(mailbox.name(), mailbox.address())}) + } + Address::Group(group) => json!({"group": { + "name": group.name(), + "mailboxes": group + .mailboxes() + .map(|mailbox| mailbox_json(mailbox.name(), mailbox.address())) + .collect::<Vec<_>>(), + }}), + }) + .collect(), + ), + None => Json::Null, + } + } + + fn parse(header: &str) -> Json { + address_json(HeaderForm::Addresses.parse(header.as_bytes()).value()) + } + + fn mailbox(name: Option<&str>, address: Option<&str>) -> Json { + json!({"mailbox": mailbox_json(name, address)}) + } + + #[test] + fn address_fixtures() { + let tests = load_tests("address.json"); + assert_eq!(tests.len(), 127); + for (header, expected) in tests { + assert_eq!(parse(&header), expected, "{header:?}"); + let crlf = header.replace("\r\n", "\n").replace('\n', "\r\n"); + assert_eq!(parse(&crlf), expected, "{crlf:?}"); + } + } + + #[test] + fn issue_98_document_order() { + let parsed = HeaderForm::Addresses.parse(b" a@b.c, g: d@e.f;, h@i.j\n"); + let list = parsed.value().as_address().expect("address list"); + assert!(list.has_groups()); + assert_eq!( + list.mailboxes() + .filter_map(|mailbox| mailbox.address()) + .collect::<Vec<_>>(), + ["a@b.c", "d@e.f", "h@i.j"] + ); + let groups: Vec<_> = list + .groups() + .map(|(name, run)| { + ( + name, + run.filter_map(|mailbox| mailbox.address()) + .collect::<Vec<_>>(), + ) + }) + .collect(); + assert_eq!( + groups, + [ + (None, vec!["a@b.c"]), + (Some("g"), vec!["d@e.f"]), + (None, vec!["h@i.j"]) + ] + ); + } + + #[test] + fn baseline_quirks_kept() { + let parsed = HeaderForm::Addresses.parse(b"J\xf6rg <a@b.com>\n"); + assert_eq!( + address_json(parsed.value()), + json!([mailbox(Some("J\u{fffd}rg"), Some("a@b.com"))]) + ); + } + + #[test] + fn simple_values_borrow() { + for header in [ + &b"john@example.com\n"[..], + b" John Smith <john@example.com>\r\n", + b"\"Smith, John\" <john@example.com>,\n\tjane@example.com\n", + b"Friends: a@b.c, <d@e.f>;\n", + b"<mailto:list@example.com> (List)\n", + ] { + let parsed = HeaderForm::Addresses.parse(header); + assert!(parsed.value().as_address().is_some()); + assert!( + parsed + .data + .as_ref() + .is_some_and(|data| data.strings.is_empty()), + "{:?}", + String::from_utf8_lossy(header) + ); + } + } + + #[test] + fn address_parts() { + for (address, local, domain, user, detail) in [ + ( + "user@example.com", + Some("user"), + Some("example.com"), + Some("user"), + None, + ), + ( + "user+tag@example.com", + Some("user+tag"), + Some("example.com"), + Some("user"), + Some("tag"), + ), + ("a+b+c@d", Some("a+b+c"), Some("d"), Some("a"), Some("c")), + ("a+@b", Some("a+"), Some("b"), Some("a"), Some("")), + ("+a@b", Some("+a"), Some("b"), None, Some("a")), + ("+@b", Some("+"), Some("b"), None, Some("")), + ("@example.com", None, None, None, None), + ("user@", None, None, None, None), + ("user", None, None, None, None), + ("", None, None, None, None), + ("us\u{e9}r@example.com", None, None, None, None), + ( + "user@ex\u{e1}mple.com", + Some("user"), + Some("ex\u{e1}mple.com"), + Some("user"), + None, + ), + ("a+\u{e9}@b", None, None, Some("a"), None), + ("a@b+c@d", Some("a"), Some("b+c@d"), Some("a"), None), + ("a+b@@", Some("a+b"), Some("@"), Some("a"), Some("b")), + ("a+b", None, None, None, None), + ] { + assert_eq!(parse_address_local_part(address), local, "{address:?}"); + assert_eq!(parse_address_domain(address), domain, "{address:?}"); + assert_eq!(parse_address_user_part(address), user, "{address:?}"); + assert_eq!(parse_address_detail_part(address), detail, "{address:?}"); + } + } +} diff --git a/src/fields/content_type.rs b/src/fields/content_type.rs new file mode 100644 index 0000000..f509103 --- /dev/null +++ b/src/fields/content_type.rs @@ -0,0 +1,1079 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{FieldCtx, push_utf8_lossy as push_lossy}; +use crate::{ + decoders::charsets, + scan::{ByteSet, Kernel}, + store::{Str, Value}, +}; +use encodify::{Error, hex, rfc2047::EncodedWord}; +use std::ops::Range; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum State { + Type, + SubType, + AttributeName, + AttributeValue, + AttributeQuotedValue, + Comment, +} + +struct Parser { + state: State, + outer_state: State, + comment_depth: usize, + c_type: Option<Str>, + c_subtype: Option<Str>, + attr_name: Option<Str>, + attr_charset: Option<Str>, + attr_position: u32, + params: u32, + sections: usize, + budget: u32, + has_continued: bool, + has_languages: bool, + token: Option<(usize, usize)>, + values: String, + has_values: bool, + is_continuation: bool, + is_encoded_attribute: bool, + is_escaped: bool, + remove_crlf: bool, + is_token_start: bool, + apostrophes: u8, +} + +fn percent_decode_append(bytes: &[u8], out: &mut Vec<u8>) -> bool { + match hex::PERCENT.decode_append(bytes, out) { + Ok(_) => true, + Err(Error::Truncated { .. }) => { + let cut = if bytes.ends_with(b"%") { 1 } else { 2 }; + bytes + .get(..bytes.len().saturating_sub(cut)) + .is_some_and(|complete| hex::PERCENT.decode_append(complete, out).is_ok()) + } + Err(_) => false, + } +} + +const MAX_PARAMS: u32 = 1_000; +const LANGUAGE_SUFFIX: &[u8] = b"-language"; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Class { + Param, + Language, + First, + Continued, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Charset, + Plain, + Encoded, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct Key(u32); + +type Entry = (Str, u32, Str); + +impl Key { + const INDEX_MASK: u32 = (1 << 28) - 1; + + fn new(class: Class, index: u32, kind: Kind) -> Key { + Key((class as u32) << 30 | index.min(Key::INDEX_MASK) << 2 | kind as u32) + } + + fn of(entry: &Entry) -> Key { + Key(entry.1) + } + + fn class(self) -> Class { + match self.0 >> 30 { + 0 => Class::Param, + 1 => Class::Language, + 2 => Class::First, + _ => Class::Continued, + } + } + + fn index(self) -> u32 { + (self.0 >> 2) & Key::INDEX_MASK + } + + fn kind(self) -> Kind { + match self.0 & 3 { + 0 => Kind::Charset, + 1 => Kind::Plain, + _ => Kind::Encoded, + } + } +} + +const MAX_SIMPLE_PARAMS: usize = 8; +const NAME: u8 = 1; +const VALUE: u8 = 2; +const QUOTED: u8 = 4; +const UPPER: u8 = 8; +const TOKEN_MARKS: &[u8] = b"!#$%&+-.^_`{|}~"; +const VALUE_MARKS: &[u8] = b"*'/@:,<>[]?)"; + +static CLASSES: [u8; 256] = { + let mut table = [0; 256]; + let mut byte = 0; + while byte < 256 { + let value = byte as u8; + let mut class = 0; + if value.is_ascii_alphanumeric() || value >= 0x80 { + class = NAME | VALUE | QUOTED; + } else if value == b' ' || value == b'\t' || value >= 0x20 && value < 0x7f { + class = QUOTED; + } + if value.is_ascii_uppercase() { + class |= UPPER; + } + let mut mark = 0; + while mark < TOKEN_MARKS.len() { + if TOKEN_MARKS[mark] == value { + class |= NAME | VALUE; + } + mark += 1; + } + mark = 0; + while mark < VALUE_MARKS.len() { + if VALUE_MARKS[mark] == value { + class |= VALUE; + } + mark += 1; + } + if value == b'"' || value == b'\\' || value == b'=' { + class = 0; + } + table[byte] = class; + byte += 1; + } + table +}; + +#[derive(Clone, Copy, Default)] +struct Token { + start: usize, + end: usize, + upper: bool, +} + +#[derive(Clone, Copy, Default)] +struct SimpleParam { + name: Token, + value: Option<(usize, usize)>, +} + +struct Simple { + ctype: Token, + subtype: Option<Token>, + params: [SimpleParam; MAX_SIMPLE_PARAMS], + len: usize, +} + +fn run_of(bytes: &[u8], at: usize, class: u8) -> (usize, u8) { + let mut seen = 0; + let end = bytes + .get(at..) + .unwrap_or_default() + .iter() + .position(|&byte| { + let found = CLASSES[usize::from(byte)]; + seen |= found; + found & class == 0 + }) + .map_or(bytes.len(), |len| at + len); + (end, seen) +} + +fn name_token(bytes: &[u8], at: usize) -> Option<Token> { + let (end, seen) = run_of(bytes, at, NAME); + (end > at).then_some(Token { + start: at, + end, + upper: seen & UPPER != 0, + }) +} + +static VALUE_STOPS: ByteSet = ByteSet::excluding(&CLASSES, VALUE); +static QUOTED_STOPS: ByteSet = ByteSet::excluding(&CLASSES, QUOTED); + +fn value_end(kernel: Kernel, bytes: &[u8], mut at: usize, stops: &ByteSet) -> Option<usize> { + loop { + let end = kernel + .first_in_set(stops, bytes, at, bytes.len()) + .unwrap_or(bytes.len()); + match bytes.get(end..).unwrap_or_default() { + [b'=', b'?', ..] => return None, + [b'=', ..] => at = end + 1, + _ => return Some(end), + } + } +} + +fn skip_blank(bytes: &[u8], mut at: usize) -> usize { + loop { + match bytes.get(at..).unwrap_or_default() { + [b' ' | b'\t', ..] => at += 1, + [b'\n', b' ' | b'\t', ..] => at += 2, + [b'\r', b'\n', b' ' | b'\t', ..] => at += 3, + _ => return at, + } + } +} + +fn skip_space(bytes: &[u8], mut at: usize) -> usize { + while matches!(bytes.get(at), Some(b' ' | b'\t')) { + at += 1; + } + at +} + +fn at_end(bytes: &[u8], at: usize) -> bool { + matches!( + bytes.get(at..).unwrap_or_default(), + [] | [b'\n', ..] | [b'\r', b'\n', ..] + ) +} + +fn simple_shape(kernel: Kernel, bytes: &[u8]) -> Option<Simple> { + let ctype = name_token(bytes, skip_blank(bytes, 0))?; + let mut simple = Simple { + ctype, + subtype: None, + params: [SimpleParam::default(); MAX_SIMPLE_PARAMS], + len: 0, + }; + let mut at = ctype.end; + if bytes.get(at) == Some(&b'/') { + let subtype = name_token(bytes, at + 1)?; + simple.subtype = Some(subtype); + at = subtype.end; + } + loop { + at = skip_blank(bytes, at); + if at_end(bytes, at) { + return Some(simple); + } + if bytes.get(at) != Some(&b';') { + return None; + } + at = skip_blank(bytes, at + 1); + if at_end(bytes, at) { + return Some(simple); + } + let name = name_token(bytes, at)?; + at = skip_space(bytes, name.end); + if bytes.get(at) != Some(&b'=') { + return None; + } + at = skip_space(bytes, at + 1); + let value = if bytes.get(at) == Some(&b'"') { + let end = value_end(kernel, bytes, at + 1, "ED_STOPS)?; + if bytes.get(end) != Some(&b'"') { + return None; + } + let value = (at + 1, end); + at = end + 1; + (end > value.0).then_some(value) + } else { + let end = value_end(kernel, bytes, at, &VALUE_STOPS)?; + if end == at { + return None; + } + let value = (at, end); + at = end; + Some(value) + }; + *simple.params.get_mut(simple.len)? = SimpleParam { name, value }; + simple.len += 1; + } +} + +fn parse_simple(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Option<Value> { + let base = value.start; + let simple = simple_shape(ctx.kernel(), ctx.src().get(value)?)?; + let lowercase = |ctx: &mut FieldCtx<'_>, token: Token| { + ctx.lowercase_scanned(base + token.start..base + token.end, token.upper) + }; + let ctype = lowercase(ctx, simple.ctype); + let subtype = simple.subtype.map(|subtype| lowercase(ctx, subtype)); + let params = ctx.params_mark(); + for param in simple.params.get(..simple.len).unwrap_or_default() { + let name = lowercase(ctx, param.name); + if let Some((start, end)) = param.value { + let value = ctx.borrow(base + start..base + end); + ctx.push_param(name, value); + } + } + Some(ctx.content_type(ctype, subtype, params)) +} + +pub(crate) fn parse_content_type(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + match parse_simple(ctx, value.clone()) { + Some(parsed) => parsed, + None => parse_state_machine(ctx, value), + } +} + +fn parse_state_machine(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + let src = ctx.src(); + let end = value.end.min(src.len()); + let mut parser = Parser { + state: State::Type, + outer_state: State::Type, + comment_depth: 0, + c_type: None, + c_subtype: None, + attr_name: None, + attr_charset: None, + attr_position: 0, + params: ctx.params_mark(), + sections: ctx.data.scratch.continuations.len(), + budget: MAX_PARAMS, + has_continued: false, + has_languages: false, + token: None, + values: ctx.take_text_scratch(), + has_values: false, + is_continuation: false, + is_encoded_attribute: false, + is_escaped: false, + remove_crlf: false, + is_token_start: true, + apostrophes: 0, + }; + + let mut pos = value.start; + while let Some(&ch) = src.get(pos).filter(|_| pos < end) { + let index = pos; + pos += 1; + match ch { + b' ' | b'\t' => { + parser.is_token_start = true; + if parser.state == State::AttributeQuotedValue { + parser.extend_token(index); + } + continue; + } + b'\n' => { + let next_is_space = pos < end && matches!(src.get(pos), Some(b' ' | b'\t')); + match parser.state { + State::Type | State::AttributeName | State::SubType => { + parser.add_attribute(ctx); + } + State::AttributeValue => parser.add_value(ctx), + State::AttributeQuotedValue => { + if next_is_space { + pos += 1; + parser.remove_crlf = true; + continue; + } + parser.add_value(ctx); + } + State::Comment => (), + } + if next_is_space { + if parser.state == State::Type { + continue; + } + parser.state = State::AttributeName; + pos += 1; + parser.is_token_start = true; + continue; + } + return parser.finish(ctx); + } + b'/' if parser.state == State::Type => { + parser.add_attribute(ctx); + parser.state = State::SubType; + continue; + } + b';' => match parser.state { + State::Type | State::SubType | State::AttributeName => { + parser.add_attribute(ctx); + parser.state = State::AttributeName; + continue; + } + State::AttributeValue => { + if !parser.is_escaped { + parser.add_value(ctx); + parser.state = State::AttributeName; + } else { + parser.is_escaped = false; + } + continue; + } + _ => (), + }, + b'*' if parser.state == State::AttributeName => { + if !parser.is_continuation { + parser.is_continuation = parser.add_attribute(ctx); + } else if !parser.is_encoded_attribute { + parser.add_attr_position(ctx); + parser.is_encoded_attribute = true; + } else { + parser.reset(); + } + continue; + } + b'=' => match parser.state { + State::AttributeName => { + if !parser.is_continuation { + if !parser.add_attribute(ctx) { + continue; + } + } else if !parser.is_encoded_attribute { + parser.is_encoded_attribute = !parser.add_attr_position(ctx); + } else { + parser.reset(); + } + parser.state = State::AttributeValue; + parser.apostrophes = 0; + continue; + } + State::AttributeValue | State::AttributeQuotedValue + if parser.is_token_start && src.get(pos) == Some(&b'?') => + { + if let Some(consumed) = parser.encoded_word(ctx, index, end) { + pos = index + consumed; + continue; + } + } + _ => (), + }, + b'"' => match parser.state { + State::AttributeValue => { + parser.is_token_start = true; + parser.state = State::AttributeQuotedValue; + continue; + } + State::AttributeQuotedValue => { + if !parser.is_escaped { + parser.add_value(ctx); + parser.state = State::AttributeName; + continue; + } + parser.is_escaped = false; + } + _ => continue, + }, + b'\\' => match parser.state { + State::AttributeQuotedValue | State::AttributeValue => { + if !parser.is_escaped { + parser.add_partial_value(ctx, Some(index)); + parser.is_escaped = true; + continue; + } + parser.is_escaped = false; + } + State::Comment => parser.is_escaped = !parser.is_escaped, + _ => continue, + }, + b'\'' + if parser.is_encoded_attribute + && !parser.is_escaped + && parser.apostrophes < 2 + && matches!( + parser.state, + State::AttributeValue | State::AttributeQuotedValue + ) => + { + parser.add_attribute_parameter(ctx); + continue; + } + b'(' if parser.state != State::AttributeQuotedValue => { + if !parser.is_escaped { + match parser.state { + State::Type | State::AttributeName | State::SubType => { + parser.add_attribute(ctx); + } + State::AttributeValue => parser.add_value(ctx), + _ => (), + } + if parser.state == State::Comment { + parser.comment_depth += 1; + } else { + parser.outer_state = parser.state; + parser.comment_depth = 1; + parser.state = State::Comment; + } + } else { + parser.is_escaped = false; + } + continue; + } + b')' if parser.state == State::Comment => { + if !parser.is_escaped { + parser.comment_depth -= 1; + if parser.comment_depth == 0 { + parser.state = parser.outer_state; + } + parser.reset(); + } else { + parser.is_escaped = false; + } + continue; + } + b'\r' => continue, + _ => (), + } + + parser.is_escaped = false; + parser.is_token_start = false; + parser.extend_token(index); + } + + match parser.state { + State::Type | State::AttributeName | State::SubType => { + parser.add_attribute(ctx); + } + State::AttributeValue | State::AttributeQuotedValue => parser.add_value(ctx), + State::Comment => (), + } + parser.finish(ctx) +} + +impl Parser { + fn reset(&mut self) { + self.token = None; + self.is_token_start = true; + } + + fn extend_token(&mut self, index: usize) { + match &mut self.token { + Some((_, end)) => *end = index + 1, + None => self.token = Some((index, index + 1)), + } + } + + fn add_attribute(&mut self, ctx: &mut FieldCtx<'_>) -> bool { + let Some((start, end)) = self.token else { + return false; + }; + let attribute = ctx.lowercase(start..end); + match self.state { + State::AttributeName => self.attr_name = Some(attribute), + State::Type => self.c_type = Some(attribute), + State::SubType => self.c_subtype = Some(attribute), + _ => (), + } + self.reset(); + true + } + + fn add_attribute_parameter(&mut self, ctx: &mut FieldCtx<'_>) { + self.apostrophes += 1; + let Some((start, end)) = self.token else { + return; + }; + let part = ctx.borrow(start..end); + if self.attr_charset.is_none() { + self.attr_charset = Some(part); + } else if self.take_budget() { + let name = language_name(ctx, self.attr_name); + let index = self.param_count(ctx); + ctx.push_param(name, part); + record( + ctx, + name, + Key::new(Class::Language, index, Kind::Plain), + Str::NONE, + ); + self.has_languages = true; + } + self.reset(); + } + + fn take_budget(&mut self) -> bool { + let available = self.budget > 0; + self.budget = self.budget.saturating_sub(1); + available + } + + fn param_count(&self, ctx: &FieldCtx<'_>) -> u32 { + ctx.params_since(self.params).len() as u32 + } + + fn add_partial_value(&mut self, ctx: &FieldCtx<'_>, backslash: Option<usize>) { + let Some((start, end)) = self.token else { + return; + }; + let in_quote = self.state == State::AttributeQuotedValue; + let end = match backslash { + Some(backslash) if in_quote => backslash, + _ => end, + }; + push_lossy(&mut self.values, ctx.bytes(start..end)); + if !in_quote { + self.values.push(' '); + } + self.has_values = true; + self.reset(); + } + + fn encoded_word(&mut self, ctx: &mut FieldCtx<'_>, at: usize, end: usize) -> Option<usize> { + let (word, consumed) = EncodedWord::parse(ctx.bytes(at..end))?; + let mut bytes = ctx.take_bytes_scratch(); + let decoded = word.decode_append(&mut bytes).is_ok(); + if decoded { + self.add_partial_value(ctx, None); + charsets::decode_append(word.charset, &bytes, &mut self.values); + self.has_values = true; + } + ctx.put_bytes_scratch(bytes); + decoded.then_some(consumed) + } + + fn add_value(&mut self, ctx: &mut FieldCtx<'_>) { + let Some(attr_name) = self.attr_name else { + return; + }; + let has_values = self.has_values; + if self.token.is_none() && !has_values { + return; + } + let value = match self.token { + Some((start, end)) if self.remove_crlf => { + self.remove_crlf = false; + let mut filtered = ctx.take_bytes_scratch(); + filtered.extend( + ctx.bytes(start..end) + .iter() + .filter(|&&byte| byte != b'\r' && byte != b'\n'), + ); + let text = if has_values { + push_lossy(&mut self.values, &filtered); + ctx.push_str(&self.values) + } else { + ctx.push_with(|pool| push_lossy(pool, &filtered)) + }; + ctx.put_bytes_scratch(filtered); + text + } + Some((start, end)) if has_values => { + push_lossy(&mut self.values, ctx.bytes(start..end)); + ctx.push_str(&self.values) + } + Some((start, end)) => ctx.borrow(start..end), + None => ctx.push_str(&self.values), + }; + self.values.clear(); + self.has_values = false; + self.attr_name = None; + + if !self.is_continuation { + if self.take_budget() { + ctx.push_param(attr_name, value); + } + } else { + let encoded = std::mem::take(&mut self.is_encoded_attribute); + let charset = self.attr_charset.take().filter(|_| encoded); + let position = std::mem::take(&mut self.attr_position); + self.is_continuation = false; + if self.take_budget() { + let (class, index) = if position > 0 { + self.has_continued = true; + (Class::Continued, position) + } else { + let index = self.param_count(ctx); + let decoded = if encoded { + self.decode_extended(ctx, value, charset) + } else { + value + }; + ctx.push_param(attr_name, decoded); + (Class::First, index) + }; + if let Some(charset) = charset { + record( + ctx, + attr_name, + Key::new(class, index, Kind::Charset), + charset, + ); + } + let kind = if encoded { Kind::Encoded } else { Kind::Plain }; + record(ctx, attr_name, Key::new(class, index, kind), value); + } + } + self.reset(); + } + + fn decode_extended(&mut self, ctx: &mut FieldCtx<'_>, value: Str, charset: Option<Str>) -> Str { + let mut bytes = ctx.take_bytes_scratch(); + let decoded = percent_decode_append(ctx.resolve(value).as_bytes(), &mut bytes); + if decoded { + let label = charset.map_or("", |charset| ctx.resolve(charset)); + charsets::decode_append(label.as_bytes(), &bytes, &mut self.values); + } + ctx.put_bytes_scratch(bytes); + let text = if decoded && self.values != ctx.resolve(value) { + ctx.push_str(&self.values) + } else { + value + }; + self.values.clear(); + text + } + + fn add_attr_position(&mut self, ctx: &FieldCtx<'_>) -> bool { + let Some((start, end)) = self.token else { + return false; + }; + self.attr_position = std::str::from_utf8(ctx.bytes(start..end)) + .ok() + .and_then(|text| text.parse().ok()) + .unwrap_or(0); + self.reset(); + true + } + + fn finish(self, ctx: &mut FieldCtx<'_>) -> Value { + let Parser { + c_type, + c_subtype, + params, + sections, + has_continued, + has_languages, + values, + .. + } = self; + ctx.put_text_scratch(values); + if has_continued || has_languages { + assemble(ctx, params, sections); + } + ctx.data.scratch.continuations.truncate(sections); + match c_type { + Some(c_type) => ctx.content_type(c_type, c_subtype, params), + None => { + ctx.rollback_params(params); + Value::Empty + } + } + } +} + +fn record(ctx: &mut FieldCtx<'_>, name: Str, key: Key, value: Str) { + ctx.data.scratch.continuations.push((name, key.0, value)); +} + +fn language_name(ctx: &mut FieldCtx<'_>, attr: Option<Str>) -> Str { + let mut name = ctx.take_bytes_scratch(); + name.extend_from_slice(attr.map_or("unknown", |attr| ctx.resolve(attr)).as_bytes()); + name.extend_from_slice(LANGUAGE_SUFFIX); + let text = ctx.push_lossy(&name); + ctx.put_bytes_scratch(name); + text +} + +fn assemble(ctx: &mut FieldCtx<'_>, params: u32, mark: usize) { + let mut entries = std::mem::take(&mut ctx.data.scratch.continuations); + entries.extend( + ctx.params_since(params) + .iter() + .zip(0..) + .map(|(param, index)| { + ( + param.name, + Key::new(Class::Param, index, Kind::Plain).0, + Str::NONE, + ) + }), + ); + let mut text = ctx.take_text_scratch(); + let mut bytes = ctx.take_bytes_scratch(); + let mut removed = false; + if let Some(ours) = entries.get_mut(mark..) { + ours.sort_unstable_by(|a, b| { + ctx.resolve(a.0) + .cmp(ctx.resolve(b.0)) + .then(a.1.cmp(&b.1)) + .then_with(|| ctx.resolve(a.2).cmp(ctx.resolve(b.2))) + }); + let mut rest: &[Entry] = ours; + while let Some(first) = rest.first() { + let name = ctx.resolve(first.0); + let len = rest + .iter() + .take_while(|entry| ctx.resolve(entry.0) == name) + .count(); + let (run, tail) = rest.split_at(len); + rest = tail; + removed |= assemble_run(ctx, params, run, &mut text, &mut bytes); + } + } + if removed { + ctx.drop_removed_params(params); + } + ctx.put_text_scratch(text); + ctx.put_bytes_scratch(bytes); + ctx.data.scratch.continuations = entries; +} + +fn assemble_run( + ctx: &mut FieldCtx<'_>, + params: u32, + run: &[Entry], + text: &mut String, + bytes: &mut Vec<u8>, +) -> bool { + let first = run + .first() + .map(Key::of) + .filter(|key| key.class() == Class::Param) + .map(Key::index); + let mut removed = false; + for key in run.iter().map(Key::of) { + if key.class() == Class::Language && Some(key.index()) != first { + ctx.remove_param(params + key.index()); + removed = true; + } + } + let Some(continued) = run + .iter() + .position(|entry| Key::of(entry).class() == Class::Continued) + else { + return removed; + }; + let (head, continuations) = run.split_at(continued); + let leading = head.iter().filter(|entry| { + let key = Key::of(entry); + key.class() == Class::First && Some(key.index()) == first + }); + text.clear(); + if let Some(index) = first + && leading.clone().next().is_none() + && let Some(base) = ctx.params_since(params + index).first() + { + text.push_str(ctx.resolve(base.value)); + } + let sections = leading.chain(continuations); + let charset = sections + .clone() + .find(|entry| Key::of(entry).kind() == Kind::Charset) + .map(|entry| entry.2); + join_sections(ctx, sections, charset, text, bytes); + let value = ctx.push_str(text); + match first { + Some(index) => ctx.set_param_value(params + index, value), + None => { + if let Some(&(name, ..)) = run.first() { + ctx.push_param(name, value); + } + } + } + removed +} + +fn join_sections<'e>( + ctx: &FieldCtx<'_>, + sections: impl Iterator<Item = &'e Entry>, + charset: Option<Str>, + text: &mut String, + bytes: &mut Vec<u8>, +) { + let label = charset + .map_or("", |charset| ctx.resolve(charset)) + .as_bytes(); + for entry in sections { + let raw = ctx.resolve(entry.2); + match Key::of(entry).kind() { + Kind::Charset => {} + Kind::Encoded if percent_decode_append(raw.as_bytes(), bytes) => {} + Kind::Encoded | Kind::Plain => { + flush_encoded(label, bytes, text); + text.push_str(raw); + } + } + } + flush_encoded(label, bytes, text); +} + +fn flush_encoded(label: &[u8], bytes: &mut Vec<u8>, text: &mut String) { + if !bytes.is_empty() { + charsets::decode_append(label, bytes, text); + bytes.clear(); + } +} + +#[cfg(test)] +mod tests { + use super::{parse_simple, parse_state_machine}; + use crate::{ + HeaderName, MessageParser, + fields::{FieldCtx, tests::load_tests}, + scan::{ + Kernel, + tests::{Rng, fixture_files}, + }, + store::{MessageData, Value}, + }; + + type Parsed = Option<(String, Option<String>, Vec<(String, String)>)>; + + fn resolve(data: &MessageData, input: &[u8], value: Value) -> Parsed { + let Value::ContentType(index) = value else { + return None; + }; + let entry = data.content_types.get(index as usize)?; + let text = |text: crate::store::Str| text.resolve(input, &data.strings).to_string(); + Some(( + text(entry.ctype), + entry + .subtype + .resolve_option(input, &data.strings) + .map(str::to_string), + data.params + .get(entry.params.range()) + .unwrap_or_default() + .iter() + .map(|param| (text(param.name), text(param.value))) + .collect(), + )) + } + + fn compare(input: &[u8]) -> bool { + let mut slow = MessageData::default(); + let expected = parse_state_machine(&mut FieldCtx::new(input, &mut slow), 0..input.len()); + let mut accepted = false; + for kernel in Kernel::available() { + let mut fast = MessageData::default(); + let Some(value) = parse_simple( + &mut FieldCtx::with_kernel(input, &mut fast, kernel), + 0..input.len(), + ) else { + assert!(!accepted, "{:?}", String::from_utf8_lossy(input)); + continue; + }; + accepted = true; + assert_eq!( + resolve(&fast, input, value), + resolve(&slow, input, expected), + "{} {:?}", + kernel.name(), + String::from_utf8_lossy(input) + ); + assert_eq!( + fast.strings, + slow.strings, + "{} {:?}", + kernel.name(), + String::from_utf8_lossy(input) + ); + } + accepted + } + + #[test] + fn simple_shapes_match_the_state_machine() { + let mut inputs: Vec<Vec<u8>> = load_tests("content_type.json") + .into_iter() + .map(|(header, _)| header.into_bytes()) + .collect(); + for sample in [ + &b" text/plain; charset=us-ascii\r\n"[..], + b" text/plain; charset=\"iso-8859-1\"\r\n", + b" multipart/alternative;\r\n\tboundary=\"----=_NextPart_000_0001\"\r\n", + b" TEXT/HTML; Charset=UTF-8\n", + b" attachment; filename=\"report (1).pdf\"; size=12\r\n", + b" inline\r\n", + b" inline ; x=y\r\n", + b" text/plain;\r\n", + b" text/plain; name=\"\"\r\n", + b" text/plain; name=\"\"; x=1\r\n", + b" text/plain\r\n ; charset=x\r\n", + b" text/plain\r\n charset=x\r\n", + b" text/plain; charset =x\r\n", + b" text/plain; charset= x\r\n", + b" text/plain; charset=\r\n x\r\n", + b" text/plain; boundary=Apple-Mail=_D9E8-1\r\n", + b" text/plain; name==?utf-8?q?a?=\r\n", + b" text/plain; name=\"=?utf-8?q?a?=\"\r\n", + b" text/plain; name*=utf-8''a\r\n", + b" text/plain; a=1; b=2; c=3; d=4; e=5; f=6; g=7; h=8; i=9\r\n", + b" text/plain; charset=utf 8\r\n", + b" text/plain (comment)\r\n", + b" text/plain; name=caf\xc3\xa9\r\n", + b" text/plain; name=caf\xe9\r\n", + b" t\xe9xt/plain\r\n", + b" text/plain; x=\"a\\\"b\"\r\n", + b" text/plain; x=\"unterminated\r\n", + b" text/plain\rx\r\n", + b"text/plain", + b"", + b" \r\n", + b" text/; x=y\r\n", + b" text/plain/extra\r\n", + b" \"text/plain\"\r\n", + b" text/plain; x=y)z\r\n", + b" text/plain; x=[a]@b:c,d<e>?\r\n", + b" text/plain;; x=y\r\n", + b" text/plain; x=y\r\n\r\nbody", + b" text/plain; x=y\nX-Other: z\n", + b" multipart/related; boundary=\"----=_Part_4521_1234567890.1700000000000\"; type=\"text/html\"\r\n", + b" multipart/mixed; boundary=--_com.android.email_1234567890123456789\r\n", + b" multipart/mixed; boundary=\"0000000000001234567890abcdef\x01tail\"\r\n", + b" multipart/mixed; boundary=\"0000000000001234567890abcdef\\\"tail\"\r\n", + b" multipart/mixed; boundary=0000000000001234567890abcdef(comment)\r\n", + b" multipart/mixed; boundary=0000000000001234567890abcdef=?x?q?y?=\r\n", + ] { + inputs.push(sample.to_vec()); + } + for message in fixture_files() { + let Some(parsed) = MessageParser::new().parse(&message) else { + continue; + }; + for part in parsed.parts() { + for header in part.headers().iter() { + if matches!( + header.name(), + HeaderName::ContentType | HeaderName::ContentDisposition + ) { + inputs.push(header.raw_value().to_vec()); + } + } + } + } + let accepted = inputs.iter().filter(|input| compare(input)).count(); + assert!( + accepted >= inputs.len() / 2, + "{accepted} of {}", + inputs.len() + ); + let alphabet = b"aZ/;=\" \t\r\n()*'\\?_-.\xc3\xa9"; + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for input in &inputs { + for _ in 0..100 { + let mut mutated = input.clone(); + for _ in 0..1 + rng.below(3) { + let at = rng.below(mutated.len() + 1); + let byte = alphabet + .get(rng.below(alphabet.len())) + .copied() + .unwrap_or(b'a'); + if rng.below(2) == 0 && at < mutated.len() { + if let Some(slot) = mutated.get_mut(at) { + *slot = byte; + } + } else { + mutated.insert(at, byte); + } + } + compare(&mutated); + } + } + } +} diff --git a/src/fields/date.rs b/src/fields/date.rs new file mode 100644 index 0000000..083dd08 --- /dev/null +++ b/src/fields/date.rs @@ -0,0 +1,762 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::FieldCtx; +use crate::{DateTime, store::Value}; +use std::{ops::Range, slice::Iter}; + +const SLOTS: usize = 7; +const MONTH_SLOT: usize = 1; +const ZONE_SLOT: usize = 6; +const WIDTHS: [u32; SLOTS] = [2, 2, 4, 2, 2, 2, 4]; +const POW10: [u32; 5] = [1, 10, 100, 1000, 10000]; +const FIXED_TAIL: usize = 23; +const LANES: u64 = 0x0101_0101_0101_0101; +const HIGH_BITS: u64 = 0x8080_8080_8080_8080; +const DIGIT_CEILING: u64 = 0x7676_7676_7676_7676; +const MONTH_YEAR: Layout = Layout::new(b"??? DDDD"); +const TIME: Layout = Layout::new(b" DD:DD:D"); +const SECOND_ZONE: Layout = Layout::new(b"DD ?DDDD"); + +static LETTER_HASH: [u8; 26] = [ + 0, 14, 4, 31, 10, 31, 14, 31, 31, 31, 31, 4, 31, 10, 15, 15, 31, 5, 31, 0, 5, 15, 31, 31, 0, 31, +]; + +static MONTH_MAP: [u8; 31] = [ + 5, 0, 0, 0, 10, 3, 0, 0, 0, 7, 1, 0, 0, 0, 12, 6, 0, 0, 0, 8, 4, 0, 0, 0, 2, 9, 0, 0, 0, 0, 11, +]; + +pub(crate) fn parse_date(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + parse_bytes(ctx.bytes(value)).map_or(Value::Empty, Value::DateTime) +} + +pub(crate) fn parse_bytes(bytes: &[u8]) -> Option<DateTime> { + canonical(bytes).or_else(|| Scanner::scan(bytes)) +} + +fn canonical(bytes: &[u8]) -> Option<DateTime> { + let rest = skip_day_name(skip_space(bytes))?; + let (day, rest) = match rest { + [d1 @ b'0'..=b'9', d2 @ b'0'..=b'9', rest @ ..] => (two_digits(*d1, *d2), rest), + [d1 @ b'0'..=b'9', rest @ ..] => (u32::from(d1 - b'0'), rest), + _ => return None, + }; + let rest = separator(rest)?; + if let Some(date) = fixed_tail(day, rest) { + return Some(date); + } + let (month, rest) = month_name(rest)?; + let (year, rest) = match separator(rest)? { + [ + y1 @ b'0'..=b'9', + y2 @ b'0'..=b'9', + y3 @ b'0'..=b'9', + y4 @ b'0'..=b'9', + rest @ .., + ] => (two_digits(*y1, *y2) * 100 + two_digits(*y3, *y4), rest), + rest => number(rest, 4)?, + }; + let (hour, minute, second, rest) = match separator(rest)? { + [ + h1 @ b'0'..=b'9', + h2 @ b'0'..=b'9', + b':', + m1 @ b'0'..=b'9', + m2 @ b'0'..=b'9', + b':', + s1 @ b'0'..=b'9', + s2 @ b'0'..=b'9', + rest @ .., + ] => ( + two_digits(*h1, *h2), + two_digits(*m1, *m2), + Some(two_digits(*s1, *s2)), + rest, + ), + rest => time(rest)?, + }; + let (tz_before_gmt, zone) = match separator(rest)? { + [ + sign @ (b'+' | b'-'), + h1 @ b'0'..=b'9', + h2 @ b'0'..=b'9', + m1 @ b'0'..=b'9', + m2 @ b'0'..=b'9', + rest @ .., + ] => { + numeric_zone_end(rest)?; + ( + *sign == b'-', + two_digits(*h1, *h2) * 100 + two_digits(*m1, *m2), + ) + } + [letter, rest @ ..] if second.is_some() && letter.is_ascii_alphabetic() => { + let (key, rest) = obs_key(*letter, rest); + inert(rest)?; + let zone = obs_zone(key); + (zone < 0, 100 * zone.unsigned_abs()) + } + _ => return None, + }; + Some(date_time( + [day, 0, year, hour, minute, second.unwrap_or(0), zone], + month, + tz_before_gmt, + )) +} + +fn date_time(parts: [u32; SLOTS], month: u8, tz_before_gmt: bool) -> DateTime { + let [day, _, year, hour, minute, second, zone] = parts; + DateTime { + year: match year { + 0..=49 => year + 2000, + 50..=99 => year + 1900, + _ => year, + } as u16, + month, + day: day as u8, + hour: hour as u8, + minute: minute as u8, + second: second as u8, + tz_before_gmt, + tz_hour: ((zone / 100) % 24) as u8, + tz_minute: ((zone % 100) % 60) as u8, + } +} + +fn fixed_tail(day: u32, bytes: &[u8]) -> Option<DateTime> { + let (block, trailer) = bytes.split_first_chunk::<FIXED_TAIL>()?; + let (&month_year, rest) = block.split_first_chunk::<8>()?; + let (&time, _) = rest.split_first_chunk::<8>()?; + let (_, &second_zone) = block.split_last_chunk::<8>()?; + let month_year = MONTH_YEAR.digits(month_year)?; + let time = TIME.digits(time)?; + let second_zone = SECOND_ZONE.digits(second_zone)?; + let &[.., sign @ (b'+' | b'-'), _, _, _, _] = block else { + return None; + }; + let (month, _) = month_name(block)?; + numeric_zone_end(trailer)?; + Some(date_time( + [ + day, + 0, + lanes(month_year, 4, 4), + lanes(time, 1, 2), + lanes(time, 4, 2), + lanes(second_zone, 0, 2), + lanes(second_zone, 4, 4), + ], + month, + sign == b'-', + )) +} + +struct Layout { + template: u64, + fixed: u64, + digits: u64, +} + +impl Layout { + const fn new(pattern: &[u8; 8]) -> Layout { + let mut layout = Layout { + template: 0, + fixed: 0, + digits: 0, + }; + let mut rest: &[u8] = pattern; + let mut shift = 0; + while let [byte, tail @ ..] = rest { + match *byte { + b'D' => { + layout.template |= (b'0' as u64) << shift; + layout.digits |= 0xff << shift; + } + b'?' => {} + other => { + layout.template |= (other as u64) << shift; + layout.fixed |= 0xff << shift; + } + } + shift += 8; + rest = tail; + } + layout + } + + fn digits(&self, word: [u8; 8]) -> Option<u64> { + let diff = u64::from_le_bytes(word) ^ self.template; + let values = diff & self.digits; + let out_of_range = (values.wrapping_add(DIGIT_CEILING) | values) & self.digits & HIGH_BITS; + (diff & self.fixed == 0 && out_of_range == 0).then_some(values) + } +} + +fn lanes(word: u64, first: u32, count: u32) -> u32 { + (first..first + count).fold(0, |value, lane| { + value * 10 + ((word >> (lane * 8)) & 0xff) as u32 + }) +} + +fn two_digits(tens: u8, units: u8) -> u32 { + u32::from(tens - b'0') * 10 + u32::from(units - b'0') +} + +fn time(bytes: &[u8]) -> Option<(u32, u32, Option<u32>, &[u8])> { + let (hour, rest) = number(bytes, 2)?; + let (minute, rest) = number(rest.strip_prefix(b":")?, 2)?; + match rest { + [b':', rest @ ..] => { + let (second, rest) = number(rest, 2)?; + Some((hour, minute, Some(second), rest)) + } + _ => Some((hour, minute, None, rest)), + } +} + +fn skip_space(mut bytes: &[u8]) -> &[u8] { + while let [b' ' | b'\t' | b'\r', rest @ ..] | [b'\n', b' ' | b'\t', rest @ ..] = bytes { + bytes = rest; + } + bytes +} + +fn separator(mut bytes: &[u8]) -> Option<&[u8]> { + let mut closed = false; + loop { + match bytes { + [b' ' | b'\t', rest @ ..] | [b'\n', b' ' | b'\t', rest @ ..] => { + closed = true; + bytes = rest; + } + [b'\r', rest @ ..] => bytes = rest, + _ => return closed.then_some(bytes), + } + } +} + +fn skip_day_name(bytes: &[u8]) -> Option<&[u8]> { + match bytes { + [b'0'..=b'9', ..] => Some(bytes), + [first, second, third, b',', rest @ ..] + if first.is_ascii_alphabetic() + && second.is_ascii_alphabetic() + && third.is_ascii_alphabetic() => + { + Some(skip_space(rest)) + } + [first, ..] if first.is_ascii_alphabetic() => { + let mut rest = bytes; + while let [letter, tail @ ..] = rest + && letter.is_ascii_alphabetic() + { + rest = tail; + } + rest.strip_prefix(b",").map(skip_space) + } + _ => None, + } +} + +fn number(mut bytes: &[u8], max_digits: u32) -> Option<(u32, &[u8])> { + let mut value = 0; + let mut digits = 0; + while let [digit @ b'0'..=b'9', rest @ ..] = bytes { + digits += 1; + if digits > max_digits { + return None; + } + value = value * 10 + u32::from(digit - b'0'); + bytes = rest; + } + (digits > 0).then_some((value, bytes)) +} + +fn numeric_zone_end(bytes: &[u8]) -> Option<()> { + match bytes { + [] | [b'\n'] | [b'\r'] | [b'\r', b'\n'] => Some(()), + _ => { + separator(bytes)?; + inert(bytes) + } + } +} + +fn inert(bytes: &[u8]) -> Option<()> { + let (words, rest) = bytes.as_chunks::<8>(); + let effect = words + .iter() + .any(|&word| has_effect(u64::from_le_bytes(word))) + || rest.iter().any(|&byte| matches!(byte, b'+' | b'-' | b';')); + (!effect).then_some(()) +} + +fn has_effect(word: u64) -> bool { + b"+-;" + .iter() + .any(|&byte| has_zero_byte(word ^ (LANES * u64::from(byte)))) +} + +fn has_zero_byte(word: u64) -> bool { + word.wrapping_sub(LANES) & !word & HIGH_BITS != 0 +} + +fn month_name(bytes: &[u8]) -> Option<(u8, &[u8])> { + match bytes { + [first, second, third, rest @ ..] + if first.is_ascii_alphabetic() + && second.is_ascii_alphabetic() + && third.is_ascii_alphabetic() => + { + let month = month_number(letter_hash(*second) + letter_hash(*third)); + (month != 0).then_some((month, rest)) + } + _ => None, + } +} + +fn letter_hash(letter: u8) -> usize { + LETTER_HASH + .get(usize::from(letter.to_ascii_lowercase().wrapping_sub(b'a'))) + .map_or(31, |&hash| usize::from(hash)) +} + +fn month_number(hash: usize) -> u8 { + MONTH_MAP.get(hash).copied().unwrap_or(0) +} + +fn obs_key(letter: u8, bytes: &[u8]) -> ([u8; 3], &[u8]) { + match bytes { + [first, second, rest @ ..] => ([letter, *first, *second], rest), + [first] => ([letter, *first, 0], &[]), + [] => ([letter, 0, 0], &[]), + } +} + +fn obs_zone(key: [u8; 3]) -> i32 { + match &key { + b"EDT" => -4, + b"EST" | b"CDT" => -5, + b"CST" | b"MDT" => -6, + b"MST" | b"PDT" => -7, + b"PST" => -8, + _ => 0, + } +} + +fn pow10(exponent: u32) -> u32 { + POW10.get(exponent as usize).copied().unwrap_or(1) +} + +fn ends_with_sign_and_digit(mut bytes: &[u8]) -> bool { + while let [rest @ .., b'\r' | b'\n'] = bytes { + bytes = rest; + } + matches!(bytes, [.., b'+' | b'-', b'0'..=b'9']) +} + +fn skip_comment(iter: &mut Iter<'_, u8>) -> bool { + let mut depth = 1usize; + while let Some(&byte) = iter.next() { + match byte { + b')' => { + depth -= 1; + if depth == 0 { + return true; + } + } + b'(' => depth += 1, + b'\\' => { + if let [b')', rest @ ..] = iter.as_slice() { + *iter = rest.iter(); + } + } + b'\n' => match iter.as_slice() { + [b' ' | b'\t', rest @ ..] => *iter = rest.iter(), + _ => return false, + }, + _ => {} + } + } + false +} + +struct Scanner { + pos: usize, + parts: [u32; SLOTS], + widths: [u32; SLOTS], + month_hash: usize, + month_letters: usize, + tz_before_gmt: bool, + new_token: bool, + ignore: bool, +} + +impl Scanner { + const START: Scanner = Scanner { + pos: 0, + parts: [0; SLOTS], + widths: WIDTHS, + month_hash: 0, + month_letters: 0, + tz_before_gmt: false, + new_token: true, + ignore: true, + }; + + fn scan(bytes: &[u8]) -> Option<DateTime> { + let mut state = Scanner::START; + let mut in_comment = false; + let mut iter = bytes.iter(); + while let Some(&byte) = iter.next() { + match byte { + b'a'..=b'z' | b'A'..=b'Z' => { + state.new_token = false; + if state.pos == MONTH_SLOT { + if matches!(state.month_letters, 1 | 2) { + state.month_hash += letter_hash(byte); + } + state.month_letters += 1; + } else if state.pos == ZONE_SLOT { + let (key, rest) = obs_key(byte, iter.as_slice()); + iter = rest.iter(); + state.set_obs_zone(obs_zone(key)); + state.close_slot(); + } else { + while let [b'a'..=b'z' | b'A'..=b'Z', rest @ ..] = iter.as_slice() { + iter = rest.iter(); + } + } + } + b'0'..=b'9' => state.digit(byte - b'0'), + b' ' | b'\t' => { + if state.token_open() { + state.close_slot(); + } + } + b':' => { + if state.token_open() && matches!(state.pos, 3 | 4) { + state.close_slot(); + } + } + b'\n' => match iter.as_slice() { + [b' ' | b'\t', rest @ ..] => { + iter = rest.iter(); + if state.token_open() { + state.close_slot(); + } + } + _ => break, + }, + b'(' => { + state.new_token = true; + if !skip_comment(&mut iter) { + in_comment = true; + break; + } + } + b'+' => state.pos = ZONE_SLOT, + b'-' => { + state.tz_before_gmt = true; + state.pos = ZONE_SLOT; + } + b';' => state = Scanner::START, + _ => {} + } + } + state.finish(bytes, in_comment) + } + + fn token_open(&self) -> bool { + !self.new_token && !self.ignore + } + + fn digit(&mut self, digit: u8) { + if let (Some(part), Some(width)) = + (self.parts.get_mut(self.pos), self.widths.get_mut(self.pos)) + && *width > 0 + { + *width -= 1; + *part += u32::from(digit) * pow10(*width); + self.ignore = false; + } + self.new_token = false; + } + + fn close_slot(&mut self) { + if let (Some(part), Some(&width)) = + (self.parts.get_mut(self.pos), self.widths.get(self.pos)) + && width > 0 + { + *part /= pow10(width); + } + self.pos += 1; + self.new_token = true; + } + + fn set_obs_zone(&mut self, zone: i32) { + self.tz_before_gmt = zone < 0; + let [.., part] = &mut self.parts; + *part = 100 * zone.unsigned_abs(); + let [.., width] = &mut self.widths; + *width = 0; + } + + fn finish(&self, bytes: &[u8], in_comment: bool) -> Option<DateTime> { + if self.pos < ZONE_SLOT { + return None; + } + let [_, month, ..] = self.parts; + let month = if self.month_letters == 3 { + month_number(self.month_hash) + } else { + month as u8 + }; + if !(1..=12).contains(&month) { + return None; + } + let mut parts = self.parts; + let [.., width] = self.widths; + if self.pos == ZONE_SLOT && width == 3 && !in_comment && ends_with_sign_and_digit(bytes) { + let [.., zone] = &mut parts; + *zone /= 10; + } + Some(date_time(parts, month, self.tz_before_gmt)) + } +} + +#[cfg(test)] +mod tests { + use super::{Scanner, canonical}; + use crate::{DateTime, HeaderForm, fields::tests::load_tests}; + use chrono::{FixedOffset, MappedLocalTime, SecondsFormat, TimeZone, Utc}; + use serde_json::Value as Json; + + fn parse(input: &str) -> Option<DateTime> { + HeaderForm::Date + .parse(input.as_bytes()) + .value() + .as_datetime() + } + + fn expected(json: &Json) -> Option<DateTime> { + if json.is_null() { + return None; + } + let number = |name: &str| { + json.get(name) + .and_then(Json::as_u64) + .unwrap_or_else(|| panic!("fixture field {name}")) + }; + let small = |name: &str| u8::try_from(number(name)).expect("fits in u8"); + Some(DateTime { + year: u16::try_from(number("year")).expect("fits in u16"), + month: small("month"), + day: small("day"), + hour: small("hour"), + minute: small("minute"), + second: small("second"), + tz_before_gmt: json + .get("tz_before_gmt") + .and_then(Json::as_bool) + .expect("fixture field tz_before_gmt"), + tz_hour: small("tz_hour"), + tz_minute: small("tz_minute"), + }) + } + + fn check_with_chrono(input: &str, date: &DateTime) { + let offset = (i32::from(date.tz_hour) * 3600 + i32::from(date.tz_minute) * 60) + * if date.tz_before_gmt { 1 } else { -1 }; + let zone = FixedOffset::west_opt(offset) + .unwrap_or_else(|| FixedOffset::east_opt(0).expect("UTC is a valid offset")); + if let MappedLocalTime::Single(chrono_date) | MappedLocalTime::Ambiguous(chrono_date, _) = + zone.with_ymd_and_hms( + i32::from(date.year), + u32::from(date.month), + u32::from(date.day), + u32::from(date.hour), + u32::from(date.minute), + u32::from(date.second), + ) + { + let rfc3339 = |timestamp: i64| { + Utc.timestamp_opt(timestamp, 0) + .single() + .map(|utc| utc.to_rfc3339_opts(SecondsFormat::Secs, true)) + }; + assert_eq!( + chrono_date.timestamp(), + date.to_timestamp(), + "{} -> {} ({:?}) -> {} ({:?})", + input.escape_debug(), + date.to_timestamp(), + rfc3339(date.to_timestamp()), + chrono_date.timestamp(), + rfc3339(chrono_date.timestamp()), + ); + let timestamp = date.to_timestamp(); + assert_eq!( + DateTime::from_timestamp(timestamp).to_timestamp(), + timestamp + ); + } + } + + #[test] + fn parse_dates() { + let tests = load_tests("date.json"); + assert_eq!(tests.len(), 84); + for (header, expected_json) in tests { + let parsed = parse(&header); + assert_eq!(parsed, expected(&expected_json), "failed for {header:?}"); + if let Some(date) = parsed.filter(DateTime::is_valid) { + check_with_chrono(&header, &date); + } + } + } + + #[test] + fn datetime_to_timezone() { + let dt = DateTime::parse_rfc3339("2021-01-01T00:00:00Z").expect("valid date"); + + for (tz, expected) in [ + (0i64, "2021-01-01T00:00:00Z"), + (3600, "2021-01-01T01:00:00+01:00"), + (-3600, "2020-12-31T23:00:00-01:00"), + (19800, "2021-01-01T05:30:00+05:30"), + (-12600, "2020-12-31T20:30:00-03:30"), + (20700, "2021-01-01T05:45:00+05:45"), + (16200, "2021-01-01T04:30:00+04:30"), + (34200, "2021-01-01T09:30:00+09:30"), + (-45900, "2020-12-31T11:15:00-12:45"), + ] { + let converted = dt.to_timezone(tz); + assert_eq!(converted.to_rfc3339(), expected, "failed for tz {tz}"); + assert!(converted.is_valid(), "invalid datetime for tz {tz}"); + assert_eq!( + converted.to_timestamp(), + dt.to_timestamp(), + "roundtrip failed for tz {tz}" + ); + } + } + + #[test] + fn parse_rfc822() { + assert_eq!( + DateTime::parse_rfc822("Sat, 20 Nov 2021 14:22:01 -0800").map(|d| d.to_rfc3339()), + Some("2021-11-20T14:22:01-08:00".to_string()) + ); + assert_eq!(DateTime::parse_rfc822("not a date"), None); + assert_eq!(DateTime::parse_rfc822(""), None); + } + + const SAMPLES: [&str; 12] = [ + " Tue, 1 Jul 2003 10:52:37 +0200\n", + " Fri, 07 Oct 1994 16:15:05 -0700 (PDT)\r\n", + "Mon, 13 Aug 1998 17:42:41 +1000", + " 26 Jan 2002 13:00:00 -0800 (PST)\n", + " Sat, 30 Jun 2001 10:35:28 EDT\n", + "\n\t09 Mar 2011 11:19:46 -0000\n", + " \t Mon, 29 Oct 2001 14:47:10 -0500\t\n", + " Wed, 27 Jun 99 04:11 +0900 \n", + "Thu,\n 13\n Feb\n 1969\n 23:32\n -0330 (Newfoundland Time)\n", + " Wed, 9 Mar 2011 06:19:47 -0500 (EST)\n", + " Thu, 10 Jul 1997 14:53:31 Z\r\n", + " Thu, 10 Jul 1997 14:53:31 UT\n", + ]; + + fn variants(sample: &str) -> Vec<Vec<u8>> { + const REPLACEMENTS: &[&[u8]] = &[ + b" ", b"\t", b"\n", b"\r", b"\r\n", b"\n ", b"\r\n\t", b"(", b")", b"\\", b";", b"+", + b"-", b":", b",", b"0", b"9", b"A", b"z", b"\x80", b"", + ]; + const ZONES: &[&str] = &[ + "GMT", + "UT", + "UTC", + "Z", + "A", + "M", + "EST", + "EDT", + "CST", + "CDT", + "MST", + "MDT", + "PST", + "PDT", + "est", + "EST5EDT", + "+5", + "-5", + "+05", + "+530", + "-0000", + "+2400", + "+9999", + "+05:30", + "", + "(PDT)", + "-0700 (PDT)", + "+0200 +EST", + "-0700\n (PDT)", + "PDT-7", + ]; + let bytes = sample.as_bytes(); + let mut out = Vec::with_capacity(bytes.len() * (REPLACEMENTS.len() + 2) + ZONES.len()); + out.extend((0..=bytes.len()).filter_map(|end| bytes.get(..end).map(<[u8]>::to_vec))); + for (index, _) in bytes.iter().enumerate() { + for replacement in REPLACEMENTS { + let mut variant = Vec::with_capacity(bytes.len() + replacement.len()); + variant.extend_from_slice(bytes.get(..index).unwrap_or_default()); + variant.extend_from_slice(replacement); + variant.extend_from_slice(bytes.get(index + 1..).unwrap_or_default()); + out.push(variant); + } + } + let trimmed = sample.trim_end(); + if let Some((head, _)) = trimmed.rsplit_once(' ') { + out.extend( + ZONES + .iter() + .map(|zone| format!("{head} {zone}\n").into_bytes()), + ); + } + out + } + + #[test] + fn fast_path_matches_scanner() { + let mut fast = 0; + let mut total = 0; + let fixtures = load_tests("date.json"); + let inputs = SAMPLES + .iter() + .copied() + .chain(fixtures.iter().map(|(header, _)| header.as_str())); + for sample in inputs { + for variant in variants(sample) { + total += 1; + if let Some(date) = canonical(&variant) { + fast += 1; + assert_eq!( + Some(date), + Scanner::scan(&variant), + "{:?}", + String::from_utf8_lossy(&variant) + ); + } + } + } + assert!(fast * 10 > total, "fast path taken for {fast} of {total}"); + for sample in SAMPLES { + assert!(canonical(sample.as_bytes()).is_some(), "{sample:?}"); + } + } +} diff --git a/src/fields/id.rs b/src/fields/id.rs new file mode 100644 index 0000000..16c39fb --- /dev/null +++ b/src/fields/id.rs @@ -0,0 +1,165 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::FieldCtx; +use crate::store::Value; +use memchr::memchr2_iter; +use std::ops::Range; + +#[inline] +pub(crate) fn parse_id(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + let bytes = ctx.bytes(value.clone()); + let base = value.start; + let mark = ctx.text_items_mark(); + let mut open = None; + for at in memchr2_iter(b'<', b'>', bytes) { + match (open, bytes.get(at)) { + (None, Some(b'<')) => open = Some(at + 1), + (Some(start), Some(b'>')) => { + if let Some(id) = trim(bytes, start..at, is_id_byte) { + let item = ctx.borrow(base + id.start..base + id.end); + ctx.push_text_item(item); + } + open = None; + } + _ => (), + } + } + if ctx.text_items_mark() == mark + && let Some(bare) = bare_span(bytes) + { + let item = ctx.borrow(base + bare.start..base + bare.end); + ctx.push_text_item(item); + } + ctx.text_list(mark) +} + +fn is_id_byte(byte: &u8) -> bool { + !matches!(byte, b' ' | b'\t' | b'\r' | b'\n' | b'<') +} + +fn is_bare_byte(byte: &u8) -> bool { + !matches!(byte, b' ' | b'\t' | b'\r' | b'\n' | b'>') +} + +fn trim(bytes: &[u8], range: Range<usize>, keep: fn(&u8) -> bool) -> Option<Range<usize>> { + let span = bytes.get(range.clone())?; + let first = span.iter().position(keep)?; + let last = span.iter().rposition(keep)?; + Some(range.start + first..range.start + last + 1) +} + +fn bare_span(bytes: &[u8]) -> Option<Range<usize>> { + let mut bare: Option<Range<usize>> = None; + let mut extend = |segment: Range<usize>| { + if let Some(span) = trim(bytes, segment, is_bare_byte) { + bare = Some(bare.take().map_or(span.start, |bare| bare.start)..span.end); + } + }; + let mut outside = Some(0); + for at in memchr2_iter(b'<', b'>', bytes) { + match (outside, bytes.get(at)) { + (Some(start), Some(b'<')) => { + extend(start..at); + outside = None; + } + (None, Some(b'>')) => outside = Some(at + 1), + _ => (), + } + } + if let Some(start) = outside { + extend(start..bytes.len()); + } + bare +} + +#[cfg(test)] +pub(crate) mod tests { + use super::parse_id; + use crate::{ + HeaderForm, HeaderValue, + fields::{FieldCtx, tests::load_tests}, + store::{MessageData, Value}, + }; + use serde_json::Value as Json; + + pub(crate) type Items = Option<Vec<String>>; + pub(crate) type Case = (&'static [u8], Option<&'static [&'static str]>); + + const EDGE_CASES: &[Case] = &[ + (b"<a\xff@b>\n", Some(&["a\u{fffd}@b"])), + (b"x\xff <\n", Some(&["x\u{fffd}"])), + ]; + + pub(crate) fn items(value: HeaderValue<'_>) -> Items { + match value { + HeaderValue::Empty => None, + HeaderValue::TextList(list) => Some(list.iter().map(str::to_string).collect()), + other => Some(vec![format!("unexpected value shape {other:?}")]), + } + } + + pub(crate) fn expected_items(expected: &Json) -> Items { + expected.as_array().map(|list| { + list.iter() + .map(|item| item.as_str().unwrap_or_default().to_string()) + .collect() + }) + } + + pub(crate) fn case_items(expected: Option<&[&str]>) -> Items { + expected.map(|list| list.iter().map(|item| item.to_string()).collect()) + } + + fn parse(input: &[u8]) -> Items { + items(HeaderForm::MessageIds.parse(input).value()) + } + + #[test] + fn message_id_fixtures() { + let tests = load_tests("id.json"); + assert_eq!(tests.len(), 34); + for (header, expected) in tests { + assert_eq!( + parse(header.as_bytes()), + expected_items(&expected), + "{header:?}" + ); + } + } + + #[test] + fn message_id_edge_cases() { + for &(input, expected) in EDGE_CASES { + assert_eq!( + parse(input), + case_items(expected), + "{:?}", + String::from_utf8_lossy(input) + ); + } + let parsed = HeaderForm::MessageIds.parse(b" <single@id>\r\n"); + assert!(matches!(parsed.value(), HeaderValue::TextList(list) if list.len() == 1)); + let parsed = HeaderForm::MessageIds.parse(b" <a@b> <c@d>\r\n"); + assert_eq!(parsed.value().as_text(), Some("c@d")); + } + + #[test] + fn message_ids_borrow_unless_lossy() { + let source = b"Message-ID: <abc@host>\r\nReferences: <x\xff@y> <z@w>\r\n"; + let mut data = MessageData::default(); + assert!(matches!( + parse_id(&mut FieldCtx::new(source, &mut data), 11..24), + Value::TextList(_) + )); + assert!(data.strings.is_empty()); + assert!(matches!( + parse_id(&mut FieldCtx::new(source, &mut data), 36..source.len()), + Value::TextList(_) + )); + assert_eq!(data.strings, "x\u{fffd}@y"); + } +} diff --git a/src/fields/list.rs b/src/fields/list.rs new file mode 100644 index 0000000..c0f2c83 --- /dev/null +++ b/src/fields/list.rs @@ -0,0 +1,288 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{FieldCtx, push_utf8_lossy}; +use crate::{decoders::charsets, store::Value}; +use encodify::rfc2047::EncodedWord; +use memchr::{memchr, memchr_iter, memchr3, memmem}; +use std::{iter::once, ops::Range}; + +pub(crate) fn parse_comma_list(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + let mark = ctx.text_items_mark(); + let range = ctx.trim_fws(value); + let bytes = ctx.bytes(range.clone()); + if memchr3(b',', b'=', b'\n', bytes).is_none() { + if !range.is_empty() { + let text = ctx.borrow(range); + ctx.push_text_item(text); + } + } else if memchr_iter(b'=', bytes).any(|at| bytes.get(at + 1) == Some(&b'?')) { + ListParser::run(ctx, range); + } else { + let mut start = 0; + for end in memchr_iter(b',', bytes).chain(once(bytes.len())) { + push_plain_item(ctx, range.start + start..range.start + end); + start = end + 1; + } + } + ctx.text_list(mark) +} + +fn push_plain_item(ctx: &mut FieldCtx<'_>, item: Range<usize>) { + let item = ctx.trim_fws(item); + if item.is_empty() { + return; + } + let bytes = ctx.bytes(item.clone()); + let text = if memchr(b'\n', bytes).is_none() { + ctx.borrow(item) + } else { + ctx.push_with(|pool| { + let mut lines = bytes + .split(|&byte| byte == b'\n') + .map(trim_wsp) + .filter(|line| !line.is_empty()); + if let Some(first) = lines.next() { + push_utf8_lossy(pool, first); + } + for line in lines { + pool.push(' '); + push_utf8_lossy(pool, line); + } + }) + }; + ctx.push_text_item(text); +} + +fn trim_wsp(mut text: &[u8]) -> &[u8] { + while let [b' ' | b'\t' | b'\r', rest @ ..] = text { + text = rest; + } + while let [rest @ .., b' ' | b'\t' | b'\r'] = text { + text = rest; + } + text +} + +struct ListParser<'a> { + bytes: &'a [u8], + base: usize, + token: Option<Range<usize>>, + is_token_start: bool, + tokens: usize, + single: Option<Range<usize>>, + text: String, + words: Vec<u8>, + charset: &'a [u8], + terminator: Option<Option<usize>>, +} + +impl<'a> ListParser<'a> { + fn run(ctx: &mut FieldCtx<'a>, range: Range<usize>) { + let mut parser = ListParser { + bytes: ctx.bytes(range.clone()), + base: range.start, + token: None, + is_token_start: true, + tokens: 0, + single: None, + text: ctx.take_text_scratch(), + words: ctx.take_bytes_scratch(), + charset: b"", + terminator: None, + }; + let mut pos = 0; + while let Some(&byte) = parser.bytes.get(pos) { + let index = pos; + pos += 1; + match byte { + b'\n' => { + parser.add_token(); + continue; + } + b' ' | b'\t' => { + parser.is_token_start = true; + continue; + } + b'\r' => continue, + b',' => { + parser.add_item(ctx); + continue; + } + b'=' if parser.is_token_start && parser.bytes.get(pos) == Some(&b'?') => { + if let Some(consumed) = parser.encoded_word(index) { + pos = index + consumed; + continue; + } + } + _ => (), + } + parser.is_token_start = false; + parser.token = Some(parser.token.map_or(index, |token| token.start)..index + 1); + } + parser.add_item(ctx); + ctx.put_text_scratch(parser.text); + ctx.put_bytes_scratch(parser.words); + } + + fn push_text(&mut self, range: Range<usize>) { + let bytes = self.bytes.get(range).unwrap_or_default(); + push_utf8_lossy(&mut self.text, bytes); + } + + fn materialize(&mut self) { + if let Some(single) = self.single.take() { + self.push_text(single); + } + } + + fn flush_words(&mut self) { + if !self.words.is_empty() { + charsets::decode_append(self.charset, &self.words, &mut self.text); + self.words.clear(); + } + } + + fn add_token(&mut self) { + let Some(token) = self.token.take() else { + return; + }; + self.is_token_start = true; + if self.tokens == 0 { + self.single = Some(token); + } else { + self.materialize(); + self.flush_words(); + self.text.push(' '); + self.push_text(token); + } + self.tokens += 1; + } + + fn add_item(&mut self, ctx: &mut FieldCtx<'_>) { + self.add_token(); + match self.single.take() { + Some(single) if self.tokens == 1 => { + let text = ctx.borrow(self.base + single.start..self.base + single.end); + ctx.push_text_item(text); + } + single => { + if self.tokens > 0 { + if let Some(single) = single { + self.push_text(single); + } + self.flush_words(); + let text = ctx.push_str(&self.text); + ctx.push_text_item(text); + } + } + } + self.text.clear(); + self.tokens = 0; + } + + fn has_terminator(&mut self, from: usize) -> bool { + match self.terminator { + Some(Some(at)) if at >= from => return true, + Some(None) => return false, + _ => (), + } + let found = memmem::find(self.bytes.get(from..).unwrap_or_default(), b"?=") + .map(|offset| from + offset); + self.terminator = Some(found); + found.is_some() + } + + fn encoded_word(&mut self, index: usize) -> Option<usize> { + if !self.has_terminator(index + 2) { + return None; + } + let (word, consumed) = EncodedWord::parse(self.bytes.get(index..)?)?; + let split = self.words.len(); + word.decode_append(&mut self.words).ok()?; + let same_run = + self.token.is_none() && split > 0 && self.charset.eq_ignore_ascii_case(word.charset); + if !same_run { + self.materialize(); + if let Some(pending) = self + .words + .get(..split) + .filter(|pending| !pending.is_empty()) + { + charsets::decode_append(self.charset, pending, &mut self.text); + } + self.words.drain(..split); + self.charset = word.charset; + if let Some(token) = self.token.take() { + if self.tokens > 0 { + self.text.push(' '); + } + self.push_text(token); + self.text.push(' '); + self.tokens += 1; + } + } + self.tokens += 1; + Some(consumed) + } +} + +#[cfg(test)] +mod tests { + use crate::{ + HeaderForm, HeaderValue, + fields::{ + id::tests::{Case, Items, case_items, expected_items, items}, + tests::load_tests, + }, + }; + + const EDGE_CASES: &[Case] = &[ + (b"caf\xc3\xa9, x\xff\n", Some(&["caf\u{e9}", "x\u{fffd}"])), + (b"a\xc3\n \xa9b\n", Some(&["a\u{fffd} \u{fffd}b"])), + ]; + + fn parse(input: &[u8]) -> Items { + items(HeaderForm::CommaList.parse(input).value()) + } + + #[test] + fn comma_list_fixtures() { + let tests = load_tests("list.json"); + assert_eq!(tests.len(), 38); + for (header, expected) in tests { + assert_eq!( + parse(header.as_bytes()), + expected_items(&expected), + "{header:?}" + ); + } + } + + #[test] + fn comma_list_edge_cases() { + for &(input, expected) in EDGE_CASES { + assert_eq!( + parse(input), + case_items(expected), + "{:?}", + String::from_utf8_lossy(input) + ); + } + let parsed = HeaderForm::CommaList.parse(b" one item \r\n"); + assert!(matches!(parsed.value(), HeaderValue::TextList(list) if list.len() == 1)); + } + + #[test] + fn comma_list_word_flood_stays_linear() { + let mut input = b"=?ab?q?x ".repeat(50_000); + input.extend_from_slice(b"?=\n"); + assert_eq!(parse(&input).map(|list| list.len()), Some(1)); + let mut input = b"a =?utf-8?q?".repeat(50_000); + input.push(b'\n'); + assert_eq!(parse(&input).map(|list| list.len()), Some(1)); + } +} diff --git a/src/fields/mod.rs b/src/fields/mod.rs new file mode 100644 index 0000000..cf6d6ee --- /dev/null +++ b/src/fields/mod.rs @@ -0,0 +1,436 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +pub(crate) mod address; +pub(crate) mod content_type; +pub(crate) mod date; +pub(crate) mod id; +pub(crate) mod list; +pub(crate) mod raw; +pub(crate) mod received; +pub(crate) mod thread; +pub(crate) mod unstructured; + +#[cfg(test)] +pub(crate) mod tests; + +use crate::{ + HeaderValue, + scan::Kernel, + store::{ + AddressEntry, ContentTypeEntry, GROUP_BIT, MessageData, ParamEntry, ReceivedEntry, Span, + Str, Value, + }, + view::Resolver, +}; +use std::{fmt, ops::Range}; + +/// How a header value is parsed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum HeaderForm { + /// The value as written, without leading and trailing whitespace. + Raw, + /// Unstructured text with RFC 2047 encoded words decoded. + Text, + /// An address list: mailboxes and groups in document order. + Addresses, + /// A list of message identifiers. + MessageIds, + /// A comma-separated list of phrases. + CommaList, + /// An RFC 5322 date. + Date, + /// A Content-Type or Content-Disposition value. + ContentType, + /// A Received trace field. + Received, + /// Not parsed; the header is kept with an empty value. + Ignore, +} + +impl HeaderForm { + /// Parses a standalone header value: the bytes after the colon, up to + /// the end of the field (a line break not followed by white space). + /// + /// ``` + /// use mail_parser::HeaderForm; + /// + /// let parsed = HeaderForm::Addresses.parse(b" Jane <jane@example.com>, bob@example.com\r\n"); + /// let addresses = parsed.value().as_address().expect("addresses"); + /// assert_eq!(addresses.mailboxes().count(), 2); + /// + /// let parsed = HeaderForm::Date.parse(b" Sat, 20 Nov 2021 14:22:01 -0800\r\n"); + /// let date = parsed.value().as_datetime().expect("date"); + /// assert_eq!(date.to_timestamp(), 1_637_446_921); + /// ``` + pub fn parse(self, value: &[u8]) -> ParsedValue<'_> { + ParsedValue::new(self, value, 0..value.len()) + } +} + +/// A header value parsed on its own, outside a message, by +/// [`HeaderForm::parse`] or [`crate::Header::parse_as`]. It borrows the +/// input and owns a small store only when the value needs one (a raw, +/// single-line text or date value allocates nothing). Parsed values compare +/// by their value. +#[derive(Clone)] +pub struct ParsedValue<'x> { + source: &'x [u8], + data: Option<MessageData>, + value: Value, +} + +static EMPTY_DATA: MessageData = MessageData::EMPTY; + +impl<'x> ParsedValue<'x> { + pub(crate) fn new(form: HeaderForm, source: &'x [u8], range: Range<usize>) -> Self { + let range = first_field(source, range); + let value = match form { + HeaderForm::Ignore => Value::Empty, + HeaderForm::Date => date::parse_bytes(source.get(range).unwrap_or_default()) + .map_or(Value::Empty, Value::DateTime), + HeaderForm::Raw => match raw::borrowed(source, range.clone()) { + Some(value) => value, + None => return Self::stored(source, |ctx| raw::parse_raw(ctx, range)), + }, + HeaderForm::Text => match unstructured::standalone(source, range) { + Ok(value) => value, + Err(pending) => return Self::stored(source, |ctx| pending.parse(ctx)), + }, + HeaderForm::Addresses + | HeaderForm::MessageIds + | HeaderForm::CommaList + | HeaderForm::ContentType + | HeaderForm::Received => { + return Self::stored(source, |ctx| parse_value(form, ctx, range)); + } + }; + ParsedValue { + source, + data: None, + value, + } + } + + fn stored(source: &'x [u8], parse: impl FnOnce(&mut FieldCtx<'_>) -> Value) -> Self { + let mut data = MessageData::default(); + let value = parse(&mut FieldCtx::new(source, &mut data)); + ParsedValue { + source, + data: Some(data), + value, + } + } + + /// The parsed value. + pub fn value(&self) -> HeaderValue<'_> { + let data = self.data.as_ref().unwrap_or(&EMPTY_DATA); + HeaderValue::new(Resolver::new(self.source, &data.strings), data, self.value) + } +} + +impl PartialEq for ParsedValue<'_> { + fn eq(&self, other: &Self) -> bool { + self.value() == other.value() + } +} + +impl Eq for ParsedValue<'_> {} + +impl fmt::Debug for ParsedValue<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ParsedValue") + .field("value", &self.value()) + .finish() + } +} + +pub(crate) fn first_field(source: &[u8], range: Range<usize>) -> Range<usize> { + let end = Kernel::MEMCHR + .field_end(source, range.start) + .map_or(range.end, |newline| range.end.min(newline + 1)); + range.start..end +} + +const FIRST_ADDRESSES: usize = 16; +const FIRST_PARAMS: usize = 16; +const FIRST_CONTENT_TYPES: usize = 16; +const FIRST_RECEIVED: usize = 8; + +fn push_sized<T>(items: &mut Vec<T>, item: T, first: usize) { + if items.capacity() == 0 { + items.reserve_exact(first); + } + items.push(item); +} + +pub(crate) fn push_utf8_lossy(out: &mut String, bytes: &[u8]) { + for chunk in bytes.utf8_chunks() { + out.push_str(chunk.valid()); + if !chunk.invalid().is_empty() { + out.push(char::REPLACEMENT_CHARACTER); + } + } +} + +pub(crate) fn is_fws(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | b'\r' | b'\n') +} + +pub(crate) fn trim_fws(src: &[u8], range: Range<usize>) -> Range<usize> { + let bytes = src.get(range.clone()).unwrap_or_default(); + let start = bytes.iter().position(|&byte| !is_fws(byte)); + let end = bytes.iter().rposition(|&byte| !is_fws(byte)); + match (start, end) { + (Some(start), Some(end)) => range.start + start..range.start + end + 1, + _ => range.start..range.start, + } +} + +pub(crate) fn parse_value(form: HeaderForm, ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + match form { + HeaderForm::Raw => raw::parse_raw(ctx, value), + HeaderForm::Text => unstructured::parse_unstructured(ctx, value), + HeaderForm::Addresses => address::parse_address(ctx, value), + HeaderForm::MessageIds => id::parse_id(ctx, value), + HeaderForm::CommaList => list::parse_comma_list(ctx, value), + HeaderForm::Date => date::parse_date(ctx, value), + HeaderForm::ContentType => content_type::parse_content_type(ctx, value), + HeaderForm::Received => received::parse_received(ctx, value), + HeaderForm::Ignore => Value::Empty, + } +} + +pub(crate) struct FieldCtx<'a> { + src: &'a [u8], + data: &'a mut MessageData, + kernel: Kernel, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct GroupMark(u32); + +impl<'a> FieldCtx<'a> { + pub(crate) fn new(src: &'a [u8], data: &'a mut MessageData) -> Self { + FieldCtx::with_kernel(src, data, Kernel::best()) + } + + pub(crate) fn with_kernel(src: &'a [u8], data: &'a mut MessageData, kernel: Kernel) -> Self { + FieldCtx { src, data, kernel } + } + + pub(crate) fn src(&self) -> &'a [u8] { + self.src + } + + pub(crate) fn kernel(&self) -> Kernel { + self.kernel + } + + pub(crate) fn bytes(&self, range: Range<usize>) -> &'a [u8] { + self.src.get(range).unwrap_or_default() + } + + pub(crate) fn resolve(&self, text: Str) -> &str { + text.resolve(self.src, &self.data.strings) + } + + pub(crate) fn try_borrow(&self, range: Range<usize>) -> Option<Str> { + Str::borrow(self.src, range) + } + + pub(crate) fn borrow(&mut self, range: Range<usize>) -> Str { + match Str::borrow(self.src, range.clone()) { + Some(text) => text, + None => self.push_lossy(self.bytes(range)), + } + } + + pub(crate) fn push_str(&mut self, text: &str) -> Str { + Str::push(&mut self.data.strings, text) + } + + pub(crate) fn push_lossy(&mut self, bytes: &[u8]) -> Str { + Str::push_with(&mut self.data.strings, |pool| push_utf8_lossy(pool, bytes)) + } + + pub(crate) fn push_with(&mut self, write: impl FnOnce(&mut String)) -> Str { + Str::push_with(&mut self.data.strings, write) + } + + pub(crate) fn lowercase(&mut self, range: Range<usize>) -> Str { + let upper = self.bytes(range.clone()).iter().any(u8::is_ascii_uppercase); + self.lowercase_scanned(range, upper) + } + + pub(crate) fn lowercase_scanned(&mut self, range: Range<usize>, upper: bool) -> Str { + if !upper && let Some(text) = Str::borrow(self.src, range.clone()) { + return text; + } + let bytes = self.bytes(range); + Str::push_with(&mut self.data.strings, |pool| { + let start = pool.len(); + push_utf8_lossy(pool, bytes); + if let Some(pushed) = pool.get_mut(start..) { + pushed.make_ascii_lowercase(); + } + }) + } + + pub(crate) fn trim_fws(&self, range: Range<usize>) -> Range<usize> { + trim_fws(self.src, range) + } + + pub(crate) fn take_text_scratch(&mut self) -> String { + let mut text = std::mem::take(&mut self.data.scratch.text); + text.clear(); + text + } + + pub(crate) fn put_text_scratch(&mut self, text: String) { + self.data.scratch.text = text; + } + + pub(crate) fn take_bytes_scratch(&mut self) -> Vec<u8> { + let mut bytes = std::mem::take(&mut self.data.scratch.bytes); + bytes.clear(); + bytes + } + + pub(crate) fn put_bytes_scratch(&mut self, bytes: Vec<u8>) { + self.data.scratch.bytes = bytes; + } + + pub(crate) fn text_items_mark(&self) -> u32 { + self.data.text_items.len() as u32 + } + + pub(crate) fn push_text_item(&mut self, item: Str) { + self.data.push_text_item(item); + } + + pub(crate) fn text_list(&self, mark: u32) -> Value { + match (self.data.text_items.len() as u32).saturating_sub(mark) { + 0 => Value::Empty, + len => Value::TextList(Span { start: mark, len }), + } + } + + pub(crate) fn address_mark(&self) -> u32 { + self.data.address_items.len() as u32 + } + + pub(crate) fn push_mailbox(&mut self, name: Option<Str>, address: Option<Str>) { + self.data.address_items.push( + AddressEntry { + name: Str::from_option(name), + address: Str::from_option(address), + group: 0, + }, + FIRST_ADDRESSES, + ); + } + + pub(crate) fn push_group(&mut self, name: Option<Str>) -> GroupMark { + let mark = GroupMark(self.data.address_items.len() as u32); + self.data.address_items.push( + AddressEntry { + name: Str::from_option(name), + address: Str::NONE, + group: GROUP_BIT, + }, + FIRST_ADDRESSES, + ); + mark + } + + pub(crate) fn end_group(&mut self, group: GroupMark) { + let members = (self.data.address_items.len() as u32).saturating_sub(group.0 + 1); + if let Some(entry) = self.data.address_items.get_mut(group.0 as usize) { + entry.group = GROUP_BIT | members; + } + } + + pub(crate) fn address_list(&self, mark: u32) -> Value { + let len = (self.data.address_items.len() as u32).saturating_sub(mark); + if len == 0 { + Value::Empty + } else { + Value::Address(Span { start: mark, len }) + } + } + + pub(crate) fn params_mark(&self) -> u32 { + self.data.params.len() as u32 + } + + pub(crate) fn push_param(&mut self, name: Str, value: Str) { + self.data + .params + .push(ParamEntry { name, value }, FIRST_PARAMS); + } + + pub(crate) fn params_since(&self, mark: u32) -> &[ParamEntry] { + self.data.params.get(mark as usize..).unwrap_or_default() + } + + pub(crate) fn set_param_value(&mut self, index: u32, value: Str) { + if let Some(param) = self.data.params.get_mut(index as usize) { + param.value = value; + } + } + + pub(crate) fn rollback_params(&mut self, mark: u32) { + self.data.params.truncate(mark as usize); + } + + pub(crate) fn remove_param(&mut self, index: u32) { + if let Some(param) = self.data.params.get_mut(index as usize) { + param.name = Str::NONE; + } + } + + pub(crate) fn drop_removed_params(&mut self, mark: u32) { + let params = &mut self.data.params; + let mut kept = mark as usize; + for index in mark as usize..params.len() { + let Some(¶m) = params.get(index) else { + break; + }; + if param.name.is_some() { + if let Some(slot) = params.get_mut(kept) { + *slot = param; + } + kept += 1; + } + } + params.truncate(kept); + } + + pub(crate) fn content_type(&mut self, ctype: Str, subtype: Option<Str>, params: u32) -> Value { + let index = self.data.content_types.len() as u32; + let params = Span { + start: params, + len: (self.data.params.len() as u32).saturating_sub(params), + }; + self.data.content_types.push( + ContentTypeEntry { + ctype, + subtype: Str::from_option(subtype), + params, + }, + FIRST_CONTENT_TYPES, + ); + Value::ContentType(index) + } + + pub(crate) fn received(&mut self, entry: ReceivedEntry) -> Value { + let index = self.data.received.len() as u32; + push_sized(&mut self.data.received, entry, FIRST_RECEIVED); + Value::Received(index) + } +} diff --git a/src/fields/raw.rs b/src/fields/raw.rs new file mode 100644 index 0000000..0e9e4f0 --- /dev/null +++ b/src/fields/raw.rs @@ -0,0 +1,27 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{FieldCtx, trim_fws}; +use crate::store::{Str, Value}; +use std::ops::Range; + +pub(crate) fn parse_raw(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + let trimmed = ctx.trim_fws(value); + if trimmed.is_empty() { + Value::Text(Str::EMPTY) + } else { + Value::Text(ctx.borrow(trimmed)) + } +} + +pub(crate) fn borrowed(src: &[u8], value: Range<usize>) -> Option<Value> { + let trimmed = trim_fws(src, value); + if trimmed.is_empty() { + Some(Value::Text(Str::EMPTY)) + } else { + Str::borrow(src, trimmed).map(Value::Text) + } +} diff --git a/src/fields/received.rs b/src/fields/received.rs new file mode 100644 index 0000000..f296f0f --- /dev/null +++ b/src/fields/received.rs @@ -0,0 +1,1228 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::FieldCtx; +use crate::{ + DateTime, Greeting, Protocol, TlsVersion, + store::{HostEntry, ReceivedEntry, Str, Value}, +}; +use std::{ + net::{IpAddr, Ipv4Addr, Ipv6Addr}, + ops::Range, +}; + +pub(crate) fn parse_received(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + let entry = Grammar::new(ctx, value).run(); + if entry == ReceivedEntry::EMPTY { + Value::Empty + } else { + ctx.received(entry) + } +} + +const LOWER_ALPHA: u16 = 1; +const UPPER_ALPHA: u16 = 1 << 1; +const LOWER_HEX: u16 = 1 << 2; +const UPPER_HEX: u16 = 1 << 3; +const DIGIT: u16 = 1 << 4; +const DOT: u16 = 1 << 5; +const AT: u16 = 1 << 6; +const PLUS: u16 = 1 << 7; +const MINUS: u16 = 1 << 8; +const UNDERSCORE: u16 = 1 << 9; +const OTHER: u16 = 1 << 10; +const UTF: u16 = 1 << 11; +const COLON: u16 = 1 << 12; +const SPACE: u16 = 1 << 13; +const SEPARATOR: u16 = 1 << 14; + +const ALPHA: u16 = LOWER_ALPHA | UPPER_ALPHA; +const HEX: u16 = LOWER_HEX | UPPER_HEX; +const LETTER: u16 = ALPHA | HEX; +const LOWER: u16 = LOWER_ALPHA | LOWER_HEX; +const ALNUM: u16 = LETTER | DIGIT; +const HEX_DIGIT: u16 = HEX | DIGIT; +const WORD: u16 = ALNUM | DOT | AT | PLUS | MINUS | UNDERSCORE | OTHER | UTF; + +const IN_COMMENT: u8 = 1; +const IN_BRACKET: u8 = 1 << 1; + +const MAX_VALUE: usize = u32::MAX as usize; +const MAX_COLONS: u8 = 7; +const UNSET: i64 = i64::MAX; +const MAX_KEYWORD: usize = 11; +const MIN_CIPHER: usize = 7; +const DAY_NAMES: [&[u8; 3]; 7] = [b"mon", b"tue", b"wed", b"thu", b"fri", b"sat", b"sun"]; +const CIPHER_PREFIXES: [&[u8; 3]; 8] = [ + b"rsa", b"ecd", b"dhe", b"psk", b"srp", b"aes", b"des", b"tls", +]; + +static CLASS: [u16; 256] = { + let mut table = [0; 256]; + let mut byte = 0; + while byte < table.len() { + table[byte] = byte_class(byte as u8); + byte += 1; + } + table +}; + +const fn byte_class(byte: u8) -> u16 { + match byte { + b'0'..=b'9' => DIGIT, + b'a'..=b'f' => LOWER_HEX, + b'g'..=b'z' => LOWER_ALPHA, + b'A'..=b'F' => UPPER_HEX, + b'G'..=b'Z' => UPPER_ALPHA, + b'.' => DOT, + b'@' => AT, + b'+' => PLUS, + b'-' => MINUS, + b'_' => UNDERSCORE, + b':' => COLON, + b' ' | b'\t' | b'\r' | b'\n' => SPACE, + b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'=' | b';' | b'/' | b'"' | b',' => SEPARATOR, + 0x7f..=0xff => UTF, + _ => OTHER, + } +} + +fn class(byte: u8) -> u16 { + CLASS[usize::from(byte)] +} + +const KEYWORDS: [(&[u8], Kind); 78] = [ + (b"from", Kind::From), + (b"by", Kind::By), + (b"for", Kind::For), + (b"id", Kind::Id), + (b"via", Kind::Via), + (b"with", Kind::With), + (b"ident", Kind::Ident), + (b"helo", Kind::Greeting(Greeting::Helo)), + (b"ehlo", Kind::Greeting(Greeting::Ehlo)), + (b"lhlo", Kind::Greeting(Greeting::Lhlo)), + (b"jan", Kind::Month(1)), + (b"feb", Kind::Month(2)), + (b"mar", Kind::Month(3)), + (b"apr", Kind::Month(4)), + (b"may", Kind::Month(5)), + (b"jun", Kind::Month(6)), + (b"jul", Kind::Month(7)), + (b"aug", Kind::Month(8)), + (b"sep", Kind::Month(9)), + (b"oct", Kind::Month(10)), + (b"nov", Kind::Month(11)), + (b"dec", Kind::Month(12)), + (b"smtp", Kind::Protocol(Protocol::SMTP)), + (b"bsmtp", Kind::Protocol(Protocol::SMTP)), + (b"smtpd", Kind::Protocol(Protocol::SMTP)), + (b"smtpsvc", Kind::Protocol(Protocol::SMTP)), + (b"localbsmtp", Kind::Protocol(Protocol::SMTP)), + (b"esmtp", Kind::Protocol(Protocol::ESMTP)), + (b"localesmtp", Kind::Protocol(Protocol::ESMTP)), + (b"esmtpa", Kind::Protocol(Protocol::ESMTPA)), + (b"asmtp", Kind::Protocol(Protocol::ESMTPA)), + (b"esmtps", Kind::Protocol(Protocol::ESMTPS)), + (b"esmtptls", Kind::Protocol(Protocol::ESMTPS)), + (b"localesmtps", Kind::Protocol(Protocol::ESMTPS)), + (b"esmtpsa", Kind::Protocol(Protocol::ESMTPSA)), + (b"lmtp", Kind::Protocol(Protocol::LMTP)), + (b"lsmtp", Kind::Protocol(Protocol::LMTP)), + (b"lmtpa", Kind::Protocol(Protocol::LMTPA)), + (b"lmtps", Kind::Protocol(Protocol::LMTPS)), + (b"lmtpsa", Kind::Protocol(Protocol::LMTPSA)), + (b"mms", Kind::Protocol(Protocol::MMS)), + (b"utf8smtp", Kind::Protocol(Protocol::UTF8SMTP)), + (b"utf8smtpa", Kind::Protocol(Protocol::UTF8SMTPA)), + (b"utf8smtps", Kind::Protocol(Protocol::UTF8SMTPS)), + (b"utf8smtpsa", Kind::Protocol(Protocol::UTF8SMTPSA)), + (b"utf8lmtp", Kind::Protocol(Protocol::UTF8LMTP)), + (b"utf8lmtpa", Kind::Protocol(Protocol::UTF8LMTPA)), + (b"utf8lmtps", Kind::Protocol(Protocol::UTF8LMTPS)), + (b"utf8lmtpsa", Kind::Protocol(Protocol::UTF8LMTPSA)), + (b"http", Kind::Protocol(Protocol::HTTP)), + (b"httpu", Kind::Protocol(Protocol::HTTP)), + (b"httprest", Kind::Protocol(Protocol::HTTP)), + (b"https", Kind::Protocol(Protocol::HTTPS)), + (b"imap", Kind::Protocol(Protocol::IMAP)), + (b"pop3", Kind::Protocol(Protocol::POP3)), + (b"local", Kind::Protocol(Protocol::Local)), + (b"socket", Kind::Protocol(Protocol::Local)), + (b"stdin", Kind::Protocol(Protocol::Local)), + (b"ssl2", Kind::Tls(TlsVersion::SSLv2)), + (b"sslv2", Kind::Tls(TlsVersion::SSLv2)), + (b"ssl3", Kind::Tls(TlsVersion::SSLv3)), + (b"sslv3", Kind::Tls(TlsVersion::SSLv3)), + (b"tls1", Kind::Tls(TlsVersion::TLSv1_0)), + (b"tlsv1", Kind::Tls(TlsVersion::TLSv1_0)), + (b"tls10", Kind::Tls(TlsVersion::TLSv1_0)), + (b"tlsv10", Kind::Tls(TlsVersion::TLSv1_0)), + (b"tls11", Kind::Tls(TlsVersion::TLSv1_1)), + (b"tlsv11", Kind::Tls(TlsVersion::TLSv1_1)), + (b"tls12", Kind::Tls(TlsVersion::TLSv1_2)), + (b"tlsv12", Kind::Tls(TlsVersion::TLSv1_2)), + (b"tls13", Kind::Tls(TlsVersion::TLSv1_3)), + (b"tlsv13", Kind::Tls(TlsVersion::TLSv1_3)), + (b"dtls10", Kind::Tls(TlsVersion::DTLSv1_0)), + (b"dtlsv10", Kind::Tls(TlsVersion::DTLSv1_0)), + (b"dtls12", Kind::Tls(TlsVersion::DTLSv1_2)), + (b"dtlsv12", Kind::Tls(TlsVersion::DTLSv1_2)), + (b"dtls13", Kind::Tls(TlsVersion::DTLSv1_3)), + (b"dtlsv13", Kind::Tls(TlsVersion::DTLSv1_3)), +]; + +static KEYWORD_STARTS: [u32; MAX_KEYWORD + 1] = { + let mut starts = [0; MAX_KEYWORD + 1]; + let mut index = 0; + while index < KEYWORDS.len() { + let keyword = KEYWORDS[index].0; + starts[keyword.len()] |= 1 << (keyword[0] - b'a'); + index += 1; + } + starts +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + BracketOpen, + BracketClose, + AngleOpen, + AngleClose, + ParenOpen, + ParenClose, + Semicolon, + Colon, + Equal, + Slash, + Quote, + Comma, + From, + By, + For, + Id, + Via, + With, + Ident, + Greeting(Greeting), + Protocol(Protocol), + Tls(TlsVersion), + Month(u8), + Word, +} + +impl Kind { + fn is_separator(self) -> bool { + matches!( + self, + Kind::BracketOpen + | Kind::BracketClose + | Kind::AngleOpen + | Kind::AngleClose + | Kind::ParenOpen + | Kind::ParenClose + | Kind::Semicolon + | Kind::Colon + | Kind::Equal + | Kind::Slash + | Kind::Quote + | Kind::Comma + ) + } + + fn is_inert(self) -> bool { + self != Kind::Semicolon && self.is_separator() + } + + fn of_word(text: &[u8], mask: u16, colons: u8) -> Kind { + if colons != 0 || mask & LETTER == 0 || mask & (AT | PLUS | UTF) != 0 { + Kind::Word + } else if mask & !ALNUM == 0 { + Kind::keyword(text) + } else { + Kind::decorated_keyword(text, mask) + } + } + + fn keyword(text: &[u8]) -> Kind { + let starts = KEYWORD_STARTS.get(text.len()).copied().unwrap_or_default(); + let letter = text + .first() + .map_or(u8::MAX, |byte| (byte | 0x20).wrapping_sub(b'a')); + if letter < 26 && starts & (1 << letter) != 0 { + Kind::lookup(text) + } else { + Kind::Word + } + } + + fn lookup(text: &[u8]) -> Kind { + hashify::map_ignore_case!(text, Kind, + "from" => Kind::From, + "by" => Kind::By, + "for" => Kind::For, + "id" => Kind::Id, + "via" => Kind::Via, + "with" => Kind::With, + "ident" => Kind::Ident, + "helo" => Kind::Greeting(Greeting::Helo), + "ehlo" => Kind::Greeting(Greeting::Ehlo), + "lhlo" => Kind::Greeting(Greeting::Lhlo), + "jan" => Kind::Month(1), + "feb" => Kind::Month(2), + "mar" => Kind::Month(3), + "apr" => Kind::Month(4), + "may" => Kind::Month(5), + "jun" => Kind::Month(6), + "jul" => Kind::Month(7), + "aug" => Kind::Month(8), + "sep" => Kind::Month(9), + "oct" => Kind::Month(10), + "nov" => Kind::Month(11), + "dec" => Kind::Month(12), + "smtp" => Kind::Protocol(Protocol::SMTP), + "bsmtp" => Kind::Protocol(Protocol::SMTP), + "smtpd" => Kind::Protocol(Protocol::SMTP), + "smtpsvc" => Kind::Protocol(Protocol::SMTP), + "localbsmtp" => Kind::Protocol(Protocol::SMTP), + "esmtp" => Kind::Protocol(Protocol::ESMTP), + "localesmtp" => Kind::Protocol(Protocol::ESMTP), + "esmtpa" => Kind::Protocol(Protocol::ESMTPA), + "asmtp" => Kind::Protocol(Protocol::ESMTPA), + "esmtps" => Kind::Protocol(Protocol::ESMTPS), + "esmtptls" => Kind::Protocol(Protocol::ESMTPS), + "localesmtps" => Kind::Protocol(Protocol::ESMTPS), + "esmtpsa" => Kind::Protocol(Protocol::ESMTPSA), + "lmtp" => Kind::Protocol(Protocol::LMTP), + "lsmtp" => Kind::Protocol(Protocol::LMTP), + "lmtpa" => Kind::Protocol(Protocol::LMTPA), + "lmtps" => Kind::Protocol(Protocol::LMTPS), + "lmtpsa" => Kind::Protocol(Protocol::LMTPSA), + "mms" => Kind::Protocol(Protocol::MMS), + "utf8smtp" => Kind::Protocol(Protocol::UTF8SMTP), + "utf8smtpa" => Kind::Protocol(Protocol::UTF8SMTPA), + "utf8smtps" => Kind::Protocol(Protocol::UTF8SMTPS), + "utf8smtpsa" => Kind::Protocol(Protocol::UTF8SMTPSA), + "utf8lmtp" => Kind::Protocol(Protocol::UTF8LMTP), + "utf8lmtpa" => Kind::Protocol(Protocol::UTF8LMTPA), + "utf8lmtps" => Kind::Protocol(Protocol::UTF8LMTPS), + "utf8lmtpsa" => Kind::Protocol(Protocol::UTF8LMTPSA), + "http" => Kind::Protocol(Protocol::HTTP), + "httpu" => Kind::Protocol(Protocol::HTTP), + "httprest" => Kind::Protocol(Protocol::HTTP), + "https" => Kind::Protocol(Protocol::HTTPS), + "imap" => Kind::Protocol(Protocol::IMAP), + "pop3" => Kind::Protocol(Protocol::POP3), + "local" => Kind::Protocol(Protocol::Local), + "socket" => Kind::Protocol(Protocol::Local), + "stdin" => Kind::Protocol(Protocol::Local), + "ssl2" => Kind::Tls(TlsVersion::SSLv2), + "sslv2" => Kind::Tls(TlsVersion::SSLv2), + "ssl3" => Kind::Tls(TlsVersion::SSLv3), + "sslv3" => Kind::Tls(TlsVersion::SSLv3), + "tls1" => Kind::Tls(TlsVersion::TLSv1_0), + "tlsv1" => Kind::Tls(TlsVersion::TLSv1_0), + "tls10" => Kind::Tls(TlsVersion::TLSv1_0), + "tlsv10" => Kind::Tls(TlsVersion::TLSv1_0), + "tls11" => Kind::Tls(TlsVersion::TLSv1_1), + "tlsv11" => Kind::Tls(TlsVersion::TLSv1_1), + "tls12" => Kind::Tls(TlsVersion::TLSv1_2), + "tlsv12" => Kind::Tls(TlsVersion::TLSv1_2), + "tls13" => Kind::Tls(TlsVersion::TLSv1_3), + "tlsv13" => Kind::Tls(TlsVersion::TLSv1_3), + "dtls10" => Kind::Tls(TlsVersion::DTLSv1_0), + "dtlsv10" => Kind::Tls(TlsVersion::DTLSv1_0), + "dtls12" => Kind::Tls(TlsVersion::DTLSv1_2), + "dtlsv12" => Kind::Tls(TlsVersion::DTLSv1_2), + "dtls13" => Kind::Tls(TlsVersion::DTLSv1_3), + "dtlsv13" => Kind::Tls(TlsVersion::DTLSv1_3), + ) + .copied() + .unwrap_or(Kind::Word) + } + + fn decorated_keyword(text: &[u8], mask: u16) -> Kind { + let first = text + .iter() + .find(|byte| byte.is_ascii_alphanumeric()) + .map(u8::to_ascii_lowercase); + let candidate = if mask & DIGIT == 0 { + matches!(first, Some(b'l' | b'e')) + } else { + matches!(first, Some(b't' | b'd')) + }; + if candidate { + Kind::decorated_lookup(text, mask) + } else { + Kind::Word + } + } + + fn decorated_lookup(text: &[u8], mask: u16) -> Kind { + let letters = text + .iter() + .filter(|byte| byte.is_ascii_alphanumeric()) + .map(u8::to_ascii_lowercase); + let mut alnum = [0u8; MAX_KEYWORD]; + let mut len = 0; + for byte in letters { + let Some(slot) = alnum.get_mut(len) else { + return Kind::Word; + }; + *slot = byte; + len += 1; + } + let alnum = alnum.get(..len).unwrap_or_default(); + if mask & DIGIT == 0 { + if mask & !(ALNUM | MINUS) != 0 { + return Kind::Word; + } + match alnum { + b"localesmtp" => Kind::Protocol(Protocol::ESMTP), + b"localesmtps" | b"esmtptls" => Kind::Protocol(Protocol::ESMTPS), + b"localbsmtp" => Kind::Protocol(Protocol::SMTP), + _ => Kind::Word, + } + } else { + let version = match alnum { + b"tls10" => return Kind::Tls(TlsVersion::TLSv1_0), + b"tls11" => return Kind::Tls(TlsVersion::TLSv1_1), + b"tls12" => return Kind::Tls(TlsVersion::TLSv1_2), + b"tls13" => return Kind::Tls(TlsVersion::TLSv1_3), + b"tlsv10" => TlsVersion::TLSv1_0, + b"tlsv11" => TlsVersion::TLSv1_1, + b"tlsv12" => TlsVersion::TLSv1_2, + b"tlsv13" => TlsVersion::TLSv1_3, + b"dtls10" | b"dtlsv10" => TlsVersion::DTLSv1_0, + b"dtls12" | b"dtlsv12" => TlsVersion::DTLSv1_2, + b"dtls13" | b"dtlsv13" => TlsVersion::DTLSv1_3, + _ => return Kind::Word, + }; + if mask & MINUS == 0 { + Kind::Tls(version) + } else { + Kind::Word + } + } + } +} + +#[derive(Debug, Clone, Copy)] +struct Token { + start: u32, + end: u32, + kind: Kind, + mask: u16, + colons: u8, + flags: u8, +} + +impl Token { + fn separator(kind: Kind) -> Token { + Token { + start: 0, + end: 0, + kind, + mask: 0, + colons: 0, + flags: 0, + } + } + + fn in_comment(&self) -> bool { + self.flags & IN_COMMENT != 0 + } + + fn in_bracket(&self) -> bool { + self.flags & IN_BRACKET != 0 + } + + fn range(&self) -> Range<usize> { + self.start as usize..self.end as usize + } + + fn text<'a>(&self, bytes: &'a [u8]) -> &'a [u8] { + bytes.get(self.range()).unwrap_or_default() + } + + fn ip(&self, bytes: &[u8]) -> Option<IpAddr> { + if self.kind != Kind::Word { + return None; + } + let text = self.text(bytes); + if self.colons == 0 { + if self.mask & DOT == 0 || self.mask & !(DIGIT | DOT) != 0 { + return None; + } + ipv4(text).map(IpAddr::V4) + } else { + if self.colons < 2 + || self.mask & (ALPHA | AT | OTHER | UNDERSCORE | PLUS | MINUS | UTF) != 0 + { + return None; + } + let count = |class_bits: u16| { + text.iter() + .filter(|&&byte| class(byte) & class_bits != 0) + .count() + }; + let (hex, digits) = (count(HEX), count(DIGIT)); + let shaped = if self.mask & DOT == 0 { + (1..=32).contains(&hex) || (1..=32).contains(&digits) + } else { + self.colons == 3 && hex == 4 && count(DOT) == 3 && (4..=12).contains(&digits) + }; + if !shaped { + return None; + } + std::str::from_utf8(text) + .ok()? + .parse::<Ipv6Addr>() + .ok() + .map(IpAddr::V6) + } + } + + fn integer(&self, bytes: &[u8]) -> Option<i64> { + if self.kind != Kind::Word + || self.colons != 0 + || self.mask & DIGIT == 0 + || self.mask & !(DIGIT | PLUS | MINUS) != 0 + { + return None; + } + let text = self.text(bytes); + let (negative, digits) = match text.split_first() { + Some((b'-', digits)) => (true, digits), + Some((b'+', digits)) => (false, digits), + _ => (false, text), + }; + if digits.is_empty() { + return None; + } + digits.iter().try_fold(0i64, |value, &byte| { + let digit = i64::from(byte.checked_sub(b'0').filter(|digit| *digit <= 9)?); + let value = value.checked_mul(10)?; + if negative { + value.checked_sub(digit) + } else { + value.checked_add(digit) + } + }) + } + + fn is_email(&self, bytes: &[u8]) -> bool { + self.kind == Kind::Word + && self.mask & AT != 0 + && self.mask & LETTER != 0 + && self + .text(bytes) + .iter() + .filter(|&&byte| byte == b'@') + .count() + == 1 + } + + fn is_domain(&self) -> bool { + self.kind == Kind::Word + && self.colons == 0 + && self.mask & LETTER != 0 + && self.mask & DOT != 0 + && self.mask & (AT | OTHER | UNDERSCORE | PLUS) == 0 + } + + fn is_cipher(&self, bytes: &[u8]) -> bool { + if self.kind != Kind::Word + || self.colons != 0 + || self.range().len() < MIN_CIPHER + || self.mask & (LOWER | DOT | AT | PLUS | OTHER | UTF) != 0 + || self.mask & DIGIT == 0 + || self.mask & (UNDERSCORE | MINUS) == 0 + { + return false; + } + let mut prefix = [0u8; 3]; + let mut letters = self + .text(bytes) + .iter() + .filter(|byte| byte.is_ascii_alphanumeric()); + for slot in &mut prefix { + match letters.next() { + Some(byte) => *slot = byte.to_ascii_lowercase(), + None => return false, + } + } + CIPHER_PREFIXES.contains(&&prefix) + } +} + +fn ipv4(text: &[u8]) -> Option<Ipv4Addr> { + let mut octets = [0u8; 4]; + let mut groups = text.split(|&byte| byte == b'.'); + for octet in &mut octets { + let group = groups.next()?; + if group.is_empty() || group.len() > 3 || (group.len() > 1 && group.first() == Some(&b'0')) + { + return None; + } + let value = group.iter().try_fold(0u16, |value, &byte| { + byte.is_ascii_digit() + .then(|| value * 10 + u16::from(byte - b'0')) + })?; + *octet = u8::try_from(value).ok()?; + } + groups.next().is_none().then_some(Ipv4Addr::from(octets)) +} + +struct Tokenizer<'a> { + bytes: &'a [u8], + pos: usize, + pending: Option<Kind>, + comment_depth: u32, + in_bracket: bool, + in_quote: bool, + in_date: bool, +} + +impl<'a> Tokenizer<'a> { + fn new(bytes: &'a [u8]) -> Self { + Tokenizer { + bytes, + pos: 0, + pending: None, + comment_depth: 0, + in_bracket: false, + in_quote: false, + in_date: false, + } + } + + fn next(&mut self, skip_inert: bool) -> Option<Token> { + loop { + let token = match self.pending.take() { + Some(kind) => Token::separator(kind), + None => self.scan()?, + }; + if !skip_inert || !token.kind.is_inert() { + return Some(token); + } + } + } + + fn scan(&mut self) -> Option<Token> { + let rest = self.bytes.get(self.pos..).unwrap_or_default(); + let Some(skip) = rest.iter().position(|&byte| class(byte) != SPACE) else { + self.pos = self.bytes.len(); + return None; + }; + let word = rest.get(skip..).unwrap_or_default(); + let start = self.pos + skip; + let flags = (u8::from(self.comment_depth > 0) * IN_COMMENT) + | (u8::from(self.in_bracket) * IN_BRACKET); + let in_date = self.in_date; + let mut mask = 0; + let mut colons = 0; + let mut bytes = word.iter(); + let stop = loop { + let Some(&byte) = bytes.next() else { + break None; + }; + let class = class(byte); + if class & WORD != 0 { + mask |= class; + } else if class == COLON && !in_date && mask & !HEX_DIGIT == 0 && colons < MAX_COLONS { + colons += 1; + } else { + break Some(byte); + } + }; + let consumed = word.len() - bytes.as_slice().len(); + self.pos = start + consumed; + let len = match stop { + Some(stop) => { + if class(stop) != SPACE { + self.consume(stop); + } + consumed - 1 + } + None => consumed, + }; + if len == 0 { + return self.pending.take().map(Token::separator); + } + let text = word.get(..len).unwrap_or_default(); + Some(Token { + start: start as u32, + end: (start + len) as u32, + kind: Kind::of_word(text, mask, colons), + mask, + colons, + flags, + }) + } + + fn canonical_date(&mut self) -> Option<[i64; 7]> { + if !self.in_date { + return None; + } + let mut cursor = Cursor { + rest: self.bytes.get(self.pos..).unwrap_or_default(), + }; + let mut token = cursor.token(); + if is_day_name(token) { + cursor.byte(b','); + token = cursor.token(); + } + let day = digits(token, 2)?; + let Kind::Month(month) = Kind::keyword(cursor.token()) else { + return None; + }; + let year = digits(cursor.token(), 4)?; + let hour = digits(cursor.token(), 2)?; + cursor.byte(b':').then_some(())?; + let minute = digits(cursor.token(), 2)?; + cursor.byte(b':').then_some(())?; + let second = digits(cursor.token(), 2)?; + let zone = zone_offset(cursor.token())?; + self.pos = self.bytes.len() - cursor.rest.len(); + Some([day, i64::from(month), year, hour, minute, second, zone]) + } + + fn consume(&mut self, byte: u8) { + let kind = match byte { + b'(' => { + if !self.in_quote { + self.comment_depth = self.comment_depth.saturating_add(1); + } + Kind::ParenOpen + } + b')' => { + if !self.in_quote { + self.comment_depth = self.comment_depth.saturating_sub(1); + } + Kind::ParenClose + } + b'[' => { + if !self.in_quote { + self.in_bracket = true; + } + Kind::BracketOpen + } + b']' => { + if !self.in_quote { + self.in_bracket = false; + } + Kind::BracketClose + } + b';' => { + if self.comment_depth == 0 { + self.in_date = true; + } + Kind::Semicolon + } + b'"' => { + self.in_quote = !self.in_quote; + Kind::Quote + } + b'<' => Kind::AngleOpen, + b'>' => Kind::AngleClose, + b'=' => Kind::Equal, + b'/' => Kind::Slash, + b',' => Kind::Comma, + b':' => Kind::Colon, + _ => return, + }; + self.pending = Some(kind); + } +} + +struct Cursor<'a> { + rest: &'a [u8], +} + +impl<'a> Cursor<'a> { + fn skip_space(&mut self) { + let spaces = self + .rest + .iter() + .position(|&byte| class(byte) != SPACE) + .unwrap_or(self.rest.len()); + self.rest = self.rest.get(spaces..).unwrap_or_default(); + } + + fn token(&mut self) -> &'a [u8] { + self.skip_space(); + let len = self + .rest + .iter() + .position(|&byte| class(byte) & WORD == 0) + .unwrap_or(self.rest.len()); + let (token, rest) = self.rest.split_at(len); + self.rest = rest; + token + } + + fn byte(&mut self, byte: u8) -> bool { + self.skip_space(); + match self.rest.split_first() { + Some((&first, rest)) if first == byte => { + self.rest = rest; + true + } + _ => false, + } + } +} + +fn is_day_name(token: &[u8]) -> bool { + token.len() == 3 + && DAY_NAMES + .iter() + .any(|name| token.eq_ignore_ascii_case(*name)) +} + +fn digits(token: &[u8], max: usize) -> Option<i64> { + if token.is_empty() || token.len() > max { + return None; + } + token.iter().try_fold(0, |value, &byte| { + byte.is_ascii_digit() + .then(|| value * 10 + i64::from(byte - b'0')) + }) +} + +fn zone_offset(token: &[u8]) -> Option<i64> { + let (&sign, digits_part) = token.split_first()?; + let value = digits(digits_part, 4).filter(|_| digits_part.len() == 4)?; + match sign { + b'+' => Some(value), + b'-' => Some(-value), + _ => None, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + Other, + From, + Date, +} + +struct DateParts { + parts: [i64; 7], + len: usize, +} + +impl DateParts { + fn push(&mut self, value: i64) { + if let Some(part) = self.parts.get_mut(self.len) { + *part = value; + self.len += 1; + } + } + + fn build(&self) -> Option<DateTime> { + let [day, month, year, hour, minute, second, zone] = self.parts; + if second == UNSET { + return None; + } + let (zone, is_plus) = match zone { + UNSET => (0, false), + zone if zone < 0 => (zone.wrapping_abs(), false), + zone => (zone, true), + }; + Some(DateTime { + year: match year { + 0..=49 => year + 2000, + 50..=99 => year + 1900, + _ => year, + } as u16, + month: month as u8, + day: day as u8, + hour: hour as u8, + minute: minute as u8, + second: second as u8, + tz_hour: (zone / 100) as u8, + tz_minute: (zone % 100) as u8, + tz_before_gmt: !is_plus, + }) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Expect { + Nothing, + From, + By, + Helo, + Id, + Via, + Ident, + For, + With, +} + +impl Expect { + fn skips(self, kind: Kind) -> bool { + match self { + Expect::From => kind == Kind::BracketOpen, + Expect::By => matches!(kind, Kind::BracketOpen | Kind::AngleOpen), + Expect::Helo => matches!(kind, Kind::Equal | Kind::BracketOpen | Kind::Colon), + Expect::Id | Expect::Ident => matches!( + kind, + Kind::Equal | Kind::AngleOpen | Kind::BracketOpen | Kind::Colon + ), + Expect::Via => kind == Kind::Equal, + Expect::For => matches!(kind, Kind::Equal | Kind::AngleOpen), + Expect::Nothing | Expect::With => false, + } + } +} + +struct Grammar<'c, 'a> { + ctx: &'c FieldCtx<'a>, + bytes: &'a [u8], + base: usize, + tokens: Tokenizer<'a>, + entry: ReceivedEntry, + state: State, + expect: Expect, + date: DateParts, +} + +impl<'c, 'a> Grammar<'c, 'a> { + fn new(ctx: &'c FieldCtx<'a>, value: Range<usize>) -> Self { + let bytes = ctx.bytes(value.clone()); + let bytes = bytes.get(..MAX_VALUE).unwrap_or(bytes); + Grammar { + ctx, + bytes, + base: value.start, + tokens: Tokenizer::new(bytes), + entry: ReceivedEntry::EMPTY, + state: State::Other, + expect: Expect::Nothing, + date: DateParts { + parts: [UNSET; 7], + len: 0, + }, + } + } + + fn run(mut self) -> ReceivedEntry { + while let Some(token) = self.tokens.next(self.expect == Expect::Nothing) { + if self.expect == Expect::Nothing || !self.expected(&token) { + self.dispatch(&token); + } + } + self.entry.date = self.date.build(); + self.entry + } + + fn expected(&mut self, token: &Token) -> bool { + let expect = self.expect; + if expect.skips(token.kind) { + return true; + } + match expect { + Expect::With => match token.kind { + Kind::Protocol(protocol) => self.entry.with = Some(protocol), + Kind::Semicolon + | Kind::Tls(_) + | Kind::By + | Kind::For + | Kind::From + | Kind::Id + | Kind::Via + | Kind::With => { + self.expect = Expect::Nothing; + return false; + } + _ => return true, + }, + Expect::For => { + if !token.is_email(self.bytes) { + self.expect = Expect::Nothing; + return false; + } + self.entry.for_ = self.text(token.range()); + } + _ if token.kind.is_separator() => { + self.expect = Expect::Nothing; + return false; + } + Expect::From => self.entry.from = self.host(token), + Expect::By => self.entry.by = self.host(token), + Expect::Helo => self.entry.helo = self.host(token), + Expect::Id => self.entry.id = self.text(token.range()), + Expect::Via => self.entry.via = self.text(token.range()), + Expect::Ident => self.entry.ident = self.text(token.range()), + Expect::Nothing => return false, + } + self.expect = Expect::Nothing; + true + } + + fn dispatch(&mut self, token: &Token) { + let in_comment = token.in_comment(); + match token.kind { + Kind::From if self.entry.from == HostEntry::None => { + self.clause(Expect::From, State::From); + } + Kind::By if !in_comment => self.clause(Expect::By, State::Other), + Kind::For if !in_comment => self.clause(Expect::For, State::Other), + Kind::Semicolon => { + self.state = State::Date; + if let Some(parts) = self.tokens.canonical_date() { + parts.into_iter().for_each(|part| self.date.push(part)); + } + } + Kind::Id if !in_comment => self.clause(Expect::Id, State::Other), + Kind::With if !in_comment => self.clause(Expect::With, State::Other), + Kind::Via if !in_comment => self.clause(Expect::Via, State::Other), + Kind::Ident if in_comment => self.expect = Expect::Ident, + Kind::Greeting(greeting) if self.state == State::From && in_comment => { + self.entry.helo_cmd = Some(greeting); + self.expect = Expect::Helo; + } + Kind::Month(month) if self.state == State::Date => { + self.date.push(i64::from(month)); + } + Kind::Tls(version) if in_comment && self.entry.tls_version.is_none() => { + self.entry.tls_version = Some(version); + } + Kind::Word => self.word(token), + _ => (), + } + } + + fn clause(&mut self, expect: Expect, state: State) { + self.expect = expect; + self.state = state; + } + + fn word(&mut self, token: &Token) { + let in_comment = token.in_comment(); + match self.state { + State::From => { + if let Some(ip) = token.ip(self.bytes) { + if token.in_bracket() || (in_comment && self.entry.from_ip.is_none()) { + self.entry.from_ip = Some(ip); + } + return; + } + if token.is_domain() { + if in_comment { + self.entry.from_iprev = self.text(token.range()); + } + return; + } + if token.is_email(self.bytes) { + let range = token.range(); + let end = range.end - usize::from(token.text(self.bytes).ends_with(b"@")); + self.entry.ident = self.text(range.start..end); + return; + } + } + State::Date => { + if let Some(value) = token.integer(self.bytes) { + self.date.push(value); + return; + } + } + State::Other => (), + } + if (in_comment || self.entry.tls_cipher.is_none()) && token.is_cipher(self.bytes) { + self.entry.tls_cipher = self.text(token.range()); + } + } + + fn host(&self, token: &Token) -> HostEntry { + match token.ip(self.bytes) { + Some(ip) => HostEntry::Ip(ip), + None => HostEntry::Name(self.text(token.range())), + } + } + + fn text(&self, range: Range<usize>) -> Str { + self.ctx + .try_borrow(self.base + range.start..self.base + range.end) + .unwrap_or(Str::EMPTY) + } +} + +#[cfg(test)] +mod tests { + use crate::{HeaderForm, Host, MessageParser, Received, fields::tests::load_tests}; + use serde_json::{Map, Value as Json, json}; + + fn host_json(host: Host<'_>) -> Json { + match host { + Host::Name(name) => json!({ "Name": name }), + Host::IpAddr(ip) => json!({ "IpAddr": ip.to_string() }), + } + } + + fn received_json(received: Received<'_>) -> Json { + let debug = |value: &dyn std::fmt::Debug| json!(format!("{value:?}")); + let fields = [ + ("from", received.from().map(host_json)), + ( + "from_ip", + received.from_ip().map(|ip| json!(ip.to_string())), + ), + ("from_iprev", received.from_iprev().map(|text| json!(text))), + ("by", received.by().map(host_json)), + ("for_", received.for_().map(|text| json!(text))), + ("with", received.with().map(|with| debug(&with))), + ( + "tls_version", + received.tls_version().map(|version| debug(&version)), + ), + ("tls_cipher", received.tls_cipher().map(|text| json!(text))), + ("id", received.id().map(|text| json!(text))), + ("ident", received.ident().map(|text| json!(text))), + ("helo", received.helo().map(host_json)), + ("helo_cmd", received.helo_cmd().map(|cmd| debug(&cmd))), + ("via", received.via().map(|text| json!(text))), + ( + "date", + received.date().map(|date| { + json!({ + "year": date.year, + "month": date.month, + "day": date.day, + "hour": date.hour, + "minute": date.minute, + "second": date.second, + "tz_before_gmt": date.tz_before_gmt, + "tz_hour": date.tz_hour, + "tz_minute": date.tz_minute, + }) + }), + ), + ]; + Json::Object( + fields + .into_iter() + .filter_map(|(name, value)| Some((name.to_string(), value?))) + .collect::<Map<_, _>>(), + ) + } + + fn parse(header: &[u8]) -> Json { + HeaderForm::Received + .parse(header) + .value() + .as_received() + .map_or(Json::Null, received_json) + } + + fn without_nulls(expected: Json) -> Json { + match expected { + Json::Object(fields) => Json::Object( + fields + .into_iter() + .filter(|(_, value)| !value.is_null()) + .collect(), + ), + other => other, + } + } + + #[test] + fn received_fixtures() { + let tests = load_tests("received.json"); + assert_eq!(tests.len(), 202); + for (header, expected) in tests { + assert_eq!( + parse(header.as_bytes()), + without_nulls(expected), + "{header:?}" + ); + } + } + + #[test] + fn received_edge_cases() { + assert_eq!( + parse(b"from \xff\xfe by y\n"), + json!({ "from": { "Name": "" }, "by": { "Name": "y" } }) + ); + } + + #[test] + fn ipv4_matches_std() { + const GROUPS: [&str; 22] = [ + "", "0", "00", "01", "1", "9", "10", "99", "100", "199", "200", "249", "250", "255", + "256", "299", "300", "999", "0000", "1000", "025", "x", + ]; + let mut text = String::with_capacity(32); + for a in GROUPS { + for b in GROUPS { + for c in GROUPS { + for d in GROUPS { + for tail in ["", ".", ".1", "..1"] { + text.clear(); + text.push_str(&[a, b, c, d].join(".")); + text.push_str(tail); + assert_eq!( + super::ipv4(text.as_bytes()), + text.parse::<std::net::Ipv4Addr>().ok(), + "{text:?}" + ); + } + } + } + } + } + for text in [ + "1.2.3", "1.2", "1", "", ".", "...", "1..2.3", "+1.2.3.4", "1.2.3.4 ", + ] { + assert_eq!(super::ipv4(text.as_bytes()), text.parse().ok(), "{text:?}"); + } + } + + #[test] + fn keyword_table() { + for (keyword, kind) in super::KEYWORDS { + assert_eq!(super::Kind::keyword(keyword), kind, "{keyword:?}"); + let upper = keyword.to_ascii_uppercase(); + assert_eq!(super::Kind::keyword(&upper), kind, "{upper:?}"); + } + } + + #[test] + fn received_truncated_fold() { + for message in [ + &b"Received:\n\t"[..], + b"Received:\r\n ", + b"Received: x\r\n ", + b"Received: x\r\n\t", + b"Received: x\n ", + b"Received: x\n\t", + b"Received: x\r\n ", + b"Received: x\r\n \t", + b"Received: x\r\n \t ", + b"Received: x\r\n \r", + b"Received: x\r\n \r\n", + b"Received: x\r\n \r\nbody", + b"Received: x\r\n y\r\n ", + b"Received: x;\r\n ", + b"To: a@b\r\nReceived: x\r\n ", + b"Received: from x (y)\r\n\t", + b"Received: from x by y;\r\n\t", + b"Received: ", + b"Received:", + b"Received: x", + ] { + let parser = MessageParser::default(); + let _ = parser.parse(message); + let _ = parser.parse_headers(message); + let _ = parse(message.get(9..).unwrap_or_default()); + } + } +} diff --git a/src/fields/tests.rs b/src/fields/tests.rs new file mode 100644 index 0000000..8c816cb --- /dev/null +++ b/src/fields/tests.rs @@ -0,0 +1,178 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{FieldCtx, HeaderForm, first_field, parse_value}; +use crate::{DateTime, HeaderValue, store::MessageData, view::Resolver}; +use serde_json::{Value as Json, json}; +use std::path::PathBuf; + +pub(crate) fn load_tests(name: &str) -> Vec<(String, Json)> { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("resources") + .join(name); + let bytes = std::fs::read(&path).expect("fixture file"); + let tests: Vec<Json> = serde_json::from_slice(&bytes).expect("valid JSON"); + tests + .into_iter() + .filter_map(|test| { + Some(( + test.get("header")?.as_str()?.to_string(), + test.get("expected")?.clone(), + )) + }) + .collect() +} + +fn content_type_json(value: HeaderValue<'_>) -> Json { + match value { + HeaderValue::ContentType(content_type) => { + let attributes: Vec<Json> = content_type + .attributes() + .map(|(name, value)| json!([name, value])) + .collect(); + json!({ + "c_type": content_type.ctype(), + "c_subtype": content_type.subtype(), + "attributes": if attributes.is_empty() { Json::Null } else { Json::Array(attributes) }, + }) + } + _ => Json::Null, + } +} + +fn normalize(expected: Json) -> Json { + match expected { + Json::Object(fields) => { + let field = |name: &str| fields.get(name).cloned().unwrap_or(Json::Null); + json!({ + "c_type": field("c_type"), + "c_subtype": field("c_subtype"), + "attributes": field("attributes"), + }) + } + other => other, + } +} + +#[test] +fn content_type_fixtures() { + let tests = load_tests("content_type.json"); + assert_eq!(tests.len(), 120); + for (header, expected) in tests { + let parsed = HeaderForm::ContentType.parse(header.as_bytes()); + assert_eq!( + content_type_json(parsed.value()), + normalize(expected), + "{header:?}" + ); + } +} + +#[test] +fn raw_values() { + let inputs = [ + ("Saying Hello\nMessage-Id", Some("Saying Hello")), + ("Re: Saying Hello\r\n \r\nFrom:", Some("Re: Saying Hello")), + ( + concat!( + " from x.y.test\n by example.net\n via TCP\n", + " with ESMTP\n id ABC12345\n ", + "for <mary@example.net>; 21 Nov 1997 10:05:43 -0600\n" + ), + Some(concat!( + "from x.y.test\n by example.net\n via TCP\n", + " with ESMTP\n id ABC12345\n ", + "for <mary@example.net>; 21 Nov 1997 10:05:43 -0600" + )), + ), + ("Re: Saying Hello", Some("Re: Saying Hello")), + (" \r\n", Some("")), + ("caf\u{e9}\n", Some("café")), + ]; + for (input, expected) in inputs { + let parsed = HeaderForm::Raw.parse(input.as_bytes()); + assert_eq!(parsed.value().as_text(), expected, "{input:?}"); + } + let parsed = HeaderForm::Raw.parse(b" caf\xe9 \n"); + assert_eq!(parsed.value().as_text(), Some("caf\u{fffd}")); +} + +#[test] +fn ignored_values() { + assert!(HeaderForm::Ignore.parse(b" anything\n").value().is_empty()); +} + +fn stored(form: HeaderForm, input: &[u8]) -> (bool, Option<String>, Option<DateTime>) { + let range = first_field(input, 0..input.len()); + let mut data = MessageData::default(); + let value = parse_value(form, &mut FieldCtx::new(input, &mut data), range); + let value = HeaderValue::new(Resolver::new(input, &data.strings), &data, value); + ( + value.is_empty(), + value.as_text().map(str::to_string), + value.as_datetime(), + ) +} + +#[test] +fn standalone_values_match_the_store_path() { + let mut inputs: Vec<Vec<u8>> = [ + "date.json", + "unstructured.json", + "address.json", + "received.json", + ] + .iter() + .flat_map(|name| load_tests(name)) + .map(|(header, _)| header.into_bytes()) + .collect(); + for sample in [ + &b""[..], + b" ", + b"\r\n", + b" plain value\r\n", + b"plain\r\n next: x\r\n", + b" folded\r\n value\r\n", + b" =?utf-8?q?caf=C3=A9?=\n", + b" caf\xc3\xa9\n", + b" caf\xe9\n", + b" \xff\xfe\r\n", + b"a\rb\n", + b"Tue, 1 Jul 2003 10:52:37 +0200\r\n", + b"Tue, 1 Jul 2003 10:52:37 +0200\nX-y: -0500", + b" 1 Jul 2003 10:52:37 -0700 (PDT)", + b"junk\n", + ] { + inputs.push(sample.to_vec()); + } + for input in &inputs { + for form in [ + HeaderForm::Raw, + HeaderForm::Text, + HeaderForm::Date, + HeaderForm::Ignore, + ] { + let parsed = form.parse(input); + let value = parsed.value(); + assert_eq!( + ( + value.is_empty(), + value.as_text().map(str::to_string), + value.as_datetime() + ), + stored(form, input), + "{form:?} {:?}", + String::from_utf8_lossy(input) + ); + } + let text = String::from_utf8_lossy(input); + assert_eq!( + DateTime::parse_rfc822(&text), + stored(HeaderForm::Date, text.as_bytes()).2, + "{text:?}" + ); + } +} diff --git a/src/parsers/fields/thread.rs b/src/fields/thread.rs similarity index 85% rename from src/parsers/fields/thread.rs rename to src/fields/thread.rs index 9a57a96..e353223 100644 --- a/src/parsers/fields/thread.rs +++ b/src/fields/thread.rs @@ -4,8 +4,12 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ +use std::str; + const MAX_PREFIX_LEN: usize = 40; const MAX_GENERIC_PREFIX_CHARS: usize = 4; +const LOWERCASE_BUFFER_LEN: usize = 64; +const URL_SCHEME_SEPARATOR: &str = "://"; fn is_re_prefix(prefix: &str) -> bool { hashify::set! {prefix.as_bytes(), @@ -174,20 +178,54 @@ fn is_generic_prefix(prefix: &str) -> bool { char_count > 0 } -fn is_prefix(text: &str, token_start: usize, token_end: usize, separator: usize) -> bool { - if is_known_prefix(text[token_start..token_end].to_lowercase().as_ref()) { - return true; - } - - if token_end == separator { - !text[separator..].starts_with("://") - && is_generic_prefix(text[token_start..token_end].to_lowercase().as_ref()) - } else { - let span = text[token_start..separator].trim_end(); - span.len() <= MAX_PREFIX_LEN && is_known_prefix(span.to_lowercase().as_ref()) +fn with_lowercase<T>(text: &str, f: impl FnOnce(&str) -> T) -> T { + let mut buffer = [0u8; LOWERCASE_BUFFER_LEN]; + match buffer.get_mut(..text.len()) { + Some(lower) if text.is_ascii() => { + lower.copy_from_slice(text.as_bytes()); + lower.make_ascii_lowercase(); + f(str::from_utf8(lower).unwrap_or_default()) + } + _ => f(&text.to_lowercase()), } } +fn is_prefix(text: &str, token_start: usize, token_end: usize, separator: usize) -> bool { + let token = text.get(token_start..token_end).unwrap_or_default(); + let is_token_prefix = with_lowercase(token, |token| { + if is_known_prefix(token) { + Some(true) + } else if token_end == separator { + Some( + !text + .get(separator..) + .unwrap_or_default() + .starts_with(URL_SCHEME_SEPARATOR) + && is_generic_prefix(token), + ) + } else { + None + } + }); + is_token_prefix.unwrap_or_else(|| { + let span = text + .get(token_start..separator) + .unwrap_or_default() + .trim_end(); + span.len() <= MAX_PREFIX_LEN && with_lowercase(span, is_known_prefix) + }) +} + +/// The thread name of a subject: the subject without reply and forward +/// prefixes (`Re:`, `Fwd:` and their translations, with counters such as +/// `Re[2]:`), bracketed list tags and trailing `(fwd)` markers, as used to +/// group messages into threads. Borrows from `text`. +/// +/// ``` +/// use mail_parser::thread_name; +/// +/// assert_eq!(thread_name("Re: Fwd: [list] Lunch on Friday"), "Lunch on Friday"); +/// ``` pub fn thread_name(text: &str) -> &str { let mut token_start = 0; let mut token_end = 0; @@ -257,15 +295,17 @@ pub fn thread_name(text: &str) -> &str { token_end = pos; } - let prefix = text[token_start..token_end].to_lowercase(); - if is_fwd_prefix(prefix.as_ref()) { - token_found = false; - seen_blob_header = true; - } else if seen_blob_header && is_re_prefix(prefix.as_ref()) { - token_found = false; - } else { - in_blob_ignore = true; - } + let token = text.get(token_start..token_end).unwrap_or_default(); + with_lowercase(token, |prefix| { + if is_fwd_prefix(prefix) { + token_found = false; + seen_blob_header = true; + } else if seen_blob_header && is_re_prefix(prefix) { + token_found = false; + } else { + in_blob_ignore = true; + } + }); } _ if ch.is_whitespace() => { if token_end == 0 { @@ -287,52 +327,55 @@ pub fn thread_name(text: &str) -> &str { if last_blob_end > thread_name_start || (fwd_start > 0 && last_blob_end > fwd_start && fwd_start > thread_name_start) { - let result = trim_trailing_fwd(&text[last_blob_end..]); + let result = trim_trailing_fwd(text.get(last_blob_end..).unwrap_or_default()); if !result.is_empty() { return result; } } if fwd_start > 0 && thread_name_start < fwd_start { - let result = trim_trailing_fwd(&text[fwd_start..fwd_end]); + let result = trim_trailing_fwd(text.get(fwd_start..fwd_end).unwrap_or_default()); if !result.is_empty() { return result; } } - trim_trailing_fwd(&text[thread_name_start..]) + trim_trailing_fwd(text.get(thread_name_start..).unwrap_or_default()) } -pub fn trim_trailing_fwd(text: &str) -> &str { +fn trim_trailing_fwd(text: &str) -> &str { let mut in_parentheses = false; let mut trim_end = true; - let mut end_found = false; let mut text_start = 0; let mut text_end = text.len(); let mut fwd_end = 0; for (pos, ch) in text.char_indices().rev() { - match ch { - '(' if !end_found => { + let end_found = match ch { + '(' => { if in_parentheses { in_parentheses = false; if fwd_end - pos > 2 - && is_fwd_prefix(text[pos + 1..fwd_end].to_lowercase().as_ref()) + && with_lowercase( + text.get(pos + 1..fwd_end).unwrap_or_default(), + is_fwd_prefix, + ) { text_end = pos; trim_end = true; continue; } } - end_found = true; + true } - ')' if !end_found => { - if !in_parentheses { + ')' => { + if in_parentheses { + true + } else { in_parentheses = true; fwd_end = pos; - } else { - end_found = true; + false } } _ if ch.is_whitespace() => { @@ -341,29 +384,27 @@ pub fn trim_trailing_fwd(text: &str) -> &str { } continue; } - _ => { - if !in_parentheses && !end_found { - end_found = true; - } - } + _ => !in_parentheses, + }; + + if end_found { + let start = text + .char_indices() + .find(|(_, ch)| !ch.is_whitespace()) + .map_or(pos, |(start, _)| start); + return text.get(start..text_end).unwrap_or_default(); } - if trim_end { - trim_end = false; - } + trim_end = false; text_start = pos; } - if text_end >= text_start { - &text[text_start..text_end] - } else { - "" - } + text.get(text_start..text_end).unwrap_or_default() } #[cfg(test)] mod tests { - use crate::parsers::fields::thread::{thread_name, trim_trailing_fwd}; + use super::{thread_name, trim_trailing_fwd}; #[test] fn parse_thread_name() { diff --git a/src/fields/unstructured.rs b/src/fields/unstructured.rs new file mode 100644 index 0000000..2bcc3e0 --- /dev/null +++ b/src/fields/unstructured.rs @@ -0,0 +1,324 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{FieldCtx, trim_fws}; +use crate::{ + decoders::charsets, + store::{Str, Value}, +}; +use encodify::rfc2047::decode_text_append_with; +use memchr::{memchr2, memchr3_iter}; +use std::ops::Range; + +#[inline] +pub(crate) fn parse_unstructured(ctx: &mut FieldCtx<'_>, value: Range<usize>) -> Value { + let value = ctx.trim_fws(value); + if value.is_empty() { + return Value::Text(Str::EMPTY); + } + let shape = Shape::of(ctx.bytes(value.clone())); + Value::Text(shaped(ctx, value, shape)) +} + +fn shaped(ctx: &mut FieldCtx<'_>, value: Range<usize>, shape: Shape) -> Str { + let bytes = ctx.bytes(value.clone()); + match shape { + Shape::Line => ctx.borrow(value), + Shape::Folded => match simdutf8::basic::from_utf8(bytes) { + Ok(text) => ctx.push_with(|pool| unfold(text, pool)), + Err(_) => decode(ctx, bytes), + }, + Shape::Encoded => decode(ctx, bytes), + } +} + +pub(crate) struct Pending { + value: Range<usize>, + shape: Shape, +} + +impl Pending { + pub(crate) fn parse(self, ctx: &mut FieldCtx<'_>) -> Value { + Value::Text(shaped(ctx, self.value, self.shape)) + } +} + +pub(crate) fn standalone(src: &[u8], value: Range<usize>) -> Result<Value, Pending> { + let value = trim_fws(src, value); + if value.is_empty() { + return Ok(Value::Text(Str::EMPTY)); + } + let shape = Shape::of(src.get(value.clone()).unwrap_or_default()); + if shape == Shape::Line + && let Some(text) = Str::borrow(src, value.clone()) + { + return Ok(Value::Text(text)); + } + Err(Pending { value, shape }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Shape { + Line, + Folded, + Encoded, +} + +impl Shape { + fn of(bytes: &[u8]) -> Shape { + let mut shape = Shape::Line; + for at in memchr3_iter(b'\n', b'\r', b'=', bytes) { + match bytes.get(at..) { + Some([b'=', b'?', ..]) => return Shape::Encoded, + Some([b'=', ..]) => {} + _ => shape = Shape::Folded, + } + } + shape + } +} + +#[inline(never)] +fn unfold(text: &str, out: &mut String) { + out.reserve(text.len()); + let mut rest = text; + while let Some((line, tail)) = + memchr2(b'\n', b'\r', rest.as_bytes()).and_then(|at| rest.split_at_checked(at)) + { + out.push_str(line.trim_end_matches([' ', '\t'])); + out.push(' '); + rest = tail.trim_start_matches([' ', '\t', '\r', '\n']); + } + out.push_str(rest); +} + +fn decode(ctx: &mut FieldCtx<'_>, bytes: &[u8]) -> Str { + let mut scratch = ctx.take_bytes_scratch(); + let text = ctx.push_with(|pool| { + decode_text_append_with(bytes, charsets::decode_append, &mut scratch, pool); + }); + ctx.put_bytes_scratch(scratch); + text +} + +#[cfg(test)] +mod tests { + use super::{Shape, parse_unstructured}; + use crate::{ + HeaderForm, MessageParser, + decoders::charsets, + fields::{FieldCtx, is_fws, tests::load_tests}, + store::{MessageData, Value}, + }; + use encodify::rfc2047; + use std::path::PathBuf; + + fn parse(input: &[u8]) -> Option<String> { + let mut data = MessageData::default(); + let mut ctx = FieldCtx::new(input, &mut data); + let Value::Text(text) = parse_unstructured(&mut ctx, 0..input.len()) else { + return None; + }; + Some(ctx.resolve(text).to_string()) + } + + fn reference(input: &[u8]) -> Option<String> { + Some(if input.iter().all(|&byte| is_fws(byte)) { + String::new() + } else { + rfc2047::decode_text(input, charsets::decode_append).into_owned() + }) + } + + #[test] + fn fixtures() { + let tests = load_tests("unstructured.json"); + assert_eq!(tests.len(), 54); + for (header, expected) in tests { + let parsed = HeaderForm::Text.parse(header.as_bytes()); + assert_eq!(parsed.value().as_text(), expected.as_str(), "{header:?}"); + } + } + + #[test] + fn decided_rules() { + let cases: [(&[u8], Option<&str>); 2] = [ + (b" caf\xe9 \xff\n", Some("caf\u{fffd} \u{fffd}")), + (b" caf\xe9\r\n \xffx\r\n", Some("caf\u{fffd} \u{fffd}x")), + ]; + for (input, expected) in cases { + assert_eq!( + parse(input).as_deref(), + expected, + "{:?}", + String::from_utf8_lossy(input) + ); + } + } + + #[test] + fn shapes() { + for (input, shape) in [ + (&b"plain"[..], Shape::Line), + (b"a = b", Shape::Line), + (b"a =", Shape::Line), + (b"a\r\n b", Shape::Folded), + (b"a\rb", Shape::Folded), + (b"a\n b = c", Shape::Folded), + (b"a =?", Shape::Encoded), + (b"a\n b =?x", Shape::Encoded), + (b"=?utf-8?q?a?=", Shape::Encoded), + ] { + assert_eq!(Shape::of(input), shape, "{input:?}"); + } + } + + #[test] + fn writes_the_pool_only_when_rewriting() { + for (input, pooled) in [ + (&b" plain value\r\n"[..], false), + (b" caf\xc3\xa9 \xe2\x82\xac\n", false), + (b" a = b\n", false), + (b" folded\r\n value\r\n", true), + (b" =?utf-8?q?a?=\n", true), + (b" caf\xe9\n", true), + ] { + let mut data = MessageData::default(); + let value = parse_unstructured(&mut FieldCtx::new(input, &mut data), 0..input.len()); + assert!(matches!(value, Value::Text(_)), "{input:?}"); + assert_eq!(!data.strings.is_empty(), pooled, "{input:?}"); + } + } + + #[test] + fn matches_decode_text_on_generated_input() { + const FRAGMENTS: &[&[u8]] = &[ + b"a", + b"Re:", + b" ", + b" ", + b"\t", + b"\r", + b"\n", + b"\r\n", + b"\n ", + b"\r\n\t", + b" \r\n ", + b"=", + b"?", + b"=?", + b"?=", + b"_", + b"=?utf-8?q?", + b"=?UTF-8?B?", + b"=?iso-8859-1?q?", + b"=?x?q?", + b"=?utf 8?q?", + b"=?utf-8*en?Q?", + b"=?*en?q?", + b"=?\xe9?q?", + b"=?utf-8?x?", + b"caf=C3=A9", + b"=E9", + b"w6k=", + b"w6k", + b"=ZZ", + b"\xc3\xa9", + b"\xe3\x83\x8f", + b"\xff", + b"\xc3", + b"\x00", + b"*en", + b"=?utf-8?q?caf=C3?= =?utf-8?q?=A9?=", + b"=?utf-8?q?a?=", + b" =?utf-8?q?x?= ", + b"=?iso-8859-1?b?6Q==?=", + b"=?utf-16le?b?YQBiAA==?=", + b"=?utf-7?q?+AKM-?=", + b"=?utf-8?b?w6k=?=\r\n =?UTF-8?Q?=C3=A9?=", + ]; + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let mut input = Vec::with_capacity(512); + for _ in 0..60_000 { + input.clear(); + let fragments = next() % 24; + for _ in 0..fragments { + let pick = (next() % FRAGMENTS.len() as u64) as usize; + input.extend_from_slice(FRAGMENTS.get(pick).copied().unwrap_or_default()); + } + assert_eq!( + parse(&input), + reference(&input), + "{:?}", + String::from_utf8_lossy(&input) + ); + } + } + + #[test] + fn reuses_the_bytes_scratch() { + let input = b" =?utf-8?q?caf=C3=A9?= =?utf-8?b?w6k=?=\n"; + let mut data = MessageData::default(); + for _ in 0..2 { + let value = parse_unstructured(&mut FieldCtx::new(input, &mut data), 0..input.len()); + let Value::Text(text) = value else { + panic!("text expected"); + }; + assert_eq!(text.resolve(input, &data.strings), "caf\u{e9}\u{e9}"); + assert!(data.scratch.bytes.capacity() > 0); + } + } + + #[test] + fn matches_decode_text_on_every_fixture_header() { + let eml = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("resources") + .join("eml"); + let mut suites: Vec<PathBuf> = std::fs::read_dir(&eml) + .expect("eml directory") + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.is_dir()) + .collect(); + suites.sort(); + let mut values = 0; + for suite in suites { + let mut files: Vec<PathBuf> = std::fs::read_dir(&suite) + .expect("suite directory") + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "eml")) + .collect(); + files.sort(); + for file in files { + let raw = std::fs::read(&file).expect("fixture"); + let Some(message) = MessageParser::new().parse(&raw) else { + continue; + }; + for part in message.parts() { + for header in part.headers().iter() { + let value = header.raw_value(); + assert_eq!( + parse(value), + reference(value), + "{}: {:?}", + file.display(), + String::from_utf8_lossy(value) + ); + values += 1; + } + } + } + } + assert!(values > 1_000, "{values}"); + } +} diff --git a/src/header_name.rs b/src/header_name.rs new file mode 100644 index 0000000..fc35b49 --- /dev/null +++ b/src/header_name.rs @@ -0,0 +1,930 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use std::{ + borrow::Cow, + cmp::Ordering, + fmt, + hash::{Hash, Hasher}, +}; + +macro_rules! header_names { + ($($variant:ident, $name:literal, $lc:literal;)+) => { + /// A header field name: one of the known names, or any other name + /// with its original spelling. + /// + /// Names compare ASCII case-insensitively, so `Other("x-custom")` + /// equals `Other("X-Custom")`, and an `Other` spelled like a known + /// name equals, hashes and orders as that name. Known names are + /// parsed into their variant by [`HeaderName::parse`], by the `From` + /// conversions (which keep any other string as written in `Other`) + /// and by the message parser, and keep their canonical spelling in + /// [`HeaderName::as_str`]; [`crate::Header::raw_name`] gives the + /// spelling used in a message. + /// + /// ``` + /// use mail_parser::HeaderName; + /// + /// assert_eq!(HeaderName::parse("content-type"), Some(HeaderName::ContentType)); + /// assert_eq!(HeaderName::ContentType.as_str(), "Content-Type"); + /// let custom = HeaderName::parse("X-Custom").expect("valid name"); + /// assert!(custom.is_other()); + /// assert_eq!(custom, HeaderName::from("x-custom")); + /// ``` + #[derive(Debug, Clone)] + #[non_exhaustive] + pub enum HeaderName<'x> { + $( + #[doc = concat!("`", $name, "`.")] + $variant, + )+ + /// Any other name, with its original spelling. + Other(Cow<'x, str>), + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[repr(u16)] + pub(crate) enum HeaderId { + $($variant,)+ + } + + pub(crate) const KNOWN_NAMES: usize = [$($lc,)+].len(); + + static CANONICAL: [&str; KNOWN_NAMES] = [$($name,)+]; + + const LOWERCASE: [&str; KNOWN_NAMES] = [$($lc,)+]; + + static VARIANTS: [HeaderName<'static>; KNOWN_NAMES] = [$(HeaderName::$variant,)+]; + + impl HeaderName<'_> { + pub(crate) fn id(&self) -> u16 { + match self { + $(HeaderName::$variant => HeaderId::$variant as u16,)+ + HeaderName::Other(_) => OTHER_ID, + } + } + } + + pub(crate) fn lookup_lowercase(name: &[u8]) -> Option<u16> { + hashify::fnc_map!(name, + $($lc => Some(HeaderId::$variant as u16),)+ + _ => None + ) + } + }; +} + +pub(crate) const OTHER_ID: u16 = u16::MAX; +pub(crate) const FIRST_VENDOR: u16 = HeaderId::XOriginalTo as u16; + +header_names! { + Subject, "Subject", "subject"; + From, "From", "from"; + To, "To", "to"; + Cc, "Cc", "cc"; + Date, "Date", "date"; + Bcc, "Bcc", "bcc"; + ReplyTo, "Reply-To", "reply-to"; + Sender, "Sender", "sender"; + Comments, "Comments", "comments"; + InReplyTo, "In-Reply-To", "in-reply-to"; + Keywords, "Keywords", "keywords"; + Received, "Received", "received"; + MessageId, "Message-ID", "message-id"; + References, "References", "references"; + ReturnPath, "Return-Path", "return-path"; + MimeVersion, "MIME-Version", "mime-version"; + ContentDescription, "Content-Description", "content-description"; + ContentId, "Content-ID", "content-id"; + ContentLanguage, "Content-Language", "content-language"; + ContentLocation, "Content-Location", "content-location"; + ContentTransferEncoding, "Content-Transfer-Encoding", "content-transfer-encoding"; + ContentType, "Content-Type", "content-type"; + ContentDisposition, "Content-Disposition", "content-disposition"; + ResentTo, "Resent-To", "resent-to"; + ResentFrom, "Resent-From", "resent-from"; + ResentBcc, "Resent-Bcc", "resent-bcc"; + ResentCc, "Resent-Cc", "resent-cc"; + ResentSender, "Resent-Sender", "resent-sender"; + ResentDate, "Resent-Date", "resent-date"; + ResentMessageId, "Resent-Message-ID", "resent-message-id"; + ListArchive, "List-Archive", "list-archive"; + ListHelp, "List-Help", "list-help"; + ListId, "List-ID", "list-id"; + ListOwner, "List-Owner", "list-owner"; + ListPost, "List-Post", "list-post"; + ListSubscribe, "List-Subscribe", "list-subscribe"; + ListUnsubscribe, "List-Unsubscribe", "list-unsubscribe"; + DkimSignature, "DKIM-Signature", "dkim-signature"; + ArcAuthenticationResults, "ARC-Authentication-Results", "arc-authentication-results"; + ArcMessageSignature, "ARC-Message-Signature", "arc-message-signature"; + ArcSeal, "ARC-Seal", "arc-seal"; + Dkim2Signature, "DKIM2-Signature", "dkim2-signature"; + MessageInstance, "Message-Instance", "message-instance"; + AcceptLanguage, "Accept-Language", "accept-language"; + AlternateRecipient, "Alternate-Recipient", "alternate-recipient"; + ArchivedAt, "Archived-At", "archived-at"; + AuthenticationResults, "Authentication-Results", "authentication-results"; + AutoSubmitted, "Auto-Submitted", "auto-submitted"; + Autoforwarded, "Autoforwarded", "autoforwarded"; + Autosubmitted, "Autosubmitted", "autosubmitted"; + ContentAlternative, "Content-Alternative", "content-alternative"; + ContentDuration, "Content-Duration", "content-duration"; + ContentFeatures, "Content-features", "content-features"; + ContentMd5, "Content-MD5", "content-md5"; + ContentTranslationType, "Content-Translation-Type", "content-translation-type"; + Conversion, "Conversion", "conversion"; + ConversionWithLoss, "Conversion-With-Loss", "conversion-with-loss"; + DlExpansionHistory, "DL-Expansion-History", "dl-expansion-history"; + DeferredDelivery, "Deferred-Delivery", "deferred-delivery"; + DeliveryDate, "Delivery-Date", "delivery-date"; + DiscardedX400IpmsExtensions, "Discarded-X400-IPMS-Extensions", "discarded-x400-ipms-extensions"; + DiscardedX400MtsExtensions, "Discarded-X400-MTS-Extensions", "discarded-x400-mts-extensions"; + DiscloseRecipients, "Disclose-Recipients", "disclose-recipients"; + DispositionNotificationOptions, "Disposition-Notification-Options", "disposition-notification-options"; + DispositionNotificationTo, "Disposition-Notification-To", "disposition-notification-to"; + DowngradedFinalRecipient, "Downgraded-Final-Recipient", "downgraded-final-recipient"; + DowngradedInReplyTo, "Downgraded-In-Reply-To", "downgraded-in-reply-to"; + DowngradedMessageId, "Downgraded-Message-Id", "downgraded-message-id"; + DowngradedOriginalRecipient, "Downgraded-Original-Recipient", "downgraded-original-recipient"; + DowngradedReferences, "Downgraded-References", "downgraded-references"; + Encoding, "Encoding", "encoding"; + Expires, "Expires", "expires"; + GenerateDeliveryReport, "Generate-Delivery-Report", "generate-delivery-report"; + HpOuter, "HP-Outer", "hp-outer"; + Importance, "Importance", "importance"; + IncompleteCopy, "Incomplete-Copy", "incomplete-copy"; + Language, "Language", "language"; + LatestDeliveryTime, "Latest-Delivery-Time", "latest-delivery-time"; + ListUnsubscribePost, "List-Unsubscribe-Post", "list-unsubscribe-post"; + MessageContext, "Message-Context", "message-context"; + MessageType, "Message-Type", "message-type"; + MmhsExemptedAddress, "MMHS-Exempted-Address", "mmhs-exempted-address"; + MmhsExtendedAuthorisationInfo, "MMHS-Extended-Authorisation-Info", "mmhs-extended-authorisation-info"; + MmhsSubjectIndicatorCodes, "MMHS-Subject-Indicator-Codes", "mmhs-subject-indicator-codes"; + MmhsHandlingInstructions, "MMHS-Handling-Instructions", "mmhs-handling-instructions"; + MmhsMessageInstructions, "MMHS-Message-Instructions", "mmhs-message-instructions"; + MmhsCodressMessageIndicator, "MMHS-Codress-Message-Indicator", "mmhs-codress-message-indicator"; + MmhsOriginatorReference, "MMHS-Originator-Reference", "mmhs-originator-reference"; + MmhsPrimaryPrecedence, "MMHS-Primary-Precedence", "mmhs-primary-precedence"; + MmhsCopyPrecedence, "MMHS-Copy-Precedence", "mmhs-copy-precedence"; + MmhsMessageType, "MMHS-Message-Type", "mmhs-message-type"; + MmhsOtherRecipientsIndicatorTo, "MMHS-Other-Recipients-Indicator-To", "mmhs-other-recipients-indicator-to"; + MmhsOtherRecipientsIndicatorCc, "MMHS-Other-Recipients-Indicator-CC", "mmhs-other-recipients-indicator-cc"; + MmhsAcp127MessageIdentifier, "MMHS-Acp127-Message-Identifier", "mmhs-acp127-message-identifier"; + MmhsOriginatorPlad, "MMHS-Originator-PLAD", "mmhs-originator-plad"; + MtPriority, "MT-Priority", "mt-priority"; + Organization, "Organization", "organization"; + OriginalEncodedInformationTypes, "Original-Encoded-Information-Types", "original-encoded-information-types"; + OriginalFrom, "Original-From", "original-from"; + OriginalMessageId, "Original-Message-ID", "original-message-id"; + OriginalRecipient, "Original-Recipient", "original-recipient"; + OriginatorReturnAddress, "Originator-Return-Address", "originator-return-address"; + OriginalSubject, "Original-Subject", "original-subject"; + PicsLabel, "PICS-Label", "pics-label"; + PreventNonDeliveryReport, "Prevent-NonDelivery-Report", "prevent-nondelivery-report"; + Priority, "Priority", "priority"; + ReceivedSpf, "Received-SPF", "received-spf"; + ReplyBy, "Reply-By", "reply-by"; + RequireRecipientValidSince, "Require-Recipient-Valid-Since", "require-recipient-valid-since"; + Sensitivity, "Sensitivity", "sensitivity"; + Solicitation, "Solicitation", "solicitation"; + Supersedes, "Supersedes", "supersedes"; + TlsReportDomain, "TLS-Report-Domain", "tls-report-domain"; + TlsReportSubmitter, "TLS-Report-Submitter", "tls-report-submitter"; + TlsRequired, "TLS-Required", "tls-required"; + VbrInfo, "VBR-Info", "vbr-info"; + X400ContentIdentifier, "X400-Content-Identifier", "x400-content-identifier"; + X400ContentReturn, "X400-Content-Return", "x400-content-return"; + X400ContentType, "X400-Content-Type", "x400-content-type"; + X400MtsIdentifier, "X400-MTS-Identifier", "x400-mts-identifier"; + X400Originator, "X400-Originator", "x400-originator"; + X400Received, "X400-Received", "x400-received"; + X400Recipients, "X400-Recipients", "x400-recipients"; + X400Trace, "X400-Trace", "x400-trace"; + ApparentlyTo, "Apparently-To", "apparently-to"; + Author, "Author", "author"; + CfblAddress, "CFBL-Address", "cfbl-address"; + CfblFeedbackId, "CFBL-Feedback-ID", "cfbl-feedback-id"; + DeliveredTo, "Delivered-To", "delivered-to"; + EdiintFeatures, "EDIINT-Features", "ediint-features"; + EesstVersion, "Eesst-Version", "eesst-version"; + ErrorsTo, "Errors-To", "errors-to"; + Face, "Face", "face"; + FormSub, "Form-Sub", "form-sub"; + JabberId, "Jabber-ID", "jabber-id"; + MmhsAuthorizingUsers, "MMHS-Authorizing-Users", "mmhs-authorizing-users"; + Privicon, "Privicon", "privicon"; + SioLabel, "SIO-Label", "sio-label"; + SioLabelHistory, "SIO-Label-History", "sio-label-history"; + WrongRecipient, "Wrong-Recipient", "wrong-recipient"; + XOriginalTo, "X-Original-To", "x-original-to"; + ReturnReceiptTo, "Return-Receipt-To", "return-receipt-to"; + XSpamStatus, "X-Spam-Status", "x-spam-status"; + XSpamScore, "X-Spam-Score", "x-spam-score"; + XSpamFlag, "X-Spam-Flag", "x-spam-flag"; + XSpamResult, "X-Spam-Result", "x-spam-result"; + XPriority, "X-Priority", "x-priority"; + XMSMailPriority, "X-MSMail-Priority", "x-msmail-priority"; + XMailer, "X-Mailer", "x-mailer"; + UserAgent, "User-Agent", "user-agent"; + XMimeOLE, "X-MimeOLE", "x-mimeole"; + XOriginatingIp, "X-Originating-IP", "x-originating-ip"; + XForwardedTo, "X-Forwarded-To", "x-forwarded-to"; + XForwardedFor, "X-Forwarded-For", "x-forwarded-for"; + XAutoResponseSuppress, "X-Auto-Response-Suppress", "x-auto-response-suppress"; + Precedence, "Precedence", "precedence"; + ThreadIndex, "Thread-Index", "thread-index"; + ThreadTopic, "Thread-Topic", "thread-topic"; + FeedbackId, "Feedback-ID", "feedback-id"; + XUniversallyUniqueIdentifier, "X-Universally-Unique-Identifier", "x-universally-unique-identifier"; + XVirusScanned, "X-Virus-Scanned", "x-virus-scanned"; + XMailFrom, "X-MailFrom", "x-mailfrom"; + XMailmanVersion, "X-Mailman-Version", "x-mailman-version"; + MessageIdHash, "Message-ID-Hash", "message-id-hash"; + XMessageIdHash, "X-Message-ID-Hash", "x-message-id-hash"; + XMailmanRuleMisses, "X-Mailman-Rule-Misses", "x-mailman-rule-misses"; + XSpamLevel, "X-Spam-Level", "x-spam-level"; + XReceived, "X-Received", "x-received"; + XGmMessageState, "X-Gm-Message-State", "x-gm-message-state"; + XGoogleDkimSignature, "X-Google-DKIM-Signature", "x-google-dkim-signature"; + XMailboxLine, "X-Mailbox-Line", "x-mailbox-line"; + XGmGg, "X-Gm-Gg", "x-gm-gg"; + XOriginalFrom, "X-Original-From", "x-original-from"; + XGoogleSmtpSource, "X-Google-Smtp-Source", "x-google-smtp-source"; + XMsTnefCorrelator, "X-MS-TNEF-Correlator", "x-ms-tnef-correlator"; + XMsHasAttach, "X-MS-Has-Attach", "x-ms-has-attach"; + XMeProxy, "X-ME-Proxy", "x-me-proxy"; + XMeProxyCause, "X-ME-Proxy-Cause", "x-me-proxy-cause"; + XMeSender, "X-ME-Sender", "x-me-sender"; + XGmFeatures, "X-Gm-Features", "x-gm-features"; + XMsExchangeTransportCrossTenantHeadersStamped, "X-MS-Exchange-Transport-CrossTenantHeadersStamped", "x-ms-exchange-transport-crosstenantheadersstamped"; + XMsPublicTrafficType, "X-MS-PublicTrafficType", "x-ms-publictraffictype"; + XOriginatorOrg, "X-OriginatorOrg", "x-originatororg"; + XMsExchangeCrossTenantNetworkMessageId, "X-MS-Exchange-CrossTenant-Network-Message-Id", "x-ms-exchange-crosstenant-network-message-id"; + XMsExchangeCrossTenantAuthSource, "X-MS-Exchange-CrossTenant-AuthSource", "x-ms-exchange-crosstenant-authsource"; + XMsExchangeCrossTenantAuthAs, "X-MS-Exchange-CrossTenant-AuthAs", "x-ms-exchange-crosstenant-authas"; + XMsExchangeCrossTenantOriginalArrivalTime, "X-MS-Exchange-CrossTenant-OriginalArrivalTime", "x-ms-exchange-crosstenant-originalarrivaltime"; + XMicrosoftAntispam, "X-Microsoft-Antispam", "x-microsoft-antispam"; + XMsExchangeCrossTenantId, "X-MS-Exchange-CrossTenant-Id", "x-ms-exchange-crosstenant-id"; + XMsTrafficTypeDiagnostic, "X-MS-TrafficTypeDiagnostic", "x-ms-traffictypediagnostic"; + XMicrosoftAntispamMessageInfo, "X-Microsoft-Antispam-Message-Info", "x-microsoft-antispam-message-info"; + XMsOffice365FilteringCorrelationId, "X-MS-Office365-Filtering-Correlation-Id", "x-ms-office365-filtering-correlation-id"; + XMsExchangeCrossTenantFromEntityHeader, "X-MS-Exchange-CrossTenant-FromEntityHeader", "x-ms-exchange-crosstenant-fromentityheader"; + XMsExchangeAntiSpamMessageDataChunkCount, "X-MS-Exchange-AntiSpam-MessageData-ChunkCount", "x-ms-exchange-antispam-messagedata-chunkcount"; + XMsExchangeAntiSpamMessageData0, "X-MS-Exchange-AntiSpam-MessageData-0", "x-ms-exchange-antispam-messagedata-0"; + XMsExchangeSenderADCheck, "X-MS-Exchange-SenderADCheck", "x-ms-exchange-senderadcheck"; + XForefrontAntispamReport, "X-Forefront-Antispam-Report", "x-forefront-antispam-report"; + XMsExchangeAntiSpamRelay, "X-MS-Exchange-AntiSpam-Relay", "x-ms-exchange-antispam-relay"; + XMsExchangeCrossTenantMailboxType, "X-MS-Exchange-CrossTenant-MailboxType", "x-ms-exchange-crosstenant-mailboxtype"; + XMsExchangeCrossTenantUserPrincipalName, "X-MS-Exchange-CrossTenant-UserPrincipalName", "x-ms-exchange-crosstenant-userprincipalname"; + XGitHubReason, "X-GitHub-Reason", "x-github-reason"; + XGitHubRecipientAddress, "X-GitHub-Recipient-Address", "x-github-recipient-address"; + XGitHubRecipient, "X-GitHub-Recipient", "x-github-recipient"; + Destinations, "Destinations", "destinations"; + XGitHubSender, "X-GitHub-Sender", "x-github-sender"; + XGitHubNotifyPlatform, "X-GitHub-Notify-Platform", "x-github-notify-platform"; + XThreadId, "X-ThreadId", "x-threadid"; + XSesOutgoing, "X-SES-Outgoing", "x-ses-outgoing"; + XProofpointVirusVersion, "X-Proofpoint-Virus-Version", "x-proofpoint-virus-version"; + XGitHubAssignees, "X-GitHub-Assignees", "x-github-assignees"; + XGitHubLabels, "X-GitHub-Labels", "x-github-labels"; + BimiSelector, "BIMI-Selector", "bimi-selector"; + XStripeEid, "X-Stripe-EID", "x-stripe-eid"; + XAttachmentId, "X-Attachment-Id", "x-attachment-id"; + XTestIDTracker, "X-Test-IDTracker", "x-test-idtracker"; + XIetfIDTracker, "X-IETF-IDTracker", "x-ietf-idtracker"; + XPmMessageId, "X-Pm-Message-ID", "x-pm-message-id"; + XAntiAbuse, "X-AntiAbuse", "x-antiabuse"; + Autocrypt, "Autocrypt", "autocrypt"; + XComplaintsTo, "X-Complaints-To", "x-complaints-to"; + XProofpointOrigGuid, "X-Proofpoint-ORIG-GUID", "x-proofpoint-orig-guid"; + XProofpointGuid, "X-Proofpoint-GUID", "x-proofpoint-guid"; + XGitHubIssueState, "X-GitHub-IssueState", "x-github-issuestate"; + XMsReactions, "X-MS-Reactions", "x-ms-reactions"; + XPmMtaPool, "X-Pm-MTA-Pool", "x-pm-mta-pool"; + XPmRcpt, "X-Pm-RCPT", "x-pm-rcpt"; + XProofpointSpamDetailsEnc, "X-Proofpoint-Spam-Details-Enc", "x-proofpoint-spam-details-enc"; + XPmMessageOptions, "X-Pm-Message-Options", "x-pm-message-options"; + XSenderId, "X-Sender-ID", "x-sender-id"; + XGitHubPullRequestStatus, "X-GitHub-PullRequestStatus", "x-github-pullrequeststatus"; + XAuthorityAnalysis, "X-Authority-Analysis", "x-authority-analysis"; + XForwardedEncrypted, "X-Forwarded-Encrypted", "x-forwarded-encrypted"; + XMsExchangeAntiSpamExternalHopMessageDataChunkCount, "X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount", "x-ms-exchange-antispam-externalhop-messagedata-chunkcount"; + XMsExchangeAntiSpamExternalHopMessageData0, "X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0", "x-ms-exchange-antispam-externalhop-messagedata-0"; + XMsExchangeCrossTenantRmsPersistedConsumerOrg, "X-MS-Exchange-CrossTenant-RMS-PersistedConsumerOrg", "x-ms-exchange-crosstenant-rms-persistedconsumerorg"; + XExchangeRoutingPolicyChecked, "X-Exchange-RoutingPolicyChecked", "x-exchange-routingpolicychecked"; + XMsExchangeCrossTenantOriginalAttributedTenantConnectingIp, "X-MS-Exchange-CrossTenant-OriginalAttributedTenantConnectingIp", "x-ms-exchange-crosstenant-originalattributedtenantconnectingip"; + XMsExchangeMessageSentRepresentingType, "X-MS-Exchange-MessageSentRepresentingType", "x-ms-exchange-messagesentrepresentingtype"; + XMsExchangeTransportCrossTenantHeadersStripped, "X-MS-Exchange-Transport-CrossTenantHeadersStripped", "x-ms-exchange-transport-crosstenantheadersstripped"; + XMsOffice365FilteringCorrelationIdPrvs, "X-MS-Office365-Filtering-Correlation-Id-Prvs", "x-ms-office365-filtering-correlation-id-prvs"; + XMicrosoftAntispamMessageInfoOriginal, "X-Microsoft-Antispam-Message-Info-Original", "x-microsoft-antispam-message-info-original"; + XMsExchangeAuthenticationResults, "X-MS-Exchange-Authentication-Results", "x-ms-exchange-authentication-results"; + XForefrontAntispamReportUntrusted, "X-Forefront-Antispam-Report-Untrusted", "x-forefront-antispam-report-untrusted"; + XMsExchangeAtpMessageProperties, "X-MS-Exchange-AtpMessageProperties", "x-ms-exchange-atpmessageproperties"; + XMicrosoftAntispamUntrusted, "X-Microsoft-Antispam-Untrusted", "x-microsoft-antispam-untrusted"; + XMsExchangeAntiSpamMessageData1, "X-MS-Exchange-AntiSpam-MessageData-1", "x-ms-exchange-antispam-messagedata-1"; + XMissiveId, "X-Missive-Id", "x-missive-id"; + XIadbIpReverse, "X-IADB-IP-Reverse", "x-iadb-ip-reverse"; + XReportAbuse, "X-Report-Abuse", "x-report-abuse"; + DkimFilter, "DKIM-Filter", "dkim-filter"; + XMeReceived, "X-ME-Received", "x-me-received"; + XProofpointSpamDetails, "X-Proofpoint-Spam-Details", "x-proofpoint-spam-details"; +} + +const fn longest(names: &[&str]) -> usize { + let mut index = 0; + let mut max = 0; + while index < names.len() { + if names[index].len() > max { + max = names[index].len(); + } + index += 1; + } + max +} + +pub(crate) const MAX_NAME_LEN: usize = longest(&LOWERCASE); + +pub(crate) fn known(id: u16) -> Option<&'static HeaderName<'static>> { + VARIANTS.get(id as usize) +} + +pub(crate) fn canonical(id: u16) -> &'static str { + CANONICAL.get(id as usize).copied().unwrap_or_default() +} + +pub(crate) fn lookup(name: &[u8]) -> Option<u16> { + let mut buf = [0u8; MAX_NAME_LEN]; + let lowercase = buf.get_mut(..name.len())?; + lowercase + .iter_mut() + .zip(name) + .for_each(|(out, byte)| *out = byte.to_ascii_lowercase()); + lookup_lowercase(lowercase) +} + +pub(crate) fn trim_blank_end(name: &[u8]) -> &[u8] { + let len = name + .iter() + .rposition(|&byte| !matches!(byte, b' ' | b'\t')) + .map_or(0, |last| last + 1); + name.get(..len).unwrap_or_default() +} + +#[inline(never)] +fn other_id(name: &str) -> u16 { + lookup(name.as_bytes()).unwrap_or(OTHER_ID) +} + +fn is_ftext(byte: u8) -> bool { + matches!(byte, b'!'..=b'9' | b';'..=b'~') +} + +impl<'x> HeaderName<'x> { + /// Parses a header name. Returns `None` for an empty name or one with a + /// byte that RFC 5322 does not allow in a field name (anything but + /// printable US-ASCII other than the colon). Never allocates. + pub fn parse(name: impl Into<Cow<'x, str>>) -> Option<HeaderName<'x>> { + let name = name.into(); + (!name.is_empty() && name.bytes().all(is_ftext)).then(|| HeaderName::resolve(name)) + } + + fn resolve(name: Cow<'x, str>) -> HeaderName<'x> { + match lookup(name.as_bytes()).and_then(known) { + Some(known) => known.clone(), + None => HeaderName::Other(name), + } + } + + /// Resolves the name once, for code that looks the same name up in many + /// parts or messages: [`crate::Headers::all_key`] and + /// [`crate::Headers::get_key`] then skip the name lookup that + /// [`crate::Headers::all`] and [`crate::Headers::get`] do on every call. + /// + /// ``` + /// use mail_parser::{HeaderName, MessageParser}; + /// + /// let message = MessageParser::new() + /// .parse(b"X-Tag: a\r\nX-Tag: b\r\n\r\nbody") + /// .expect("message"); + /// let name = HeaderName::from("x-tag"); + /// let key = name.key(); + /// assert_eq!(message.headers().all_key(key).count(), 2); + /// assert_eq!( + /// message.headers().get_key(key).map(|header| header.raw_value()), + /// Some(&b" b\r\n"[..]) + /// ); + /// ``` + #[inline] + pub fn key(&self) -> HeaderKey<'_> { + HeaderKey { + id: self.resolved_id(), + name: self.as_str(), + } + } + + #[inline] + pub(crate) fn resolved_id(&self) -> u16 { + match self { + HeaderName::Other(name) => other_id(name), + known => known.id(), + } + } + + /// Converts the name into one that owns its spelling. + pub fn into_owned(self) -> HeaderName<'static> { + match self { + HeaderName::Other(name) => HeaderName::Other(name.into_owned().into()), + known => known + .known_static() + .cloned() + .unwrap_or(HeaderName::Other(Cow::Borrowed(""))), + } + } + + fn known_static(&self) -> Option<&'static HeaderName<'static>> { + match self { + HeaderName::Other(_) => None, + known => VARIANTS.get(known.id() as usize), + } + } + + /// Canonical spelling of a known name; empty for other names. + pub fn as_static_str(&self) -> &'static str { + match self { + HeaderName::Other(_) => "", + known => CANONICAL + .get(known.id() as usize) + .copied() + .unwrap_or_default(), + } + } + + /// Canonical spelling of a known name, or the original spelling of any + /// other name. + pub fn as_str(&self) -> &str { + match self { + HeaderName::Other(name) => name.as_ref(), + known => known.as_static_str(), + } + } + + /// Whether this is not one of the known names. + pub fn is_other(&self) -> bool { + matches!(self, HeaderName::Other(_)) + } + + /// Whether this is one of the seven `Content-*` MIME header fields. + pub fn is_mime_header(&self) -> bool { + matches!( + self, + HeaderName::ContentDescription + | HeaderName::ContentId + | HeaderName::ContentLanguage + | HeaderName::ContentLocation + | HeaderName::ContentTransferEncoding + | HeaderName::ContentType + | HeaderName::ContentDisposition + ) + } + + /// Whether the default parser yields a structured value for this name. + pub fn is_structured(&self) -> bool { + matches!( + self, + HeaderName::Subject + | HeaderName::Comments + | HeaderName::ContentDescription + | HeaderName::ContentLocation + | HeaderName::ContentTransferEncoding + | HeaderName::From + | HeaderName::To + | HeaderName::Cc + | HeaderName::Bcc + | HeaderName::ReplyTo + | HeaderName::Sender + | HeaderName::ResentTo + | HeaderName::ResentFrom + | HeaderName::ResentBcc + | HeaderName::ResentCc + | HeaderName::ResentSender + | HeaderName::ListArchive + | HeaderName::ListHelp + | HeaderName::ListId + | HeaderName::ListOwner + | HeaderName::ListPost + | HeaderName::ListSubscribe + | HeaderName::ListUnsubscribe + | HeaderName::Date + | HeaderName::ResentDate + | HeaderName::MessageId + | HeaderName::References + | HeaderName::InReplyTo + | HeaderName::ReturnPath + | HeaderName::ContentId + | HeaderName::ResentMessageId + | HeaderName::Keywords + | HeaderName::ContentLanguage + | HeaderName::Received + | HeaderName::ContentType + | HeaderName::ContentDisposition + ) + } +} + +impl PartialEq for HeaderName<'_> { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (HeaderName::Other(a), HeaderName::Other(b)) => a.eq_ignore_ascii_case(b), + (HeaderName::Other(name), known) | (known, HeaderName::Other(name)) => { + name.eq_ignore_ascii_case(known.as_static_str()) + } + _ => self.id() == other.id(), + } + } +} + +impl Eq for HeaderName<'_> {} + +impl Hash for HeaderName<'_> { + fn hash<H: Hasher>(&self, state: &mut H) { + match (self, self.resolved_id()) { + (HeaderName::Other(name), OTHER_ID) => name + .bytes() + .for_each(|byte| byte.to_ascii_lowercase().hash(state)), + (_, id) => id.hash(state), + } + } +} + +impl PartialOrd for HeaderName<'_> { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for HeaderName<'_> { + fn cmp(&self, other: &Self) -> Ordering { + match (self.resolved_id(), other.resolved_id()) { + (OTHER_ID, OTHER_ID) => self + .as_str() + .bytes() + .map(|byte| byte.to_ascii_lowercase()) + .cmp(other.as_str().bytes().map(|byte| byte.to_ascii_lowercase())), + (a, b) => a.cmp(&b), + } + } +} + +impl fmt::Display for HeaderName<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl<'x> From<&'x str> for HeaderName<'x> { + fn from(value: &'x str) -> Self { + HeaderName::resolve(Cow::Borrowed(value)) + } +} + +impl<'x> From<Cow<'x, str>> for HeaderName<'x> { + fn from(value: Cow<'x, str>) -> Self { + HeaderName::resolve(value) + } +} + +impl From<String> for HeaderName<'_> { + fn from(value: String) -> Self { + HeaderName::resolve(Cow::Owned(value)) + } +} + +impl<'x> From<&HeaderName<'x>> for HeaderName<'x> { + fn from(value: &HeaderName<'x>) -> Self { + value.clone() + } +} + +impl<'x> From<HeaderName<'x>> for Cow<'x, str> { + fn from(name: HeaderName<'x>) -> Self { + match name { + HeaderName::Other(name) => name, + known => Cow::Borrowed(known.as_static_str()), + } + } +} + +impl From<HeaderName<'_>> for String { + fn from(name: HeaderName<'_>) -> Self { + name.as_str().to_string() + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for HeaderName<'_> { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.serialize_str(self.as_str()) + } +} + +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for HeaderName<'static> { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + String::deserialize(deserializer).map(HeaderName::from) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BASELINE_NAMES: [&str; 140] = [ + "Subject", + "From", + "To", + "Cc", + "Date", + "Bcc", + "Reply-To", + "Sender", + "Comments", + "In-Reply-To", + "Keywords", + "Received", + "Message-ID", + "References", + "Return-Path", + "MIME-Version", + "Content-Description", + "Content-ID", + "Content-Language", + "Content-Location", + "Content-Transfer-Encoding", + "Content-Type", + "Content-Disposition", + "Resent-To", + "Resent-From", + "Resent-Bcc", + "Resent-Cc", + "Resent-Sender", + "Resent-Date", + "Resent-Message-ID", + "List-Archive", + "List-Help", + "List-ID", + "List-Owner", + "List-Post", + "List-Subscribe", + "List-Unsubscribe", + "DKIM-Signature", + "ARC-Authentication-Results", + "ARC-Message-Signature", + "ARC-Seal", + "DKIM2-Signature", + "Message-Instance", + "Accept-Language", + "Alternate-Recipient", + "Archived-At", + "Authentication-Results", + "Auto-Submitted", + "Autoforwarded", + "Autosubmitted", + "Content-Alternative", + "Content-Duration", + "Content-features", + "Content-MD5", + "Content-Translation-Type", + "Conversion", + "Conversion-With-Loss", + "DL-Expansion-History", + "Deferred-Delivery", + "Delivery-Date", + "Discarded-X400-IPMS-Extensions", + "Discarded-X400-MTS-Extensions", + "Disclose-Recipients", + "Disposition-Notification-Options", + "Disposition-Notification-To", + "Downgraded-Final-Recipient", + "Downgraded-In-Reply-To", + "Downgraded-Message-Id", + "Downgraded-Original-Recipient", + "Downgraded-References", + "Encoding", + "Expires", + "Generate-Delivery-Report", + "HP-Outer", + "Importance", + "Incomplete-Copy", + "Language", + "Latest-Delivery-Time", + "List-Unsubscribe-Post", + "Message-Context", + "Message-Type", + "MMHS-Exempted-Address", + "MMHS-Extended-Authorisation-Info", + "MMHS-Subject-Indicator-Codes", + "MMHS-Handling-Instructions", + "MMHS-Message-Instructions", + "MMHS-Codress-Message-Indicator", + "MMHS-Originator-Reference", + "MMHS-Primary-Precedence", + "MMHS-Copy-Precedence", + "MMHS-Message-Type", + "MMHS-Other-Recipients-Indicator-To", + "MMHS-Other-Recipients-Indicator-CC", + "MMHS-Acp127-Message-Identifier", + "MMHS-Originator-PLAD", + "MT-Priority", + "Organization", + "Original-Encoded-Information-Types", + "Original-From", + "Original-Message-ID", + "Original-Recipient", + "Originator-Return-Address", + "Original-Subject", + "PICS-Label", + "Prevent-NonDelivery-Report", + "Priority", + "Received-SPF", + "Reply-By", + "Require-Recipient-Valid-Since", + "Sensitivity", + "Solicitation", + "Supersedes", + "TLS-Report-Domain", + "TLS-Report-Submitter", + "TLS-Required", + "VBR-Info", + "X400-Content-Identifier", + "X400-Content-Return", + "X400-Content-Type", + "X400-MTS-Identifier", + "X400-Originator", + "X400-Received", + "X400-Recipients", + "X400-Trace", + "Apparently-To", + "Author", + "CFBL-Address", + "CFBL-Feedback-ID", + "Delivered-To", + "EDIINT-Features", + "Eesst-Version", + "Errors-To", + "Face", + "Form-Sub", + "Jabber-ID", + "MMHS-Authorizing-Users", + "Privicon", + "SIO-Label", + "SIO-Label-History", + "Wrong-Recipient", + ]; + + #[test] + fn baseline_names_round_trip() { + for name in BASELINE_NAMES { + let parsed = HeaderName::parse(name).expect("valid name"); + assert!(!parsed.is_other(), "{name} is not known"); + assert_eq!(parsed.as_str(), name); + assert_eq!(HeaderName::parse(parsed.as_str()), Some(parsed.clone())); + assert_eq!( + HeaderName::parse(name.to_ascii_uppercase()), + Some(parsed.clone()) + ); + } + } + + #[test] + fn vendor_names_follow_the_baseline_names() { + assert_eq!(FIRST_VENDOR as usize, BASELINE_NAMES.len()); + for (id, name) in BASELINE_NAMES.iter().enumerate() { + assert_eq!(canonical(id as u16), *name); + } + } + + #[test] + fn every_known_name_round_trips() { + for (canonical, lowercase) in CANONICAL.iter().zip(LOWERCASE.iter()) { + assert_eq!(&canonical.to_ascii_lowercase(), lowercase); + let parsed = HeaderName::parse(*canonical).expect("valid"); + assert_eq!(parsed.as_str(), *canonical); + assert_eq!(lookup(lowercase.as_bytes()), Some(parsed.id())); + } + assert_eq!(KNOWN_NAMES, 252); + assert_eq!(MAX_NAME_LEN, 62); + } + + #[test] + fn other_names() { + let custom = HeaderName::parse("X-Custom-Field").expect("valid"); + assert_eq!(custom, HeaderName::Other("x-custom-field".into())); + assert_eq!(custom.as_str(), "X-Custom-Field"); + assert!(HeaderName::parse("").is_none()); + assert!(HeaderName::parse("mal formed").is_none()); + assert_eq!(HeaderName::parse("X-Mailer"), Some(HeaderName::XMailer)); + assert_eq!( + HeaderName::parse("x-face").map(|n| n.is_other()), + Some(true) + ); + assert_eq!( + HeaderName::parse("Original-Encoded-Information-Types-Extra").map(|n| n.is_other()), + Some(true) + ); + assert_eq!(lookup(b"SUBJECT"), Some(HeaderName::Subject.id())); + for name in [ + &b" subject"[..], + b"Sub ject", + b"MIME-version ", + b"From\r", + b"F\x0crom", + b":From", + b"", + ] { + assert_eq!(lookup(name), None, "{name:?}"); + } + } + + #[test] + fn every_field_name_character_is_accepted() { + for name in ["X.Spam", "A@[]{}~", "X!#$%&'*+/=?^`|", "X;Y"] { + let parsed = HeaderName::parse(name).expect("valid field name"); + assert_eq!(parsed, HeaderName::Other(name.into())); + assert_eq!(parsed.as_str(), name); + } + for name in ["", "X:Y", "X Y", "caf\u{e9}", "X\u{7f}", "X\tY"] { + assert_eq!(HeaderName::parse(name), None, "{name:?}"); + } + for name in ["X.Spam", "mal formed", ":From", "caf\u{e9}", ""] { + assert_eq!(HeaderName::from(name).as_str(), name); + assert_eq!(HeaderName::from(name.to_string()).as_str(), name); + assert_eq!(HeaderName::from(Cow::Borrowed(name)).as_str(), name); + } + assert_eq!(HeaderName::from("x-mailer"), HeaderName::XMailer); + assert!(HeaderName::from("Sub ject").is_other()); + } + + #[test] + fn other_spelling_a_known_name_is_that_name() { + use std::collections::{BTreeSet, HashSet}; + + let pairs = [ + (HeaderName::Other("Subject".into()), HeaderName::Subject), + (HeaderName::Other("x-MAILER".into()), HeaderName::XMailer), + ( + HeaderName::Other("content-type".into()), + HeaderName::ContentType, + ), + ]; + for (other, known) in &pairs { + assert_eq!(other, known); + assert_eq!(known, other); + assert_eq!(other.cmp(known), Ordering::Equal); + assert_eq!(other.resolved_id(), known.id()); + let hashed: HashSet<HeaderName<'_>> = [other.clone()].into_iter().collect(); + assert!(hashed.contains(known)); + let ordered: BTreeSet<HeaderName<'_>> = [known.clone()].into_iter().collect(); + assert!(ordered.contains(other)); + } + let custom = HeaderName::Other("X-Custom".into()); + assert_ne!(custom, HeaderName::Subject); + assert_ne!(HeaderName::Other("Sub ject".into()), HeaderName::Subject); + assert_eq!(custom.cmp(&HeaderName::Subject), Ordering::Greater); + assert_eq!(custom.resolved_id(), OTHER_ID); + let mut names = [ + HeaderName::Other("x-b".into()), + HeaderName::Other("From".into()), + HeaderName::Subject, + HeaderName::Other("X-A".into()), + ]; + names.sort(); + assert_eq!( + names.iter().map(HeaderName::as_str).collect::<Vec<_>>(), + ["Subject", "From", "X-A", "x-b"] + ); + } +} + +/// A header name resolved once by [`HeaderName::key`], for repeated lookups +/// with [`crate::Headers::all_key`] and [`crate::Headers::get_key`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct HeaderKey<'x> { + id: u16, + name: &'x str, +} + +impl<'x> HeaderKey<'x> { + /// The spelling of the name the key was made from. + pub fn as_str(&self) -> &'x str { + self.name + } + + pub(crate) fn id(&self) -> u16 { + self.id + } +} diff --git a/src/lib.rs b/src/lib.rs index 420389c..3858b77 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,89 +3,108 @@ * * SPDX-License-Identifier: Apache-2.0 OR MIT */ -#![doc = include_str!("../README.md")] -#![deny(rust_2018_idioms)] -#[forbid(unsafe_code)] -pub mod core; + +//! Fast and robust e-mail parsing. +//! +//! A [`MessageParser`] turns the bytes of an RFC 5322 message into a +//! read-only [`Message`]: the raw bytes plus a flat, index-based store of +//! every nested message, MIME part and header field. Everything is read +//! through small `Copy` views ([`MessageRef`], [`MessagePart`], [`Header`], +//! [`HeaderValue`], ...), and bodies are decoded on access. +//! +//! ``` +//! use mail_parser::MessageParser; +//! +//! let raw = b"From: Ann <ann@example.com>\r\nSubject: Hi\r\n\r\nHello!\r\n"; +//! let message = MessageParser::new().parse(raw).expect("message"); +//! assert_eq!(message.subject(), Some("Hi")); +//! assert_eq!(message.body_text(0).as_deref(), Some("Hello!\r\n")); +//! ``` +//! +//! - Parsing: [`MessageParser::parse`], [`MessageParser::parse_owned`], +//! [`MessageParser::parse_headers`], and [`MessageParser::parse_with`] +//! with [`MessageBuffers`] to reuse storage from one message to the next. +//! - Structure: [`Message::parts`] and [`Message::messages`] in document +//! order, [`MessagePart::children`], [`MessagePart::nested`], the RFC 8621 +//! body lists ([`MessageRef::text_body`], [`MessageRef::html_body`], +//! [`MessageRef::attachments`]) and MIME boundaries +//! ([`MessagePart::boundary`], [`Message::part_by_boundary`]). +//! - Bodies: [`MessagePart::decoded`], [`MessagePart::text`], +//! [`MessagePart::text_prefix`] and [`MessagePart::decoded_len`]; +//! [`MessagePart::decoded_checked`] and [`MessagePart::text_checked`] +//! also report decoding problems. +//! - Header fields: [`Headers`] with typed getters, [`Header::raw_name`] +//! and [`Header::raw_value`] as written, [`Header::parse_as`] to parse a +//! field in another form, and [`HeaderForm::parse`] for values on their +//! own. +//! - Mailboxes: [`mailbox::mbox`] and [`mailbox::maildir`]. +//! - Utilities: [`DateTime`], [`thread_name`], [`html_to_text`], +//! [`text_to_html`], [`preview_text`], [`Charset`] and the other +//! [`decoders`]. +//! +//! Parsing never fails on malformed input: damaged structure is reported +//! by [`MessagePart::flags`], malformed encodings by the checked decoding +//! methods. The `full_encoding` feature adds the multi-byte charsets +//! (through `encoding_rs`), and the `serde` feature serializes messages. + +#![warn(missing_docs)] + +mod datetime; pub mod decoders; +mod fields; +mod header_name; pub mod mailbox; -pub mod parsers; +mod parser; +#[doc(hidden)] +pub mod scan; +mod store; +mod view; -use parsers::MessageStream; -use std::{borrow::Cow, collections::HashMap, hash::Hash, net::IpAddr}; +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +pub struct ReadmeDoctests; -/// RFC5322/RFC822 message parser. -#[derive(Debug, PartialEq, Eq, Clone)] -#[allow(unpredictable_function_pointer_comparisons)] -pub struct MessageParser { - pub(crate) header_map: HashMap<HeaderName<'static>, HdrParseFnc>, - pub(crate) def_hdr_parse_fnc: HdrParseFnc, -} +pub use datetime::{DOW, DateTime, MONTH}; +pub use decoders::{ + charsets::Charset, + html::{add_html_token, html_to_text, strip_charset_meta, text_to_html}, + preview::{preview_html, preview_text, truncate_html, truncate_text}, +}; +pub use fields::{ + HeaderForm, ParsedValue, + address::{ + parse_address_detail_part, parse_address_domain, parse_address_local_part, + parse_address_user_part, + }, + thread::thread_name, +}; +pub use header_name::{HeaderKey, HeaderName}; +pub use parser::MessageParser; +pub use store::{MessageBuffers, MessageId, PartId}; +pub use view::{ + Address, AddressList, AddressRun, ContentType, DecodeProblems, Greeting, Group, Header, + HeaderIter, HeaderValue, Headers, Host, Mailbox, Message, MessagePart, MessageRef, + NamedHeaders, PartFlags, PartKind, PartRole, Protocol, Received, Source, TextList, TlsVersion, +}; -pub(crate) type HdrParseFnc = for<'x> fn(&mut MessageStream<'x>) -> crate::HeaderValue<'x>; - -/// An RFC5322/RFC822 message. -#[derive(Debug, Default, PartialEq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct Message<'x> { - #[cfg_attr(feature = "serde", serde(default))] - pub html_body: Vec<MessagePartId>, - #[cfg_attr(feature = "serde", serde(default))] - pub text_body: Vec<MessagePartId>, - #[cfg_attr(feature = "serde", serde(default))] - pub attachments: Vec<MessagePartId>, - - #[cfg_attr(feature = "serde", serde(default))] - pub parts: Vec<MessagePart<'x>>, - - #[cfg_attr(feature = "serde", serde(skip))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Skip))] - pub raw_message: Cow<'x, [u8]>, -} - -/// MIME Message Part -#[derive(Debug, PartialEq, Default, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct MessagePart<'x> { - #[cfg_attr(feature = "serde", serde(default))] - pub headers: Vec<Header<'x>>, - pub is_encoding_problem: bool, - #[cfg_attr(feature = "serde", serde(default))] - //#[cfg_attr(feature = "rkyv", rkyv(omit_bounds))] - pub body: PartType<'x>, - #[cfg_attr(feature = "serde", serde(skip))] - pub encoding: Encoding, - pub offset_header: u32, - pub offset_body: u32, - pub offset_end: u32, -} - -/// MIME Part encoding type -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] +/// Declared Content-Transfer-Encoding of a part. The numeric values (0, 1, +/// 2) are stable. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[repr(u8)] pub enum Encoding { + /// No transfer encoding: `7bit`, `8bit`, `binary`, no field, or a value + /// the parser does not know. #[default] None = 0, + /// `quoted-printable`. QuotedPrintable = 1, + /// `base64`. Base64 = 2, } impl From<u8> for Encoding { - fn from(v: u8) -> Self { - match v { + fn from(value: u8) -> Self { + match value { 1 => Encoding::QuotedPrintable, 2 => Encoding::Base64, _ => Encoding::None, @@ -93,618 +112,8 @@ impl From<u8> for Encoding { } } -/// Unique ID representing a MIME part within a message. -pub type MessagePartId = u32; - -/// A text, binary or nested e-mail MIME message part. -/// -/// - Text: Any text/* part -/// - Binary: Any other part type that is not text. -/// - Message: Nested RFC5322 message. -/// - MultiPart: Multipart part. -/// -#[derive(Debug, PartialEq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -#[cfg_attr( - feature = "rkyv", - rkyv(serialize_bounds( - __S: rkyv::ser::Writer + rkyv::ser::Allocator, - __S::Error: rkyv::rancor::Source, - )) -)] -#[cfg_attr( - feature = "rkyv", - rkyv(deserialize_bounds(__D::Error: rkyv::rancor::Source)) -)] -#[cfg_attr( - feature = "rkyv", - rkyv(bytecheck( - bounds( - __C: rkyv::validation::ArchiveContext, - ) - )) -)] -pub enum PartType<'x> { - /// Any text/* part - Text(#[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] Cow<'x, str>), - - /// A text/html part - Html(#[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] Cow<'x, str>), - - /// Any other part type that is not text. - Binary(#[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] Cow<'x, [u8]>), - - /// Any inline binary data that. - InlineBinary(#[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] Cow<'x, [u8]>), - - /// Nested RFC5322 message. - Message(#[cfg_attr(feature = "rkyv", rkyv(omit_bounds))] Message<'x>), - - /// Multipart part - Multipart(Vec<MessagePartId>), -} - -impl Default for PartType<'_> { - fn default() -> Self { - PartType::Multipart(Vec::with_capacity(0)) +impl From<Encoding> for u8 { + fn from(value: Encoding) -> Self { + value as u8 } } - -/// An RFC5322 or RFC2369 internet address. -#[derive(Debug, PartialEq, Eq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct Addr<'x> { - /// The address name including comments - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub name: Option<Cow<'x, str>>, - - /// An e-mail address (RFC5322/RFC2369) or URL (RFC2369) - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub address: Option<Cow<'x, str>>, -} - -/// An RFC5322 address group. -#[derive(Debug, PartialEq, Eq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct Group<'x> { - /// Group name - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub name: Option<Cow<'x, str>>, - - /// Addresses member of the group - #[cfg_attr(feature = "serde", serde(default))] - pub addresses: Vec<Addr<'x>>, -} - -/// A message header. -#[derive(Debug, PartialEq, Eq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -#[cfg_attr(feature = "rkyv", rkyv(compare(PartialEq)))] -pub struct Header<'x> { - pub name: HeaderName<'x>, - pub value: HeaderValue<'x>, - pub offset_field: u32, - pub offset_start: u32, - pub offset_end: u32, -} - -macro_rules! header_names { - ($($variant:ident = $tag:literal, id = $id:literal, $name:literal, $lc:literal;)+) => { - /// A header field - #[derive(Debug, Clone, PartialOrd, Ord)] - #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] - #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] - #[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) - )] - #[cfg_attr(feature = "rkyv", rkyv(compare(PartialEq)))] - #[non_exhaustive] - #[repr(u8)] - pub enum HeaderName<'x> { - Other(#[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] Cow<'x, str>) = 37, - $($variant = $tag,)+ - } - - impl HeaderName<'_> { - pub fn as_static_str(&self) -> &'static str { - match self { - $(HeaderName::$variant => $name,)+ - HeaderName::Other(_) => "", - } - } - - pub fn id(&self) -> u8 { - match self { - $(HeaderName::$variant => $id,)+ - HeaderName::Other(_) => 37, - } - } - - pub fn to_owned(&self) -> HeaderName<'static> { - match self { - $(HeaderName::$variant => HeaderName::$variant,)+ - HeaderName::Other(name) => HeaderName::Other(name.to_string().into()), - } - } - - pub fn into_owned(self) -> HeaderName<'static> { - match self { - $(HeaderName::$variant => HeaderName::$variant,)+ - HeaderName::Other(name) => HeaderName::Other(name.into_owned().into()), - } - } - } - - pub(crate) fn header_map(name: &[u8]) -> Option<HeaderName<'static>> { - hashify::fnc_map!(name, - $($lc => Some(HeaderName::$variant),)+ - _ => None - ) - } - - #[cfg(feature = "rkyv")] - impl ArchivedHeaderName<'_> { - pub fn as_static_str(&self) -> &'static str { - match self { - $(ArchivedHeaderName::$variant => $name,)+ - ArchivedHeaderName::Other(_) => "", - } - } - - pub fn id(&self) -> u8 { - match self { - $(ArchivedHeaderName::$variant => $id,)+ - ArchivedHeaderName::Other(_) => 37, - } - } - } - - #[cfg(feature = "rkyv")] - impl From<&ArchivedHeaderName<'_>> for HeaderName<'static> { - fn from(value: &ArchivedHeaderName<'_>) -> Self { - match value { - $(ArchivedHeaderName::$variant => HeaderName::$variant,)+ - ArchivedHeaderName::Other(name) => HeaderName::Other(name.to_string().into()), - } - } - } - }; -} - -header_names! { - Subject = 0, id = 0, "Subject", "subject"; - From = 1, id = 1, "From", "from"; - To = 2, id = 2, "To", "to"; - Cc = 3, id = 3, "Cc", "cc"; - Date = 4, id = 4, "Date", "date"; - Bcc = 5, id = 5, "Bcc", "bcc"; - ReplyTo = 6, id = 6, "Reply-To", "reply-to"; - Sender = 7, id = 7, "Sender", "sender"; - Comments = 8, id = 8, "Comments", "comments"; - InReplyTo = 9, id = 9, "In-Reply-To", "in-reply-to"; - Keywords = 10, id = 10, "Keywords", "keywords"; - Received = 11, id = 11, "Received", "received"; - MessageId = 12, id = 12, "Message-ID", "message-id"; - References = 13, id = 13, "References", "references"; - ReturnPath = 14, id = 14, "Return-Path", "return-path"; - MimeVersion = 15, id = 15, "MIME-Version", "mime-version"; - ContentDescription = 16, id = 16, "Content-Description", "content-description"; - ContentId = 17, id = 17, "Content-ID", "content-id"; - ContentLanguage = 18, id = 18, "Content-Language", "content-language"; - ContentLocation = 19, id = 19, "Content-Location", "content-location"; - ContentTransferEncoding = 20, id = 20, "Content-Transfer-Encoding", "content-transfer-encoding"; - ContentType = 21, id = 21, "Content-Type", "content-type"; - ContentDisposition = 22, id = 22, "Content-Disposition", "content-disposition"; - ResentTo = 23, id = 23, "Resent-To", "resent-to"; - ResentFrom = 24, id = 24, "Resent-From", "resent-from"; - ResentBcc = 25, id = 25, "Resent-Bcc", "resent-bcc"; - ResentCc = 26, id = 26, "Resent-Cc", "resent-cc"; - ResentSender = 27, id = 27, "Resent-Sender", "resent-sender"; - ResentDate = 28, id = 28, "Resent-Date", "resent-date"; - ResentMessageId = 29, id = 29, "Resent-Message-ID", "resent-message-id"; - ListArchive = 30, id = 30, "List-Archive", "list-archive"; - ListHelp = 31, id = 31, "List-Help", "list-help"; - ListId = 32, id = 32, "List-ID", "list-id"; - ListOwner = 33, id = 33, "List-Owner", "list-owner"; - ListPost = 34, id = 34, "List-Post", "list-post"; - ListSubscribe = 35, id = 35, "List-Subscribe", "list-subscribe"; - ListUnsubscribe = 36, id = 36, "List-Unsubscribe", "list-unsubscribe"; - DkimSignature = 38, id = 41, "DKIM-Signature", "dkim-signature"; - ArcAuthenticationResults = 39, id = 38, "ARC-Authentication-Results", "arc-authentication-results"; - ArcMessageSignature = 40, id = 39, "ARC-Message-Signature", "arc-message-signature"; - ArcSeal = 41, id = 40, "ARC-Seal", "arc-seal"; - Dkim2Signature = 42, id = 42, "DKIM2-Signature", "dkim2-signature"; - MessageInstance = 43, id = 43, "Message-Instance", "message-instance"; - AcceptLanguage = 44, id = 44, "Accept-Language", "accept-language"; - AlternateRecipient = 45, id = 45, "Alternate-Recipient", "alternate-recipient"; - ArchivedAt = 46, id = 46, "Archived-At", "archived-at"; - AuthenticationResults = 47, id = 47, "Authentication-Results", "authentication-results"; - AutoSubmitted = 48, id = 48, "Auto-Submitted", "auto-submitted"; - Autoforwarded = 49, id = 49, "Autoforwarded", "autoforwarded"; - Autosubmitted = 50, id = 50, "Autosubmitted", "autosubmitted"; - ContentAlternative = 51, id = 51, "Content-Alternative", "content-alternative"; - ContentDuration = 52, id = 52, "Content-Duration", "content-duration"; - ContentFeatures = 53, id = 53, "Content-features", "content-features"; - ContentMd5 = 54, id = 54, "Content-MD5", "content-md5"; - ContentTranslationType = 55, id = 55, "Content-Translation-Type", "content-translation-type"; - Conversion = 56, id = 56, "Conversion", "conversion"; - ConversionWithLoss = 57, id = 57, "Conversion-With-Loss", "conversion-with-loss"; - DlExpansionHistory = 58, id = 58, "DL-Expansion-History", "dl-expansion-history"; - DeferredDelivery = 59, id = 59, "Deferred-Delivery", "deferred-delivery"; - DeliveryDate = 60, id = 60, "Delivery-Date", "delivery-date"; - DiscardedX400IpmsExtensions = 61, id = 61, "Discarded-X400-IPMS-Extensions", "discarded-x400-ipms-extensions"; - DiscardedX400MtsExtensions = 62, id = 62, "Discarded-X400-MTS-Extensions", "discarded-x400-mts-extensions"; - DiscloseRecipients = 63, id = 63, "Disclose-Recipients", "disclose-recipients"; - DispositionNotificationOptions = 64, id = 64, "Disposition-Notification-Options", "disposition-notification-options"; - DispositionNotificationTo = 65, id = 65, "Disposition-Notification-To", "disposition-notification-to"; - DowngradedFinalRecipient = 66, id = 66, "Downgraded-Final-Recipient", "downgraded-final-recipient"; - DowngradedInReplyTo = 67, id = 67, "Downgraded-In-Reply-To", "downgraded-in-reply-to"; - DowngradedMessageId = 68, id = 68, "Downgraded-Message-Id", "downgraded-message-id"; - DowngradedOriginalRecipient = 69, id = 69, "Downgraded-Original-Recipient", "downgraded-original-recipient"; - DowngradedReferences = 70, id = 70, "Downgraded-References", "downgraded-references"; - Encoding = 71, id = 71, "Encoding", "encoding"; - Expires = 72, id = 72, "Expires", "expires"; - GenerateDeliveryReport = 73, id = 73, "Generate-Delivery-Report", "generate-delivery-report"; - HpOuter = 74, id = 74, "HP-Outer", "hp-outer"; - Importance = 75, id = 75, "Importance", "importance"; - IncompleteCopy = 76, id = 76, "Incomplete-Copy", "incomplete-copy"; - Language = 77, id = 77, "Language", "language"; - LatestDeliveryTime = 78, id = 78, "Latest-Delivery-Time", "latest-delivery-time"; - ListUnsubscribePost = 79, id = 79, "List-Unsubscribe-Post", "list-unsubscribe-post"; - MessageContext = 80, id = 80, "Message-Context", "message-context"; - MessageType = 81, id = 81, "Message-Type", "message-type"; - MmhsExemptedAddress = 82, id = 82, "MMHS-Exempted-Address", "mmhs-exempted-address"; - MmhsExtendedAuthorisationInfo = 83, id = 83, "MMHS-Extended-Authorisation-Info", "mmhs-extended-authorisation-info"; - MmhsSubjectIndicatorCodes = 84, id = 84, "MMHS-Subject-Indicator-Codes", "mmhs-subject-indicator-codes"; - MmhsHandlingInstructions = 85, id = 85, "MMHS-Handling-Instructions", "mmhs-handling-instructions"; - MmhsMessageInstructions = 86, id = 86, "MMHS-Message-Instructions", "mmhs-message-instructions"; - MmhsCodressMessageIndicator = 87, id = 87, "MMHS-Codress-Message-Indicator", "mmhs-codress-message-indicator"; - MmhsOriginatorReference = 88, id = 88, "MMHS-Originator-Reference", "mmhs-originator-reference"; - MmhsPrimaryPrecedence = 89, id = 89, "MMHS-Primary-Precedence", "mmhs-primary-precedence"; - MmhsCopyPrecedence = 90, id = 90, "MMHS-Copy-Precedence", "mmhs-copy-precedence"; - MmhsMessageType = 91, id = 91, "MMHS-Message-Type", "mmhs-message-type"; - MmhsOtherRecipientsIndicatorTo = 92, id = 92, "MMHS-Other-Recipients-Indicator-To", "mmhs-other-recipients-indicator-to"; - MmhsOtherRecipientsIndicatorCc = 93, id = 93, "MMHS-Other-Recipients-Indicator-CC", "mmhs-other-recipients-indicator-cc"; - MmhsAcp127MessageIdentifier = 94, id = 94, "MMHS-Acp127-Message-Identifier", "mmhs-acp127-message-identifier"; - MmhsOriginatorPlad = 95, id = 95, "MMHS-Originator-PLAD", "mmhs-originator-plad"; - MtPriority = 96, id = 96, "MT-Priority", "mt-priority"; - Organization = 97, id = 97, "Organization", "organization"; - OriginalEncodedInformationTypes = 98, id = 98, "Original-Encoded-Information-Types", "original-encoded-information-types"; - OriginalFrom = 99, id = 99, "Original-From", "original-from"; - OriginalMessageId = 100, id = 100, "Original-Message-ID", "original-message-id"; - OriginalRecipient = 101, id = 101, "Original-Recipient", "original-recipient"; - OriginatorReturnAddress = 102, id = 102, "Originator-Return-Address", "originator-return-address"; - OriginalSubject = 103, id = 103, "Original-Subject", "original-subject"; - PicsLabel = 104, id = 104, "PICS-Label", "pics-label"; - PreventNonDeliveryReport = 105, id = 105, "Prevent-NonDelivery-Report", "prevent-nondelivery-report"; - Priority = 106, id = 106, "Priority", "priority"; - ReceivedSpf = 107, id = 107, "Received-SPF", "received-spf"; - ReplyBy = 108, id = 108, "Reply-By", "reply-by"; - RequireRecipientValidSince = 109, id = 109, "Require-Recipient-Valid-Since", "require-recipient-valid-since"; - Sensitivity = 110, id = 110, "Sensitivity", "sensitivity"; - Solicitation = 111, id = 111, "Solicitation", "solicitation"; - Supersedes = 112, id = 112, "Supersedes", "supersedes"; - TlsReportDomain = 113, id = 113, "TLS-Report-Domain", "tls-report-domain"; - TlsReportSubmitter = 114, id = 114, "TLS-Report-Submitter", "tls-report-submitter"; - TlsRequired = 115, id = 115, "TLS-Required", "tls-required"; - VbrInfo = 116, id = 116, "VBR-Info", "vbr-info"; - X400ContentIdentifier = 117, id = 117, "X400-Content-Identifier", "x400-content-identifier"; - X400ContentReturn = 118, id = 118, "X400-Content-Return", "x400-content-return"; - X400ContentType = 119, id = 119, "X400-Content-Type", "x400-content-type"; - X400MtsIdentifier = 120, id = 120, "X400-MTS-Identifier", "x400-mts-identifier"; - X400Originator = 121, id = 121, "X400-Originator", "x400-originator"; - X400Received = 122, id = 122, "X400-Received", "x400-received"; - X400Recipients = 123, id = 123, "X400-Recipients", "x400-recipients"; - X400Trace = 124, id = 124, "X400-Trace", "x400-trace"; - ApparentlyTo = 125, id = 125, "Apparently-To", "apparently-to"; - Author = 126, id = 126, "Author", "author"; - CfblAddress = 127, id = 127, "CFBL-Address", "cfbl-address"; - CfblFeedbackId = 128, id = 128, "CFBL-Feedback-ID", "cfbl-feedback-id"; - DeliveredTo = 129, id = 129, "Delivered-To", "delivered-to"; - EdiintFeatures = 130, id = 130, "EDIINT-Features", "ediint-features"; - EesstVersion = 131, id = 131, "Eesst-Version", "eesst-version"; - ErrorsTo = 132, id = 132, "Errors-To", "errors-to"; - Face = 133, id = 133, "Face", "face"; - FormSub = 134, id = 134, "Form-Sub", "form-sub"; - JabberId = 135, id = 135, "Jabber-ID", "jabber-id"; - MmhsAuthorizingUsers = 136, id = 136, "MMHS-Authorizing-Users", "mmhs-authorizing-users"; - Privicon = 137, id = 137, "Privicon", "privicon"; - SioLabel = 138, id = 138, "SIO-Label", "sio-label"; - SioLabelHistory = 139, id = 139, "SIO-Label-History", "sio-label-history"; - WrongRecipient = 140, id = 140, "Wrong-Recipient", "wrong-recipient"; -} - -/// Parsed header value. -#[derive(Debug, PartialEq, Eq, Clone, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub enum HeaderValue<'x> { - /// Address list or group - Address(Address<'x>), - - /// String - Text(#[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] Cow<'x, str>), - - /// List of strings - TextList( - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - Vec<Cow<'x, str>>, - ), - - /// Datetime - DateTime(DateTime), - - /// Content-Type or Content-Disposition header - ContentType(ContentType<'x>), - - /// Received header - Received(Box<Received<'x>>), - - #[default] - Empty, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub enum Address<'x> { - /// Address list - List(Vec<Addr<'x>>), - /// Group of addresses - Group(Vec<Group<'x>>), -} - -/// Header form -#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] -pub enum HeaderForm { - Raw, - Text, - Addresses, - GroupedAddresses, - MessageIds, - Date, - URLs, -} -/// An RFC2047 Content-Type or RFC2183 Content-Disposition MIME header field. -#[derive(Debug, PartialEq, Eq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct ContentType<'x> { - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] - pub c_type: Cow<'x, str>, - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub c_subtype: Option<Cow<'x, str>>, - #[cfg_attr(feature = "serde", serde(default))] - pub attributes: Option<Vec<Attribute<'x>>>, -} - -#[derive(Debug, PartialEq, Eq, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct Attribute<'x> { - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] - pub name: Cow<'x, str>, - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] - pub value: Cow<'x, str>, -} - -/// An RFC5322 datetime. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct DateTime { - pub year: u16, - pub month: u8, - pub day: u8, - pub hour: u8, - pub minute: u8, - pub second: u8, - pub tz_before_gmt: bool, - pub tz_hour: u8, - pub tz_minute: u8, -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub struct Received<'x> { - #[cfg_attr(feature = "serde", serde(default))] - pub from: Option<Host<'x>>, - #[cfg_attr(feature = "serde", serde(default))] - pub from_ip: Option<IpAddr>, - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub from_iprev: Option<Cow<'x, str>>, - #[cfg_attr(feature = "serde", serde(default))] - pub by: Option<Host<'x>>, - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub for_: Option<Cow<'x, str>>, - #[cfg_attr(feature = "serde", serde(default))] - pub with: Option<Protocol>, - #[cfg_attr(feature = "serde", serde(default))] - pub tls_version: Option<TlsVersion>, - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub tls_cipher: Option<Cow<'x, str>>, - #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub id: Option<Cow<'x, str>>, - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub ident: Option<Cow<'x, str>>, - #[cfg_attr(feature = "serde", serde(default))] - pub helo: Option<Host<'x>>, - #[cfg_attr(feature = "serde", serde(default))] - pub helo_cmd: Option<Greeting>, - #[cfg_attr(feature = "serde", serde(default))] - #[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::Map<rkyv::with::AsOwned>))] - pub via: Option<Cow<'x, str>>, - pub date: Option<DateTime>, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub enum Host<'x> { - Name(#[cfg_attr(feature = "rkyv", rkyv(with = rkyv::with::AsOwned))] Cow<'x, str>), - IpAddr(IpAddr), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub enum TlsVersion { - SSLv2, - SSLv3, - TLSv1_0, - TLSv1_1, - TLSv1_2, - TLSv1_3, - DTLSv1_0, - DTLSv1_2, - DTLSv1_3, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -pub enum Greeting { - Helo, - Ehlo, - Lhlo, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr( - feature = "rkyv", - derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive) -)] -#[allow(clippy::upper_case_acronyms)] -pub enum Protocol { - // IANA Mail Transmission Types - SMTP, - ESMTP, - ESMTPA, - ESMTPS, - ESMTPSA, - LMTP, - LMTPA, - LMTPS, - LMTPSA, - MMS, - UTF8SMTP, - UTF8SMTPA, - UTF8SMTPS, - UTF8SMTPSA, - UTF8LMTP, - UTF8LMTPA, - UTF8LMTPS, - UTF8LMTPSA, - - // Non-Standard Mail Transmission Types - HTTP, - HTTPS, - IMAP, - POP3, - Local, // includes stdin, socket, etc. -} - -/// MIME Header field access trait -pub trait MimeHeaders<'x> { - /// Returns the Content-Description field - fn content_description(&self) -> Option<&str>; - /// Returns the Content-Disposition field - fn content_disposition(&self) -> Option<&ContentType<'_>>; - /// Returns the Content-ID field - fn content_id(&self) -> Option<&str>; - /// Returns the Content-Encoding field - fn content_transfer_encoding(&self) -> Option<&str>; - /// Returns the Content-Type field - fn content_type(&self) -> Option<&ContentType<'_>>; - /// Returns the Content-Language field - fn content_language(&self) -> &HeaderValue<'_>; - /// Returns the Content-Location field - fn content_location(&self) -> Option<&str>; - /// Returns the attachment name, if any. - fn attachment_name(&self) -> Option<&str> { - self.content_disposition() - .and_then(|cd| cd.attribute("filename")) - .or_else(|| self.content_type().and_then(|ct| ct.attribute("name"))) - } - // Returns true is the content type matches - fn is_content_type(&self, type_: &str, subtype: &str) -> bool { - self.content_type().is_some_and(|ct| { - ct.c_type.eq_ignore_ascii_case(type_) - && ct - .c_subtype - .as_ref() - .is_some_and(|st| st.eq_ignore_ascii_case(subtype)) - }) - } -} - -pub trait GetHeader<'x> { - fn header_value(&self, name: &HeaderName<'_>) -> Option<&HeaderValue<'x>>; - fn header(&self, name: impl Into<HeaderName<'x>>) -> Option<&Header<'x>>; -} - -struct BodyPartIterator<'x> { - message: &'x Message<'x>, - list: &'x [MessagePartId], - pos: i32, -} - -struct AttachmentIterator<'x> { - message: &'x Message<'x>, - pos: i32, -} diff --git a/src/mailbox/maildir.rs b/src/mailbox/maildir.rs index 6509d90..57b3668 100644 --- a/src/mailbox/maildir.rs +++ b/src/mailbox/maildir.rs @@ -4,12 +4,15 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ +//! Maildir and Maildir++ folders. + use std::{ fs, io, path::{Path, PathBuf}, }; /// Maildir folder iterator +#[derive(Debug)] pub struct FolderIterator<'x> { inbox: Option<MessageIterator>, it_stack: Vec<fs::ReadDir>, @@ -18,6 +21,7 @@ pub struct FolderIterator<'x> { } /// Maildir message iterator +#[derive(Debug)] pub struct MessageIterator { name: Option<String>, cur_it: fs::ReadDir, @@ -36,11 +40,17 @@ pub struct Message { /// Flags of Maildir message #[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)] pub enum Flag { + /// `P`: the message was resent, forwarded or bounced. Passed, + /// `R`: the message was replied to. Replied, + /// `S`: the message was read. Seen, + /// `T`: the message is marked for deletion. Trashed, + /// `D`: the message is a draft. Draft, + /// `F`: the message is flagged. Flagged, } @@ -118,7 +128,8 @@ impl Iterator for FolderIterator<'_> { } loop { - let entry = match self.it_stack.last_mut().unwrap().next() { + let entries = self.it_stack.last_mut()?; + let entry = match entries.next() { Some(Ok(entry)) => entry, Some(Err(err)) => return Some(Err(err)), None => { @@ -338,13 +349,13 @@ mod tests { .join("maildir"), ".".into(), ) - .unwrap() + .expect("maildir exists") { - let folder = folder.unwrap(); + let folder = folder.expect("folder is readable"); let name = folder.name().unwrap_or("INBOX").to_string(); for message in folder { - let mut message = message.unwrap(); + let mut message = message.expect("message is readable"); assert_ne!(message.internal_date(), 0); assert!(message.path.exists()); message.internal_date = 0; diff --git a/src/mailbox/mbox.rs b/src/mailbox/mbox.rs index 7c87bc4..4c2b6b2 100644 --- a/src/mailbox/mbox.rs +++ b/src/mailbox/mbox.rs @@ -4,19 +4,50 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ -use crate::DateTime; -use std::io::BufRead; +//! Mbox files. -/// Parses an Mbox mailbox from a `Read` stream, returning each message as a -/// `Vec<u8>`. +use crate::{DateTime, MONTH}; +use memchr::{memchr, memmem::Finder, memrchr}; +use std::io::{self, BufRead}; + +const SEPARATOR: &[u8] = b"From "; +const QUOTE: u8 = b'>'; +const CONTENTS_CAPACITY: usize = 1024; + +/// Iterates the messages of an mbox read from a buffered reader. /// -/// Supports >From quoting as defined in the [QMail mbox specification](http://qmail.org/qmail-manual-html/man5/mbox.html). +/// A message starts at each line beginning with `From ` (the separator line, +/// which gives [`Message::from`] and [`Message::internal_date`]) and runs to +/// the next one. Lines before the first separator are skipped. Lines quoted +/// as `>From `, `>>From `, ... lose one `>`, as described in the +/// [qmail mbox specification](http://qmail.org/qmail-manual-html/man5/mbox.html). +/// Separators are found with `memchr`, and the contents are copied from the +/// reader's buffer in bulk. +/// +/// ``` +/// use mail_parser::mailbox::mbox::MessageIterator; +/// +/// let mbox = b"From ann@example.com Sat Jan 3 01:05:34 1996\n\ +/// Subject: hello\n\n>From the start\n"; +/// let message = MessageIterator::new(&mbox[..]) +/// .next() +/// .expect("one message") +/// .expect("readable mbox"); +/// assert_eq!(message.from(), "ann@example.com"); +/// assert_eq!(message.internal_date(), 820_631_134); +/// assert_eq!(message.contents(), b"Subject: hello\n\nFrom the start\n"); +/// ``` +#[derive(Debug)] pub struct MessageIterator<T> { reader: T, message: Option<Message>, + line: Vec<u8>, + complete: usize, + separator: Finder<'static>, } -/// Mbox message contents and metadata +/// A message of an mbox: its contents and the metadata of its separator +/// line. #[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord)] pub struct Message { internal_date: u64, @@ -28,10 +59,14 @@ impl<T> MessageIterator<T> where T: BufRead, { + /// Iterates over the messages of the mbox read from `reader`. pub fn new(reader: T) -> MessageIterator<T> { MessageIterator { reader, message: None, + line: Vec::new(), + complete: 0, + separator: Finder::new(SEPARATOR), } } } @@ -40,165 +75,170 @@ impl<T> Iterator for MessageIterator<T> where T: BufRead, { - type Item = std::io::Result<Message>; + type Item = io::Result<Message>; fn next(&mut self) -> Option<Self::Item> { - let mut message_line = Vec::with_capacity(80); - loop { - match self.reader.read_until(b'\n', &mut message_line) { - Ok(0) => return self.message.take().map(Ok), - Ok(_) => {} - Err(e) => return Some(Err(e)), - } - - let is_from = message_line.starts_with(b"From "); - - if is_from { - let message = self.message.take().map(Ok); - self.message = - Message::new(std::str::from_utf8(&message_line).unwrap_or("")).into(); - if message.is_some() { - return message; + if self.line.is_empty() { + let buf = match self.reader.fill_buf() { + Ok(buf) => buf, + Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => return Some(Err(err)), + }; + if buf.is_empty() { + return self.message.take().map(Ok); } - message_line.clear(); - continue; - } - - if let Some(message) = &mut self.message { - if message_line[0] != b'>' { - message.contents.extend_from_slice(&message_line); - message_line.clear(); + if self.complete == 0 || self.complete > buf.len() { + self.complete = memrchr(b'\n', buf).map_or(0, |last| last + 1); + } + if let Some(lines) = buf.get(..self.complete).filter(|lines| !lines.is_empty()) { + let (consumed, finished) = split(&self.separator, &mut self.message, lines); + self.reader.consume(consumed); + self.complete -= consumed; + if finished.is_some() { + return finished.map(Ok); + } continue; } - // can become split_once once slice_split_once becomes stable - let i = message_line - .iter() - .position(|&ch| ch != b'>') - .unwrap_or(message_line.len()); - if message_line[i..].starts_with(b"From ") { - message.contents.extend_from_slice(&message_line[1..]); - } else { - message.contents.extend_from_slice(&message_line); - } } - message_line.clear(); + if let Err(err) = self.reader.read_until(b'\n', &mut self.line) { + return Some(Err(err)); + } + let (_, finished) = split(&self.separator, &mut self.message, &self.line); + self.line.clear(); + if finished.is_some() { + return finished.map(Ok); + } } } } -impl Message { - fn new(hdr: &str) -> Self { - let (internal_date, from) = if let Some((from, date)) = hdr - .strip_prefix("From ") - .and_then(|hdr| hdr.split_once(' ')) - { - let mut dt = DateTime { - year: u16::MAX, - month: u8::MAX, - day: u8::MAX, - hour: u8::MAX, - minute: u8::MAX, - second: u8::MAX, - tz_before_gmt: false, - tz_hour: 0, - tz_minute: 0, - }; +fn split( + separator: &Finder<'_>, + message: &mut Option<Message>, + lines: &[u8], +) -> (usize, Option<Message>) { + let mut copied = 0; + let mut offset = 0; + while let Some(hit) = lines + .get(offset..) + .and_then(|rest| separator.find(rest)) + .map(|found| offset + found) + { + offset = hit + SEPARATOR.len(); + let before = lines.get(..hit).unwrap_or_default(); + let quotes = before + .iter() + .rev() + .take_while(|&&byte| byte == QUOTE) + .count(); + let Some((head, _)) = before.split_at_checked(before.len() - quotes) else { + continue; + }; + if !matches!(head.last(), None | Some(b'\n')) { + continue; + } + let line_start = head.len(); + append(message, lines.get(copied..line_start)); + if quotes > 0 { + copied = line_start + 1; + continue; + } + let line_end = lines + .get(hit..) + .and_then(|rest| memchr(b'\n', rest)) + .map_or(lines.len(), |end| hit + end + 1); + let finished = message.replace(Message::new( + lines.get(line_start..line_end).unwrap_or_default(), + )); + if finished.is_some() { + return (line_end, finished); + } + copied = line_end; + offset = line_end; + } + append(message, lines.get(copied..)); + (lines.len(), None) +} - for (pos, part) in date.split_whitespace().enumerate() { - match pos { - 1 => { - dt.month = if part.eq_ignore_ascii_case("jan") { - 1 - } else if part.eq_ignore_ascii_case("feb") { - 2 - } else if part.eq_ignore_ascii_case("mar") { - 3 - } else if part.eq_ignore_ascii_case("apr") { - 4 - } else if part.eq_ignore_ascii_case("may") { - 5 - } else if part.eq_ignore_ascii_case("jun") { - 6 - } else if part.eq_ignore_ascii_case("jul") { - 7 - } else if part.eq_ignore_ascii_case("aug") { - 8 - } else if part.eq_ignore_ascii_case("sep") { - 9 - } else if part.eq_ignore_ascii_case("oct") { - 10 - } else if part.eq_ignore_ascii_case("nov") { - 11 - } else if part.eq_ignore_ascii_case("dec") { - 12 - } else { - u8::MAX - }; - } - 2 => { - dt.day = part.parse().unwrap_or(u8::MAX); - } - 3 => { - for (pos, part) in part.split(':').enumerate() { - match pos { - 0 => { - dt.hour = part.parse().unwrap_or(u8::MAX); - } - 1 => { - dt.minute = part.parse().unwrap_or(u8::MAX); - } - 2 => { - dt.second = part.parse().unwrap_or(u8::MAX); - } - _ => { - break; - } - } - } - } - 4 => { - dt.year = part.parse().unwrap_or(u16::MAX); - } - _ => (), +fn append(message: &mut Option<Message>, bytes: Option<&[u8]>) { + if let (Some(message), Some(bytes)) = (message, bytes) { + message.contents.extend_from_slice(bytes); + } +} + +fn internal_date(date: &str) -> u64 { + let mut dt = DateTime { + year: u16::MAX, + month: u8::MAX, + day: u8::MAX, + hour: u8::MAX, + minute: u8::MAX, + second: u8::MAX, + tz_before_gmt: false, + tz_hour: 0, + tz_minute: 0, + }; + for (pos, part) in date.split_whitespace().enumerate() { + match pos { + 1 => { + dt.month = MONTH + .iter() + .zip(1..) + .find(|(name, _)| part.eq_ignore_ascii_case(name)) + .map_or(u8::MAX, |(_, month)| month); + } + 2 => dt.day = part.parse().unwrap_or(u8::MAX), + 3 => { + let fields = [&mut dt.hour, &mut dt.minute, &mut dt.second]; + for (field, value) in fields.into_iter().zip(part.split(':')) { + *field = value.parse().unwrap_or(u8::MAX); } } + 4 => dt.year = part.parse().unwrap_or(u16::MAX), + _ => (), + } + } + if dt.is_valid() { + dt.to_timestamp() as u64 + } else { + 0 + } +} - ( - if dt.is_valid() { - dt.to_timestamp() as u64 - } else { - 0 - }, - from.trim().to_string(), - ) - } else { - (0, "".to_string()) - }; - - Self { +impl Message { + fn new(line: &[u8]) -> Self { + let (internal_date, from) = line + .strip_prefix(SEPARATOR) + .and_then(|rest| std::str::from_utf8(rest).ok()) + .and_then(|rest| rest.split_once(' ')) + .map_or((0, String::new()), |(from, date)| { + (internal_date(date), from.trim().to_string()) + }); + Message { internal_date, from, - contents: Vec::with_capacity(1024), + contents: Vec::with_capacity(CONTENTS_CAPACITY), } } - /// Returns the message creation date in UTC seconds since UNIX epoch + /// The date of the separator line, in seconds since the UNIX epoch; 0 + /// when it is missing or does not parse. pub fn internal_date(&self) -> u64 { self.internal_date } - /// Returns the message sender address + /// The sender address of the separator line; empty when missing. pub fn from(&self) -> &str { &self.from } - /// Returns the message contents + /// The message, ready for [`crate::MessageParser::parse`]. pub fn contents(&self) -> &[u8] { &self.contents } - /// Unwraps the message contents + /// Takes the message contents. pub fn unwrap_contents(self) -> Vec<u8> { self.contents } @@ -206,13 +246,11 @@ impl Message { #[cfg(test)] mod tests { - use crate::mailbox::mbox::Message; + use super::{Message, MessageIterator}; + use crate::scan::tests::Rng; + use std::io::{self, BufRead, BufReader, Read}; - use super::MessageIterator; - - #[test] - fn parse_mbox() { - let message = br#"From god@heaven.af.mil Sat Jan 3 01:05:34 1996 + const MBOX: &[u8] = br#"From god@heaven.af.mil Sat Jan 3 01:05:34 1996 Message 1 From cras@irccrew.org Tue Jul 23 19:39:23 2002 @@ -230,8 +268,8 @@ Message 4 >F "#; - let parser = MessageIterator::new(&message[..]); - let expected_messages = vec![ + fn expected() -> Vec<Message> { + vec![ Message { internal_date: 820631134, from: "god@heaven.af.mil".to_string(), @@ -252,10 +290,137 @@ Message 4 from: "other@domain.com".to_string(), contents: b"Message 4\n> From\n>F\n".to_vec(), }, - ]; + ] + } - for (message, expected_messages) in parser.zip(expected_messages) { - assert_eq!(message.unwrap(), expected_messages); + fn read_all(reader: impl BufRead) -> Vec<Message> { + MessageIterator::new(reader) + .map(|message| message.expect("message is readable")) + .collect() + } + + fn unquoted(line: &[u8]) -> &[u8] { + let quotes = line.iter().take_while(|&&byte| byte == b'>').count(); + match (line.get(quotes..), line.get(1..)) { + (Some(rest), Some(unquoted)) if quotes > 0 && rest.starts_with(b"From ") => unquoted, + _ => line, } } + + fn reference(mbox: &[u8]) -> Vec<Message> { + let mut messages = Vec::new(); + let mut current: Option<Message> = None; + for line in mbox.split_inclusive(|&byte| byte == b'\n') { + if line.starts_with(b"From ") { + messages.extend(current.replace(Message::new(line))); + } else if let Some(message) = &mut current { + message.contents.extend_from_slice(unquoted(line)); + } + } + messages.extend(current); + messages + } + + struct Chunked<'x> { + data: &'x [u8], + sizes: Vec<usize>, + 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).max(1); + self.next = (self.next + 1) % self.sizes.len().max(1); + let len = size.min(buf.len()).min(self.data.len()); + let (head, tail) = self.data.split_at(len); + buf.get_mut(..len) + .expect("length fits") + .copy_from_slice(head); + self.data = tail; + Ok(len) + } + } + + #[test] + fn parse_mbox() { + assert_eq!(read_all(MBOX), expected()); + assert_eq!(reference(MBOX), expected()); + } + + #[test] + fn buffer_boundaries() { + for capacity in 1..=64 { + assert_eq!( + read_all(BufReader::with_capacity(capacity, MBOX)), + expected(), + "capacity {capacity}" + ); + } + } + + #[test] + fn same_as_line_reader() { + const PIECES: [&[u8]; 14] = [ + b"From ", + b">", + b">>", + b"From a@b Sat Jan 3 01:05:34 1996", + b"\n", + b"\r\n", + b"text", + b" ", + b"From", + b"F", + b"rom ", + b">From x", + b"x@y", + b"From \xff Tue Jul 23 19:39:23 2002", + ]; + let mut rng = Rng(0x6d62_6f78_0000_0001); + for round in 0..4_000 { + let mbox: Vec<u8> = (0..rng.below(40)) + .flat_map(|_| { + PIECES + .get(rng.below(PIECES.len())) + .copied() + .unwrap_or_default() + }) + .copied() + .collect(); + let expected = reference(&mbox); + assert_eq!(read_all(&mbox[..]), expected, "round {round}: {mbox:?}"); + let capacity = 1 + rng.below(12); + assert_eq!( + read_all(BufReader::with_capacity(capacity, &mbox[..])), + expected, + "round {round} capacity {capacity}: {mbox:?}" + ); + let sizes = (0..4).map(|_| 1 + rng.below(9)).collect(); + let chunked = Chunked { + data: &mbox, + sizes, + next: 0, + }; + assert_eq!( + read_all(BufReader::with_capacity(16, chunked)), + expected, + "round {round} chunked: {mbox:?}" + ); + } + } + + #[test] + fn long_lines_and_missing_final_newline() { + let long = "x".repeat(10_000); + let mbox = format!( + "{long}\nFrom a@b Sat Jan 3 01:05:34 1996\n{long}\n>From {long}\nFrom c@d {long}" + ); + let expected = reference(mbox.as_bytes()); + assert_eq!(expected.len(), 2); + assert_eq!(read_all(mbox.as_bytes()), expected); + assert_eq!( + read_all(BufReader::with_capacity(64, mbox.as_bytes())), + expected + ); + } } diff --git a/src/mailbox/mod.rs b/src/mailbox/mod.rs index d6a258b..0944602 100644 --- a/src/mailbox/mod.rs +++ b/src/mailbox/mod.rs @@ -1,2 +1,10 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +//! Readers for mailbox files: mbox and Maildir. + pub mod maildir; pub mod mbox; diff --git a/src/parser/builder.rs b/src/parser/builder.rs new file mode 100644 index 0000000..67ee91c --- /dev/null +++ b/src/parser/builder.rs @@ -0,0 +1,1176 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{ + MessageParser, + classify::{Container, Disposition, Leaf, MimeClass, MimeType}, + delimiter::{Dashed, Delimiter, dashed_boundary}, +}; +use crate::{ + Encoding, decoders, + scan::Kernel, + store::{ + ContentTypeEntry, KindTag, MessageData, MessageEntry, MessageId, NONE, PartEntry, PartId, + SourceBuffer, Span, Str, flag, role, + }, +}; +use std::ops::Range; + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Frame { + kind: FrameKind, + part: PartId, + message: MessageId, + state: Container, +} + +#[derive(Debug, Clone, Copy)] +enum FrameKind { + Message(Option<Encoded>), + Multipart { + boundary: Str, + closed: bool, + children: u32, + }, +} + +#[derive(Debug, Clone, Copy)] +struct Encoded { + parent_source: u32, + parent_base: u32, + parent_open: u32, + resume: Option<Delimiter>, +} + +#[derive(Debug, Clone, Copy)] +struct SeekMemo { + from: u32, + line: u32, +} + +#[derive(Debug, Clone, Copy)] +struct BoundaryMemo { + boundary: Str, + from: u32, + line: u32, +} + +impl SeekMemo { + fn covers(self, src: &[u8], from: usize) -> bool { + u32::try_from(from).is_ok_and(|start| { + self.from <= start + && start <= self.line + && (start == self.from + || from.checked_sub(1).and_then(|last| src.get(last)) == Some(&b'\n')) + }) + } +} + +const INLINE_FRAMES: usize = 4; +const SAVED_SEEKS: usize = 4; +const SPILL_FRAMES: usize = 16; +const FIRST_MESSAGES: usize = 8; +const FIRST_SINGLE_PARTS: usize = 4; +const FIRST_MULTIPART_PARTS: usize = 16; +const FIRST_IDS: usize = 32; +const FIRST_PENDING: usize = 16; +const MIN_HEADERS: usize = 32; +const MAX_HEADERS: usize = 128; +const BYTES_PER_HEADER: usize = 128; + +#[derive(Debug)] +struct Frames { + inline: [Frame; INLINE_FRAMES], + len: usize, + spill: Vec<Frame>, +} + +impl Frames { + fn new(mut spill: Vec<Frame>) -> Self { + spill.clear(); + let filler = Frame { + kind: FrameKind::Message(None), + part: NONE, + message: 0, + state: Container::message(), + }; + Frames { + inline: [filler; INLINE_FRAMES], + len: 0, + spill, + } + } + + fn as_slice(&self) -> &[Frame] { + if self.spill.is_empty() { + self.inline.get(..self.len).unwrap_or_default() + } else { + &self.spill + } + } + + fn as_mut_slice(&mut self) -> &mut [Frame] { + if self.spill.is_empty() { + self.inline.get_mut(..self.len).unwrap_or_default() + } else { + &mut self.spill + } + } + + fn len(&self) -> usize { + self.len + } + + fn push(&mut self, frame: Frame) { + if self.spill.is_empty() + && let Some(slot) = self.inline.get_mut(self.len) + { + *slot = frame; + } else { + if self.spill.is_empty() { + self.spill.reserve(SPILL_FRAMES); + self.spill + .extend_from_slice(self.inline.get(..self.len).unwrap_or_default()); + } + self.spill.push(frame); + } + self.len += 1; + } + + fn pop(&mut self) -> Option<Frame> { + let frame = match self.spill.pop() { + Some(frame) => frame, + None => *self.inline.get(self.len.checked_sub(1)?)?, + }; + self.len -= 1; + Some(frame) + } + + fn get(&self, index: usize) -> Option<&Frame> { + self.as_slice().get(index) + } + + fn get_mut(&mut self, index: usize) -> Option<&mut Frame> { + self.as_mut_slice().get_mut(index) + } + + fn last(&self) -> Option<&Frame> { + self.as_slice().last() + } + + fn last_mut(&mut self) -> Option<&mut Frame> { + self.as_mut_slice().last_mut() + } + + fn into_spill(mut self) -> Vec<Frame> { + self.spill.clear(); + self.spill + } +} + +pub(super) enum Next { + Part(usize), + Enter(Enter), + SourceEnd, +} + +struct LeafEnd { + body: Range<usize>, + encoding: Encoding, + flags: u16, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Enclosing { + Continues, + EndsHere, +} + +impl Enclosing { + fn end(self, src: &[u8], delimiter: Option<Delimiter>, body: usize) -> usize { + delimiter.map_or(src.len(), |delimiter| match self { + Enclosing::Continues => delimiter.content_end(src, body), + Enclosing::EndsHere => delimiter.content_end(src, 0), + }) + } +} + +pub(super) struct Enter { + decoded: Vec<u8>, + part: PartId, + resume: Option<Delimiter>, +} + +pub(super) struct Builder<'p, 'd> { + pub(super) conf: &'p MessageParser, + pub(super) kernel: Kernel, + pub(super) data: &'d mut MessageData, + frames: Frames, + pending: Vec<PartId>, + source: u32, + base: usize, + open: usize, + seek_memo: Option<SeekMemo>, + saved_seeks: [Option<SeekMemo>; SAVED_SEEKS], + boundary_memo: Option<BoundaryMemo>, + encoded_depth: u32, + max_depth: usize, + max_parts: usize, + max_encoded_nesting: u32, + stopped: bool, + headers_only: bool, +} + +fn source_bytes<'a>(raw: &'a [u8], sources: &'a [SourceBuffer], source: u32) -> &'a [u8] { + match source.checked_sub(1) { + None => raw, + Some(index) => sources + .get(index as usize) + .map_or(&[], |source| source.bytes.as_ref()), + } +} + +impl<'p, 'd> Builder<'p, 'd> { + pub(super) fn new( + conf: &'p MessageParser, + data: &'d mut MessageData, + headers_only: bool, + ) -> Self { + let frames = Frames::new(std::mem::take(&mut data.scratch.frames)); + let mut pending = std::mem::take(&mut data.scratch.pending); + pending.clear(); + let (max_depth, max_parts, max_encoded_nesting) = conf.limits(); + Builder { + conf, + kernel: conf.scan_kernel(), + data, + frames, + pending, + source: 0, + base: 0, + open: 0, + seek_memo: None, + saved_seeks: [None; SAVED_SEEKS], + boundary_memo: None, + encoded_depth: 0, + max_depth: max_depth as usize, + max_parts: max_parts as usize, + max_encoded_nesting, + stopped: false, + headers_only, + } + } + + pub(super) fn run(mut self, raw: &[u8]) -> bool { + self.reserve(raw.len()); + let mut sources = std::mem::take(&mut self.data.sources); + self.open_message(NONE, 0, None); + let mut next = Next::Part(0); + while !self.stopped { + let src = source_bytes(raw, &sources, self.source); + next = match next { + Next::Part(offset) => self.part(src, offset), + Next::Enter(enter) => { + sources.push(SourceBuffer { + bytes: enter.decoded.into_boxed_slice(), + container: enter.part, + }); + self.enter(enter.part, enter.resume, sources.len() as u32) + } + Next::SourceEnd if self.source == 0 => break, + Next::SourceEnd => { + let (resume, discard) = self.leave(src); + if discard { + sources.pop(); + } + let parent = source_bytes(raw, &sources, self.source); + self.advance(parent, resume) + } + }; + } + if self.stopped { + self.extend_last_part(raw, &sources); + } + loop { + let src = source_bytes(raw, &sources, self.source); + if self.source == 0 { + self.unwind(src, 0, None); + break; + } + if self.leave(src).1 { + sources.pop(); + } + } + let has_root = self + .data + .messages + .first() + .is_some_and(|message| message.root != NONE); + self.data.sources = sources; + self.pending.clear(); + self.data.scratch.frames = self.frames.into_spill(); + self.data.scratch.pending = self.pending; + has_root + } + + fn reserve(&mut self, len: usize) { + self.data + .headers + .reserve((len / BYTES_PER_HEADER).clamp(MIN_HEADERS, MAX_HEADERS)); + } + + fn part(&mut self, src: &[u8], offset: usize) -> Next { + let parts = self.data.parts.len(); + if parts >= self.max_parts { + self.stopped = true; + return Next::SourceEnd; + } + let headers_start = self.data.headers.len(); + let block = self.header_block(src, offset); + let headers_len = self.data.headers.len() - headers_start; + let body = block + .delimiter() + .map_or(block.body, |delimiter| delimiter.content_end(src, offset)); + let Some(frame) = self.frames.last() else { + return Next::SourceEnd; + }; + let message = frame.message; + let in_multipart = matches!(frame.kind, FrameKind::Multipart { .. }); + let message_empty = self + .data + .messages + .get(message as usize) + .is_none_or(|entry| entry.root == NONE); + if headers_len == 0 + && (block.reaches_eof() || !block.has_blank_line() && !in_multipart && message_empty) + { + return self.advance(src, block.delimiter()); + } + + let part_id = parts as PartId; + let Some(frame) = self.frames.last_mut() else { + return Next::SourceEnd; + }; + frame.state.parts += 1; + let parent_mime = frame.state.mime_type; + let parent = if in_multipart { + self.pending.push(part_id); + frame.part + } else { + NONE + }; + + let mime = block.mime; + let content_type = self + .data + .content_types + .get(mime.content_type as usize) + .copied(); + let disposition_type = self + .data + .content_types + .get(mime.disposition as usize) + .copied(); + let class = MimeClass::new( + content_type.map(|entry| self.content_type_strs(src, entry)), + parent_mime, + ); + let boundary = if class.is_multipart { + content_type.and_then(|entry| self.param(src, entry, "boundary")) + } else { + None + }; + let disposition = + Disposition::new(disposition_type.map(|entry| self.content_type_strs(src, entry).0)); + let is_text_body = class.is_text_body(); + let name = if is_text_body { + content_type.and_then(|entry| self.param(src, entry, "name")) + } else { + None + }; + let has_part_name = is_text_body + && disposition_type + .and_then(|entry| self.param(src, entry, "filename")) + .or(name) + .is_some_and(|name| !name.is_empty()); + + if self.data.parts.capacity() == 0 { + self.data.parts.reserve_exact(if class.is_multipart { + FIRST_MULTIPART_PARTS + } else { + FIRST_SINGLE_PARTS + }); + } + self.data.parts.push(PartEntry { + offset_header: offset as u32, + offset_body: body as u32, + offset_end: body as u32, + headers: Span { + start: headers_start as u32, + len: headers_len as u32, + }, + parent, + message, + content_type: mime.content_type, + content_disposition: mime.disposition, + children: Span::default(), + kind: KindTag::Text, + encoding: mime.encoding, + flags: if block.has_blank_line() { + 0 + } else { + flag::NO_BLANK_LINE + }, + }); + if message_empty && let Some(entry) = self.data.messages.get_mut(message as usize) { + entry.root = part_id; + } + + if self.headers_only { + self.update_part(part_id, |part| { + part.kind = class.plain_kind(); + part.offset_end = src.len() as u32; + }); + return Next::SourceEnd; + } + + let mut class = class; + let mut known_end = block.delimiter().map(Some); + if let Some(boundary) = boundary { + if block.delimiter().is_some() { + class = class.as_broken_text(); + } else if self.frames.len() >= self.max_depth { + self.add_flags(part_id, flag::LIMIT_REACHED); + class = class.as_broken_text(); + } else { + match self.open_multipart(src, boundary, class.mime_type, part_id, message, body) { + Ok(delimiter) => { + self.update_part(part_id, |part| { + part.kind = KindTag::Multipart; + if delimiter.fallback { + part.flags |= flag::FALLBACK_DELIMITER; + } + }); + return self.advance(src, Some(delimiter)); + } + Err(end) => { + class = class.as_broken_text(); + known_end = Some(end); + } + } + } + } else if class.mime_type == MimeType::Message + && mime.encoding == Encoding::None + && block.delimiter().is_none() + { + if self.frames.len() >= self.max_depth { + self.add_flags(part_id, flag::LIMIT_REACHED); + } else { + let roles = self.frames.last().map_or(role::ATTACHMENT, |frame| { + frame.state.message_roles(disposition) + }); + self.add_roles(part_id, message, roles); + let nested = self.open_message(part_id, self.source, None); + self.update_part(part_id, |part| { + part.kind = KindTag::Message; + part.children = Span { + start: nested, + len: 0, + }; + }); + return Next::Part(body); + } + } + + let (delimiter, found) = self.leaf_end(src, body, known_end); + let mut flags = 0; + if !found { + flags |= flag::MISSING_DELIMITER; + } + if delimiter.is_some_and(|d| d.fallback) { + flags |= flag::FALLBACK_DELIMITER; + } + let enclosing = match delimiter { + Some(delimiter) if delimiter.frame + 1 < self.frames.len() => Enclosing::EndsHere, + _ => Enclosing::Continues, + }; + let end = enclosing.end(src, delimiter, body); + let end = LeafEnd { + body: body.min(end)..end, + encoding: mime.encoding, + flags, + }; + let leaf = Leaf { + class, + disposition, + has_part_name, + }; + self.leaf(src, part_id, message, leaf, delimiter, end) + } + + fn leaf( + &mut self, + src: &[u8], + part_id: PartId, + message: MessageId, + leaf: Leaf, + delimiter: Option<Delimiter>, + end: LeafEnd, + ) -> Next { + if leaf.class.mime_type == MimeType::Message { + let roles = self.frames.last().map_or(role::ATTACHMENT, |frame| { + frame.state.message_roles(leaf.disposition) + }); + let nesting = if end.encoding == Encoding::None || self.max_encoded_nesting == 0 { + 0 + } else if self.encoded_depth >= self.max_encoded_nesting { + flag::NESTING_LIMIT + } else if self.frames.len() >= self.max_depth { + flag::LIMIT_REACHED + } else { + self.finish_leaf(part_id, message, &end, None, roles); + let mut decoded = Vec::new(); + decoders::transfer_decode_append( + src.get(end.body).unwrap_or_default(), + end.encoding, + &mut decoded, + ); + return Next::Enter(Enter { + decoded, + part: part_id, + resume: delimiter, + }); + }; + let end = LeafEnd { + flags: end.flags | nesting, + ..end + }; + self.finish_leaf(part_id, message, &end, Some(KindTag::Binary), roles); + } else if let Some(frame) = self.frames.last_mut() { + let classified = frame.state.classify(&leaf); + self.finish_leaf( + part_id, + message, + &end, + Some(classified.kind), + classified.roles, + ); + } + self.advance(src, delimiter) + } + + fn finish_leaf( + &mut self, + part: PartId, + message: MessageId, + end: &LeafEnd, + kind: Option<KindTag>, + roles: u16, + ) { + let Some(entry) = self.data.parts.get_mut(part as usize) else { + return; + }; + entry.offset_header = entry.offset_header.min(end.body.end as u32); + entry.offset_body = end.body.start as u32; + entry.offset_end = end.body.end as u32; + if let Some(kind) = kind { + entry.kind = kind; + } + let added = roles & !entry.flags; + entry.flags |= end.flags | roles; + self.count_roles(message, added); + } + + fn enter(&mut self, part: PartId, resume: Option<Delimiter>, source: u32) -> Next { + let encoded = Encoded { + parent_source: self.source, + parent_base: self.base as u32, + parent_open: self.open as u32, + resume, + }; + self.boundary_memo = None; + let parent_seek = self.seek_memo.take(); + if let Some(slot) = self.saved_seeks.get_mut(self.encoded_depth as usize) { + *slot = parent_seek; + } + let nested = self.open_message(part, source, Some(encoded)); + self.update_part(part, |part| { + part.kind = KindTag::Message; + part.children = Span { + start: nested, + len: 0, + }; + }); + self.base = self.frames.len() - 1; + self.open = 0; + self.source = source; + self.encoded_depth += 1; + Next::Part(0) + } + + fn leave(&mut self, src: &[u8]) -> (Option<Delimiter>, bool) { + self.unwind(src, self.base + 1, None); + let Some(frame) = self.frames.pop() else { + return (None, false); + }; + let FrameKind::Message(Some(encoded)) = frame.kind else { + return (None, false); + }; + if let Some(root) = self + .data + .messages + .get(frame.message as usize) + .map(|entry| entry.root) + { + self.update_part(root, |part| part.offset_end = src.len() as u32); + } + let discard = self.close_message(frame.message, frame.part, true); + self.source = encoded.parent_source; + self.base = encoded.parent_base as usize; + self.open = encoded.parent_open as usize; + self.boundary_memo = None; + self.encoded_depth = self.encoded_depth.saturating_sub(1); + self.seek_memo = self + .saved_seeks + .get(self.encoded_depth as usize) + .copied() + .flatten(); + (encoded.resume, discard) + } + + fn extend_last_part(&mut self, raw: &[u8], sources: &[SourceBuffer]) { + let (Some(frame), Some(last)) = (self.frames.last().copied(), self.data.parts.last()) + else { + return; + }; + let last_id = (self.data.parts.len() - 1) as PartId; + let is_open_leaf = matches!(frame.kind, FrameKind::Multipart { .. }) + && last.parent == frame.part + && !matches!(last.kind, KindTag::Multipart | KindTag::Message); + let holder = if is_open_leaf || frame.part == NONE { + last_id + } else { + frame.part + }; + if is_open_leaf { + let end = source_bytes(raw, sources, self.source).len() as u32; + self.update_part(last_id, |part| part.offset_end = end); + } + self.add_flags(holder, flag::LIMIT_REACHED); + } + + pub(super) fn advance(&mut self, src: &[u8], mut delimiter: Option<Delimiter>) -> Next { + loop { + let Some(found) = delimiter else { + return Next::SourceEnd; + }; + self.unwind(src, found.frame + 1, Some(found)); + if !found.is_close { + return Next::Part(found.next); + } + self.close_multipart(found.frame); + delimiter = self.seek(src, found.next); + } + } + + fn open_message( + &mut self, + container: PartId, + source: u32, + encoded: Option<Encoded>, + ) -> MessageId { + let id = self.data.messages.push( + MessageEntry { + root: NONE, + parts_end: NONE, + source, + container, + lists: 0, + text_len: 0, + html_len: 0, + attachments_len: 0, + }, + FIRST_MESSAGES, + ); + self.frames.push(Frame { + kind: FrameKind::Message(encoded), + part: container, + message: id, + state: Container::message(), + }); + id + } + + fn open_multipart( + &mut self, + src: &[u8], + boundary: Str, + mime_type: MimeType, + part_id: PartId, + message: MessageId, + body: usize, + ) -> Result<Delimiter, Option<Delimiter>> { + if boundary.is_empty() + || self.no_delimiter_ahead(src, body) && !self.boundary_occurs(src, boundary, body) + { + return Err(self.seek(src, body)); + } + let Some(parent) = self.frames.last() else { + return Err(None); + }; + let (html_len, text_len) = self + .data + .messages + .get(message as usize) + .map_or((0, 0), |entry| (entry.html_len, entry.text_len)); + let state = parent.state.multipart(mime_type, html_len, text_len); + if self.pending.capacity() == 0 { + self.pending.reserve_exact(FIRST_PENDING); + } + self.frames.push(Frame { + kind: FrameKind::Multipart { + boundary, + closed: false, + children: self.pending.len() as u32, + }, + part: part_id, + message, + state, + }); + self.open += 1; + self.seek_memo = None; + let frame = self.frames.len() - 1; + match self.seek(src, body) { + Some(delimiter) if delimiter.frame == frame && !delimiter.is_close => Ok(delimiter), + Some(close) if close.frame == frame => { + self.remember_seek(body, Some(close)); + Ok(self + .mid_line_delimiter(src, frame, body, close.line) + .filter(|delimiter| !delimiter.is_close) + .unwrap_or(close)) + } + other => { + self.remember_seek(body, other); + let limit = other.map_or(src.len(), |d| d.line); + if let Some(delimiter) = self.mid_line_delimiter(src, frame, body, limit) { + return Ok(delimiter); + } + self.frames.pop(); + self.open -= 1; + Err(other) + } + } + } + + fn no_delimiter_ahead(&self, src: &[u8], from: usize) -> bool { + self.seek_memo + .is_some_and(|memo| memo.line == NONE && memo.covers(src, from)) + } + + fn remember_seek(&mut self, from: usize, found: Option<Delimiter>) { + self.seek_memo = Some(SeekMemo { + from: from as u32, + line: found.map_or(NONE, |delimiter| delimiter.line as u32), + }); + } + + fn boundary_occurs(&mut self, src: &[u8], boundary: Str, from: usize) -> bool { + let bytes = boundary.resolve(src, &self.data.strings).as_bytes(); + let start = from as u32; + if let Some(memo) = self.boundary_memo + && memo.from <= start + && start <= memo.line + && memo.boundary.resolve(src, &self.data.strings).as_bytes() == bytes + { + return memo.line != NONE; + } + let line = match dashed_boundary(src, from, bytes) { + Dashed::At(line) => line as u32, + Dashed::Absent => NONE, + Dashed::Unknown => return true, + }; + self.boundary_memo = Some(BoundaryMemo { + boundary, + from: start, + line, + }); + line != NONE + } + + fn close_multipart(&mut self, index: usize) { + let Some(frame) = self.frames.get_mut(index) else { + return; + }; + let FrameKind::Multipart { + closed, children, .. + } = &mut frame.kind + else { + return; + }; + if *closed { + return; + } + *closed = true; + let (part, children, message, state) = (frame.part, *children, frame.message, frame.state); + self.open -= 1; + self.seek_memo = None; + if self.finish_children(part, children) == 0 { + self.add_flags(part, flag::MISSING_DELIMITER); + } + if state.needs_alternative_fixup() { + self.fix_alternative(part, message, state); + } + } + + fn fix_alternative(&mut self, part: PartId, message: MessageId, state: Container) { + let Some(entry) = self.data.messages.get(message as usize).copied() else { + return; + }; + let (from, to) = if entry.text_len == state.text_parts && entry.html_len != state.html_parts + { + (role::IN_HTML_BODY, role::IN_TEXT_BODY) + } else if entry.html_len == state.html_parts && entry.text_len != state.text_parts { + (role::IN_TEXT_BODY, role::IN_HTML_BODY) + } else { + return; + }; + let mut added = 0; + for entry in self + .data + .parts + .iter_mut() + .skip(part as usize + 1) + .filter(|entry| entry.message == message && entry.has_role(from) && !entry.has_role(to)) + { + entry.flags |= to | role::COPIED; + added += 1; + } + if let Some(entry) = self.data.messages.get_mut(message as usize) { + if to == role::IN_TEXT_BODY { + entry.text_len += added; + } else { + entry.html_len += added; + } + } + } + + fn finish_children(&mut self, part: PartId, children: u32) -> usize { + let start = self.data.ids.len(); + let children = (children as usize).min(self.pending.len()); + self.data + .ids + .extend_from_slice(self.pending.get(children..).unwrap_or_default(), FIRST_IDS); + self.pending.truncate(children); + let len = self.data.ids.len() - start; + self.update_part(part, |part| { + part.children = Span { + start: start as u32, + len: len as u32, + } + }); + len + } + + fn unwind(&mut self, src: &[u8], keep: usize, delimiter: Option<Delimiter>) { + while self.frames.len() > keep { + let Some(frame) = self.frames.pop() else { + break; + }; + let enclosing = if self.frames.len() > keep { + Enclosing::EndsHere + } else { + Enclosing::Continues + }; + match frame.kind { + FrameKind::Multipart { + closed, children, .. + } => { + if !closed { + self.open = self.open.saturating_sub(1); + self.seek_memo = None; + self.finish_children(frame.part, children); + if !self.stopped { + self.add_flags(frame.part, flag::UNTERMINATED); + } + if frame.state.needs_alternative_fixup() { + self.fix_alternative(frame.part, frame.message, frame.state); + } + } + self.set_end(src, frame.part, delimiter, enclosing); + } + FrameKind::Message(_) if frame.part == NONE => { + if let Some(root) = self + .data + .messages + .get(frame.message as usize) + .map(|entry| entry.root) + { + self.update_part(root, |part| part.offset_end = src.len() as u32); + } + self.close_message(frame.message, NONE, false); + } + FrameKind::Message(_) => { + self.set_end(src, frame.part, delimiter, enclosing); + self.close_message(frame.message, frame.part, false); + } + } + } + } + + fn set_end( + &mut self, + src: &[u8], + part: PartId, + delimiter: Option<Delimiter>, + enclosing: Enclosing, + ) { + self.update_part(part, |part| { + let end = enclosing.end(src, delimiter, part.offset_body as usize) as u32; + part.offset_header = part.offset_header.min(end); + part.offset_body = part.offset_body.min(end); + part.offset_end = end; + }); + } + + fn close_message(&mut self, message: MessageId, container: PartId, encoded: bool) -> bool { + let Some(entry) = self.data.messages.get(message as usize).copied() else { + return false; + }; + if entry.root != NONE { + self.finish_lists(message, entry); + return false; + } + if container == NONE { + return false; + } + let problem = if self.stopped { + flag::LIMIT_REACHED + } else { + flag::NO_BLANK_LINE + }; + self.update_part(container, |part| { + part.kind = if encoded { + KindTag::Binary + } else { + KindTag::Text + }; + part.children = Span::default(); + part.flags |= problem; + }); + if message as usize + 1 == self.data.messages.len() { + self.data.messages.pop(); + } + encoded + } + + fn finish_lists(&mut self, message: MessageId, entry: MessageEntry) { + let text = entry.text_len as usize; + let html = entry.html_len as usize; + let attachments = entry.attachments_len as usize; + let base = self.data.ids.len(); + self.data + .ids + .resize(base + text + html + attachments, 0, FIRST_IDS); + let slots = self.data.ids.get_mut(base..).unwrap_or_default(); + let (text_slots, rest) = slots.split_at_mut(text.min(slots.len())); + let (html_slots, attachment_slots) = rest.split_at_mut(html.min(rest.len())); + let mut text_slots = text_slots.iter_mut(); + let mut html_slots = html_slots.iter_mut(); + let mut attachment_slots = attachment_slots.iter_mut(); + for (id, part) in self + .data + .parts + .iter() + .enumerate() + .skip(entry.root as usize) + .filter(|(_, part)| part.message == message) + { + let slots = [ + (role::IN_TEXT_BODY, &mut text_slots), + (role::IN_HTML_BODY, &mut html_slots), + (role::ATTACHMENT, &mut attachment_slots), + ]; + for (role, slots) in slots { + if part.has_role(role) + && let Some(slot) = slots.next() + { + *slot = id as PartId; + } + } + } + let parts_end = self.data.parts.len() as PartId; + if let Some(entry) = self.data.messages.get_mut(message as usize) { + entry.lists = base as u32; + entry.parts_end = parts_end; + } + } + + fn leaf_end( + &mut self, + src: &[u8], + body: usize, + known: Option<Option<Delimiter>>, + ) -> (Option<Delimiter>, bool) { + let found = known.unwrap_or_else(|| self.seek(src, body)); + let Some(innermost) = self.innermost_open() else { + return (found, true); + }; + if found.is_some_and(|d| d.frame == innermost) { + return (found, true); + } + if known.is_none() { + self.remember_seek(body, found); + } + let limit = found.map_or(src.len(), |d| d.line); + match self.mid_line_delimiter(src, innermost, body, limit) { + Some(delimiter) => (Some(delimiter), true), + None => (found, false), + } + } + + fn seek(&mut self, src: &[u8], from: usize) -> Option<Delimiter> { + if self.open == 0 { + return None; + } + if let Some(memo) = self.seek_memo + && memo.covers(src, from) + { + return (memo.line != NONE) + .then(|| self.delimiter_at(src, memo.line as usize)) + .flatten(); + } + self.scan_delimiter(src, from) + } + + fn scan_delimiter(&self, src: &[u8], from: usize) -> Option<Delimiter> { + if let Some(delimiter) = self.delimiter_at(src, from) { + return Some(delimiter); + } + let mut cursor = from; + while let Some(newline) = self.kernel.dash_line(src, cursor) { + if let Some(delimiter) = self.delimiter_at(src, newline + 1) { + return Some(delimiter); + } + cursor = newline + 1; + } + None + } + + pub(super) fn has_open_boundaries(&self) -> bool { + self.open > 0 + } + + pub(super) fn delimiter_at(&self, src: &[u8], line: usize) -> Option<Delimiter> { + if !src.get(line..)?.starts_with(b"--") { + return None; + } + self.open_frames() + .find_map(|(index, frame)| match frame.kind { + FrameKind::Multipart { + boundary, + closed: false, + .. + } => Delimiter::at_line( + src, + line, + index, + boundary.resolve(src, &self.data.strings).as_bytes(), + ), + _ => None, + }) + } + + fn open_frames(&self) -> impl Iterator<Item = (usize, &Frame)> { + let base = self.base; + self.frames + .as_slice() + .get(base..) + .unwrap_or_default() + .iter() + .enumerate() + .rev() + .map(move |(index, frame)| (base + index, frame)) + } + + fn innermost_open(&self) -> Option<usize> { + self.open_frames() + .find(|(_, frame)| matches!(frame.kind, FrameKind::Multipart { closed: false, .. })) + .map(|(index, _)| index) + } + + fn mid_line_delimiter( + &self, + src: &[u8], + frame: usize, + from: usize, + limit: usize, + ) -> Option<Delimiter> { + match self.frames.get(frame)?.kind { + FrameKind::Multipart { boundary, .. } => Delimiter::mid_line( + src, + from, + limit, + frame, + boundary.resolve(src, &self.data.strings).as_bytes(), + ), + FrameKind::Message(_) => None, + } + } + + fn content_type_strs<'a>( + &'a self, + src: &'a [u8], + entry: ContentTypeEntry, + ) -> (&'a str, Option<&'a str>) { + ( + entry.ctype.resolve(src, &self.data.strings), + entry.subtype.resolve_option(src, &self.data.strings), + ) + } + + fn param(&self, src: &[u8], entry: ContentTypeEntry, name: &str) -> Option<Str> { + let range: Range<usize> = entry.params.range(); + self.data + .params + .get(range)? + .iter() + .find(|param| param.name.resolve(src, &self.data.strings) == name) + .map(|param| param.value) + } + + fn update_part(&mut self, part: PartId, update: impl FnOnce(&mut PartEntry)) { + if let Some(part) = self.data.parts.get_mut(part as usize) { + update(part); + } + } + + fn add_flags(&mut self, part: PartId, flags: u16) { + self.update_part(part, |part| part.flags |= flags); + } + + fn add_roles(&mut self, part: PartId, message: MessageId, roles: u16) { + let Some(entry) = self.data.parts.get_mut(part as usize) else { + return; + }; + let added = roles & !entry.flags; + entry.flags |= roles; + self.count_roles(message, added); + } + + fn count_roles(&mut self, message: MessageId, added: u16) { + if let Some(message) = self.data.messages.get_mut(message as usize) { + if added & role::IN_TEXT_BODY != 0 { + message.text_len += 1; + } + if added & role::IN_HTML_BODY != 0 { + message.html_len += 1; + } + if added & role::ATTACHMENT != 0 { + message.attachments_len += 1; + } + } + } +} diff --git a/src/parser/classify.rs b/src/parser/classify.rs new file mode 100644 index 0000000..96c07e3 --- /dev/null +++ b/src/parser/classify.rs @@ -0,0 +1,254 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use crate::store::{KindTag, role}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) enum MimeType { + MultipartMixed, + MultipartAlternative, + MultipartRelated, + MultipartDigest, + TextPlain, + TextHtml, + TextOther, + Inline, + #[default] + Message, + Other, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) enum Disposition { + #[default] + None, + Inline, + Attachment, + Other, +} + +impl Disposition { + pub(crate) fn new(disposition_type: Option<&str>) -> Self { + match disposition_type { + None => Disposition::None, + Some(value) if value.eq_ignore_ascii_case("inline") => Disposition::Inline, + Some(value) if value.eq_ignore_ascii_case("attachment") => Disposition::Attachment, + Some(_) => Disposition::Other, + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) struct MimeClass { + pub(crate) is_multipart: bool, + pub(crate) is_inline: bool, + pub(crate) is_text: bool, + pub(crate) mime_type: MimeType, +} + +impl MimeClass { + pub(crate) fn new(content_type: Option<(&str, Option<&str>)>, parent: MimeType) -> Self { + let (is_multipart, is_inline, is_text, mime_type) = match content_type { + Some((ctype, subtype)) => match ctype { + "multipart" => ( + true, + false, + false, + match subtype { + Some("mixed") => MimeType::MultipartMixed, + Some("alternative") => MimeType::MultipartAlternative, + Some("related") => MimeType::MultipartRelated, + Some("digest") => MimeType::MultipartDigest, + _ => MimeType::Other, + }, + ), + "text" => match subtype { + Some("plain") => (false, true, true, MimeType::TextPlain), + Some("html") => (false, true, true, MimeType::TextHtml), + _ => (false, false, true, MimeType::TextOther), + }, + "image" | "audio" | "video" => (false, true, false, MimeType::Inline), + "message" if matches!(subtype, Some("rfc822" | "global")) => { + (false, false, false, MimeType::Message) + } + _ => (false, false, false, MimeType::Other), + }, + None if parent == MimeType::MultipartDigest => (false, false, false, MimeType::Message), + None => (false, true, true, MimeType::TextPlain), + }; + MimeClass { + is_multipart, + is_inline, + is_text, + mime_type, + } + } + + pub(crate) fn as_broken_text(self) -> Self { + MimeClass { + is_multipart: false, + is_inline: false, + is_text: true, + mime_type: if self.mime_type == MimeType::TextPlain { + MimeType::TextPlain + } else { + MimeType::TextOther + }, + } + } + + pub(crate) fn is_text_body(self) -> bool { + matches!(self.mime_type, MimeType::TextPlain | MimeType::TextHtml) + } + + pub(crate) fn plain_kind(self) -> KindTag { + match self.mime_type { + _ if self.is_multipart => KindTag::Multipart, + MimeType::TextHtml => KindTag::Html, + _ if self.is_text => KindTag::Text, + _ => KindTag::Binary, + } + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Container { + pub(crate) mime_type: MimeType, + pub(crate) in_alternative: bool, + pub(crate) parts: u32, + pub(crate) html_parts: u32, + pub(crate) text_parts: u32, + pub(crate) need_html_body: bool, + pub(crate) need_text_body: bool, +} + +pub(crate) struct Leaf { + pub(crate) class: MimeClass, + pub(crate) disposition: Disposition, + pub(crate) has_part_name: bool, +} + +pub(crate) struct Classified { + pub(crate) kind: KindTag, + pub(crate) roles: u16, +} + +impl Container { + pub(crate) fn message() -> Self { + Container { + mime_type: MimeType::Message, + in_alternative: false, + parts: 0, + html_parts: 0, + text_parts: 0, + need_html_body: true, + need_text_body: true, + } + } + + pub(crate) fn multipart(&self, mime_type: MimeType, html_len: u32, text_len: u32) -> Self { + Container { + in_alternative: self.in_alternative || mime_type == MimeType::MultipartAlternative, + mime_type, + parts: 0, + html_parts: html_len, + text_parts: text_len, + need_html_body: self.need_html_body, + need_text_body: self.need_text_body, + } + } + + fn is_first(&self) -> bool { + self.parts == 1 + } + + fn renders_inline(&self, disposition: Disposition) -> bool { + match disposition { + Disposition::Inline => true, + Disposition::None => self.mime_type == MimeType::MultipartRelated && !self.is_first(), + Disposition::Attachment | Disposition::Other => false, + } + } + + fn inline_role(&self, disposition: Disposition) -> u16 { + if self.renders_inline(disposition) { + role::INLINE + } else { + 0 + } + } + + pub(crate) fn message_roles(&self, disposition: Disposition) -> u16 { + role::ATTACHMENT | self.inline_role(disposition) + } + + pub(crate) fn classify(&mut self, leaf: &Leaf) -> Classified { + let lists = self.rfc8621_lists(leaf); + let inline = self.inline_role(leaf.disposition); + let kind = match leaf.class.mime_type { + MimeType::TextHtml if leaf.class.is_text => KindTag::Html, + _ if leaf.class.is_text => KindTag::Text, + _ if inline != 0 => KindTag::InlineBinary, + _ => KindTag::Binary, + }; + Classified { + kind, + roles: lists | inline, + } + } + + fn rfc8621_lists(&mut self, leaf: &Leaf) -> u16 { + let mime_type = leaf.class.mime_type; + let is_media = mime_type == MimeType::Inline; + let is_inline = leaf.class.is_inline + && leaf.disposition != Disposition::Attachment + && (self.is_first() + || self.mime_type != MimeType::MultipartRelated + && (is_media || !leaf.has_part_name)); + if !is_inline { + return role::ATTACHMENT; + } + if self.mime_type == MimeType::MultipartAlternative { + return match mime_type { + MimeType::TextPlain => list_roles(self.need_text_body, false, false), + MimeType::TextHtml => list_roles(false, self.need_html_body, false), + _ => role::ATTACHMENT, + }; + } + if self.in_alternative { + match mime_type { + MimeType::TextPlain => self.need_html_body = false, + MimeType::TextHtml => self.need_text_body = false, + _ => (), + } + } + list_roles( + self.need_text_body, + self.need_html_body, + is_media && !(self.need_text_body && self.need_html_body), + ) + } + + pub(crate) fn needs_alternative_fixup(&self) -> bool { + self.mime_type == MimeType::MultipartAlternative + && self.need_html_body + && self.need_text_body + } +} + +fn list_roles(text_body: bool, html_body: bool, attachment: bool) -> u16 { + let mut roles = 0; + if text_body { + roles |= role::IN_TEXT_BODY; + } + if html_body { + roles |= role::IN_HTML_BODY; + } + if attachment { + roles |= role::ATTACHMENT; + } + roles +} diff --git a/src/parser/delimiter.rs b/src/parser/delimiter.rs new file mode 100644 index 0000000..a2874f6 --- /dev/null +++ b/src/parser/delimiter.rs @@ -0,0 +1,156 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use memchr::{memchr, memmem}; + +const MAX_NEEDLE: usize = 128; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Delimiter { + pub(crate) frame: usize, + pub(crate) line: usize, + pub(crate) next: usize, + pub(crate) is_close: bool, + pub(crate) fallback: bool, +} + +impl Delimiter { + pub(crate) fn at_line(raw: &[u8], line: usize, frame: usize, boundary: &[u8]) -> Option<Self> { + let after_dashes = raw.get(line..)?.strip_prefix(b"--")?; + let is_close = match strip_boundary(after_dashes, boundary)? { + [b'-', b'-', ..] => true, + [] | [b'\n' | b'\r' | b' ' | b'\t', ..] => false, + _ => return None, + }; + Some(Delimiter { + frame, + line, + next: line_after(raw, line + 2 + boundary.len()), + is_close, + fallback: false, + }) + } + + pub(crate) fn mid_line( + raw: &[u8], + from: usize, + limit: usize, + frame: usize, + boundary: &[u8], + ) -> Option<Self> { + let hay = raw.get(from..limit)?; + let found = memmem::find_iter(hay, boundary) + .find(|&pos| hay.get(..pos).is_some_and(|before| before.ends_with(b"--")))?; + let line = from + found - 2; + let after = line + 2 + boundary.len(); + Some(Delimiter { + frame, + line, + next: line_after(raw, after), + is_close: raw.get(after..).is_some_and(|rest| rest.starts_with(b"--")), + fallback: true, + }) + } + + pub(crate) fn content_end(&self, raw: &[u8], floor: usize) -> usize { + let before = raw.get(floor..self.line).unwrap_or_default(); + let trimmed = before + .strip_suffix(b"\n") + .map_or(before, |line| line.strip_suffix(b"\r").unwrap_or(line)); + floor + trimmed.len() + } +} + +pub(crate) enum Dashed { + At(usize), + Absent, + Unknown, +} + +pub(crate) fn dashed_boundary(raw: &[u8], from: usize, boundary: &[u8]) -> Dashed { + let mut buffer = [0u8; MAX_NEEDLE]; + let Some(needle) = buffer.get_mut(..boundary.len() + 2) else { + return Dashed::Unknown; + }; + let (dashes, name) = needle.split_at_mut(2); + dashes.copy_from_slice(b"--"); + name.copy_from_slice(boundary); + match raw.get(from..).and_then(|hay| memmem::find(hay, needle)) { + Some(pos) => Dashed::At(from + pos), + None => Dashed::Absent, + } +} + +fn strip_boundary<'a>(line: &'a [u8], boundary: &[u8]) -> Option<&'a [u8]> { + if let (Some(head), Some(expected)) = (line.first_chunk::<8>(), boundary.first_chunk::<8>()) + && head != expected + { + return None; + } + line.strip_prefix(boundary) +} + +fn line_after(raw: &[u8], from: usize) -> usize { + raw.get(from..) + .and_then(|tail| memchr(b'\n', tail)) + .map_or(raw.len(), |pos| from + pos + 1) +} + +#[cfg(test)] +mod tests { + use super::{Dashed, Delimiter, MAX_NEEDLE, dashed_boundary}; + + #[test] + fn delimiter_rule() { + let raw = b"x\n--BND\r\n--BND--\n--BNDX\n--BND \t\n--BND"; + let at = |line| Delimiter::at_line(raw, line, 0, b"BND"); + let open = at(2).expect("open delimiter"); + assert!(!open.is_close && open.next == 9); + assert!(at(9).is_some_and(|d| d.is_close)); + assert!(at(17).is_none()); + assert!(at(24).is_some_and(|d| !d.is_close)); + assert!(at(32).is_some_and(|d| !d.is_close && d.next == raw.len())); + assert!(at(0).is_none()); + } + + #[test] + fn mid_line_fallback() { + let raw = b"text invalid--1-- tail\nnext"; + let found = Delimiter::mid_line(raw, 0, raw.len(), 3, b"1").expect("found"); + assert_eq!(found.line, 12); + assert!(found.is_close && found.fallback); + assert_eq!(found.next, 23); + assert_eq!(found.content_end(raw, 0), 12); + assert!(Delimiter::mid_line(raw, 0, 12, 3, b"1").is_none()); + } + + #[test] + fn dashed_boundary_finds_the_leftmost_occurrence() { + let found = |raw: &[u8], from, boundary: &[u8]| match dashed_boundary(raw, from, boundary) { + Dashed::At(line) => Some(line), + Dashed::Absent => None, + Dashed::Unknown => Some(usize::MAX), + }; + assert_eq!( + found(b"\n--------------related\n", 0, b"----------"), + Some(1) + ); + assert_eq!(found(b"x--b\n--b--", 0, b"b"), Some(1)); + assert_eq!(found(b"x--b\n--b--", 2, b"b"), Some(5)); + assert_eq!(found(b"x--b", 3, b"b"), None); + assert_eq!(found(b"boundary=b\n", 0, b"b"), None); + let long = [b'a'; MAX_NEEDLE]; + assert_eq!(found(b"--aaaa", 0, &long), Some(usize::MAX)); + } + + #[test] + fn content_end_trims_one_line_break() { + let raw = b"body\r\n\r\n--b"; + let delimiter = Delimiter::at_line(raw, 8, 0, b"b").expect("valid"); + assert_eq!(delimiter.content_end(raw, 0), 6); + assert_eq!(delimiter.content_end(raw, 8), 8); + } +} diff --git a/src/parser/header_block.rs b/src/parser/header_block.rs new file mode 100644 index 0000000..f5c2ca0 --- /dev/null +++ b/src/parser/header_block.rs @@ -0,0 +1,424 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{builder::Builder, delimiter::Delimiter}; +use crate::{ + Encoding, HeaderForm, + fields::{self, FieldCtx}, + header_name::{self, HeaderId}, + scan::swar::{self, WORD}, + store::{HeaderEntry, NONE, OTHER_NAME, Str, Value}, +}; +use memchr::memchr2; +use std::ops::Range; + +const KEY_LEN: usize = 64; +const FIRST_NON_BLANK: u8 = 0x21; +const CONTENT_TYPE: u16 = HeaderId::ContentType as u16; +const CONTENT_DISPOSITION: u16 = HeaderId::ContentDisposition as u16; +const CONTENT_TRANSFER_ENCODING: u16 = HeaderId::ContentTransferEncoding as u16; + +#[derive(Debug, Clone, Copy)] +pub(super) struct Mime { + pub(super) content_type: u32, + pub(super) disposition: u32, + pub(super) encoding: Encoding, +} + +impl Default for Mime { + fn default() -> Self { + Mime { + content_type: NONE, + disposition: NONE, + encoding: Encoding::None, + } + } +} + +#[derive(Debug, Clone, Copy)] +enum Terminator { + Blank, + Delimiter(Delimiter), + Eof, +} + +#[derive(Debug, Clone, Copy)] +pub(super) struct Block { + pub(super) body: usize, + terminator: Terminator, + pub(super) mime: Mime, +} + +impl Block { + pub(super) fn delimiter(&self) -> Option<Delimiter> { + match self.terminator { + Terminator::Delimiter(delimiter) => Some(delimiter), + Terminator::Blank | Terminator::Eof => None, + } + } + + pub(super) fn reaches_eof(&self) -> bool { + matches!(self.terminator, Terminator::Eof) + } + + pub(super) fn has_blank_line(&self) -> bool { + matches!(self.terminator, Terminator::Blank) + } +} + +fn is_line_space(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | b'\r' | b'\x0c') +} + +struct FieldName { + name: Range<usize>, + colon: usize, + id: Option<u16>, +} + +fn field_name(field: &[u8]) -> Result<FieldName, usize> { + match simple_name(field) { + Some(name) => Ok(name), + None => { + let (name, colon) = split_name(field)?; + Ok(FieldName { + id: header_name::lookup(field.get(name.clone()).unwrap_or_default()), + name, + colon, + }) + } + } +} + +fn simple_name(field: &[u8]) -> Option<FieldName> { + let mut key = [0u8; KEY_LEN]; + for (index, (bytes, out)) in field.chunks(WORD).zip(key.chunks_mut(WORD)).enumerate() { + let word = swar::load(bytes); + out.copy_from_slice(&swar::ascii_lowercase(word).to_le_bytes()); + let stops = swar::equal_bytes(word, b':') | swar::bytes_below(word, FIRST_NON_BLANK); + if stops == 0 { + continue; + } + let colon = index * WORD + swar::first_byte(stops); + return (colon > 0 && field.get(colon) == Some(&b':')).then(|| FieldName { + name: 0..colon, + colon, + id: key.get(..colon).and_then(header_name::lookup_lowercase), + }); + } + None +} + +fn split_name(field: &[u8]) -> Result<(Range<usize>, usize), usize> { + let lead = field.iter().take_while(|&&byte| byte == b':').count(); + let rest = field.get(lead..).unwrap_or_default(); + match memchr2(b':', b'\n', rest) { + Some(colon) if rest.get(colon) == Some(&b':') => { + let name = field.get(..lead + colon).unwrap_or_default(); + Ok((0..header_name::trim_blank_end(name).len(), lead + colon)) + } + Some(newline) => Err(lead + newline + 1), + None => Err(field.len()), + } +} + +enum Fold { + Field(usize, FieldName), + End(usize, Terminator), + Continue, +} + +#[inline(never)] +fn folded_field(src: &[u8], mut line: usize, field_end: usize) -> Fold { + while line < field_end { + let rest = src.get(line..field_end).unwrap_or_default(); + let skip = rest.iter().take_while(|&&byte| is_line_space(byte)).count(); + match rest.get(skip) { + None if field_end == src.len() => return Fold::End(src.len(), Terminator::Eof), + None => return Fold::Continue, + Some(b'\n') => return Fold::End(line + skip + 1, Terminator::Blank), + Some(_) => {} + } + let field_start = line + skip; + match field_name(src.get(field_start..field_end).unwrap_or_default()) { + Ok(name) => return Fold::Field(field_start, name), + Err(next_line) => line = field_start + next_line, + } + } + Fold::Continue +} + +fn declared_encoding(value: &[u8]) -> Encoding { + let token = value + .split(|&byte| byte == b'(') + .next() + .unwrap_or_default() + .trim_ascii(); + if token.eq_ignore_ascii_case(b"base64") { + Encoding::Base64 + } else if token.eq_ignore_ascii_case(b"quoted-printable") { + Encoding::QuotedPrintable + } else { + Encoding::None + } +} + +impl Builder<'_, '_> { + pub(super) fn header_block(&mut self, src: &[u8], offset: usize) -> Block { + let mut mime = Mime::default(); + let mut line = offset; + loop { + let rest = src.get(line..).unwrap_or_default(); + if rest.is_empty() { + return Block { + body: src.len(), + terminator: Terminator::Eof, + mime, + }; + } + if self.has_open_boundaries() + && rest.starts_with(b"--") + && let Some(delimiter) = self.delimiter_at(src, line) + { + return Block { + body: delimiter.line, + terminator: Terminator::Delimiter(delimiter), + mime, + }; + } + let skip = rest.iter().take_while(|&&byte| is_line_space(byte)).count(); + match rest.get(skip) { + None => { + return Block { + body: src.len(), + terminator: Terminator::Eof, + mime, + }; + } + Some(b'\n') => { + return Block { + body: line + skip + 1, + terminator: Terminator::Blank, + mime, + }; + } + Some(_) => {} + } + let field_start = line + skip; + let field_end = self + .kernel + .field_end(src, field_start) + .map_or(src.len(), |newline| newline + 1); + let field = src.get(field_start..field_end).unwrap_or_default(); + let (field_start, name) = match field_name(field) { + Ok(name) => (field_start, name), + Err(next_line) => match folded_field(src, field_start + next_line, field_end) { + Fold::Field(start, name) => (start, name), + Fold::End(body, terminator) => { + return Block { + body, + terminator, + mime, + }; + } + Fold::Continue => { + line = field_end; + continue; + } + }, + }; + self.push_header( + src, + &name, + field_start, + field_start + name.colon + 1..field_end, + &mut mime, + ); + line = field_end; + } + } + + fn push_header( + &mut self, + src: &[u8], + name: &FieldName, + field_start: usize, + value: Range<usize>, + mime: &mut Mime, + ) { + let id = name.id; + let name_bytes = src + .get(field_start + name.name.start..field_start + name.name.end) + .unwrap_or_default(); + let form = match id { + Some(id) => self.conf.known_form(id), + None => self.conf.other_form(name_bytes), + }; + let other_name = match id { + Some(_) => NONE, + None => { + let text = match Str::borrow( + src, + field_start + name.name.start..field_start + name.name.end, + ) { + Some(text) => text, + None => Str::push_with(&mut self.data.strings, |pool| { + fields::push_utf8_lossy(pool, name_bytes) + }), + }; + self.data.push_text_item(text) + } + }; + let parsed = match form { + HeaderForm::Ignore => Value::Empty, + form => fields::parse_value( + form, + &mut FieldCtx::with_kernel(src, self.data, self.kernel), + value.clone(), + ), + }; + self.data.headers.push(HeaderEntry { + offset_field: field_start as u32, + offset_start: value.start as u32, + offset_end: value.end as u32, + value: parsed, + name: id.unwrap_or(OTHER_NAME), + other_name, + }); + let content_type = match parsed { + Value::ContentType(index) => index, + _ => NONE, + }; + match id { + Some(CONTENT_TYPE) => mime.content_type = content_type, + Some(CONTENT_DISPOSITION) => mime.disposition = content_type, + Some(CONTENT_TRANSFER_ENCODING) => { + mime.encoding = declared_encoding(src.get(value).unwrap_or_default()); + } + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::{declared_encoding, field_name, split_name}; + use crate::{Encoding, header_name, scan::tests::Rng}; + use std::ops::Range; + + type Slow = Result<(Range<usize>, usize, Option<u16>), usize>; + + fn slow(field: &[u8]) -> Slow { + let (name, colon) = split_name(field)?; + let bytes = field.get(name.clone()).unwrap_or_default(); + Ok((name, colon, header_name::lookup(bytes))) + } + + fn fast(field: &[u8]) -> Slow { + field_name(field).map(|name| (name.name, name.colon, name.id)) + } + + #[test] + fn field_names_match_split_name() { + let long = "X-".repeat(40); + let mut names: Vec<Vec<u8>> = [ + &b"Subject"[..], + b"subject", + b"SUBJECT", + b"Content-Transfer-Encoding", + b"content-type", + b"X-Mailer", + b"X-MS-Exchange-Organization-AuthAs", + b"x", + b"Sub ject", + b"Subject ", + b"Subject\t", + b":Subject", + b"::", + b"caf\xc3\xa9", + b"X-\xff", + b"X-\x01-Y", + b"X-\x7f", + b"Received", + b"A@[]{}~", + b"", + ] + .iter() + .map(|name| name.to_vec()) + .collect(); + names.extend((55..=70).map(|len| long.as_bytes().get(..len).unwrap_or_default().to_vec())); + names.extend((55..=70).map(|len| { + let mut name = b"Subject".to_vec(); + name.resize(len, b'x'); + name + })); + for name in &names { + for tail in [ + &b": value\r\n"[..], + b":value\n", + b" : v\n", + b"\t: v\n", + b":", + b"", + b"\n next: x\n", + b"\r\n", + ] { + let mut field = name.clone(); + field.extend_from_slice(tail); + for end in 0..=field.len() { + let prefix = field.get(..end).unwrap_or_default(); + assert_eq!( + fast(prefix), + slow(prefix), + "{:?}", + String::from_utf8_lossy(prefix) + ); + } + } + } + let alphabet = b"aZ-:: \t\r\n\x00\x80\xc3\xa9!~"; + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + for _ in 0..50_000 { + let len = rng.below(80); + let field: Vec<u8> = (0..len) + .map(|_| { + alphabet + .get(rng.below(alphabet.len())) + .copied() + .unwrap_or(b'a') + }) + .collect(); + assert_eq!(fast(&field), slow(&field), "{field:?}"); + } + } + + #[test] + fn names() { + assert_eq!(split_name(b"Subject: x\n"), Ok((0..7, 7))); + assert_eq!(split_name(b"subject : x\n"), Ok((0..7, 10))); + assert_eq!(split_name(b"Subject\t \t: x\n"), Ok((0..7, 10))); + assert_eq!(split_name(b"From\r: x\n"), Ok((0..5, 5))); + assert_eq!(split_name(b":Weird: v"), Ok((0..6, 6))); + assert_eq!(split_name(b":: From: v"), Ok((0..8, 8))); + assert_eq!(split_name(b"mal formed: v"), Ok((0..10, 10))); + assert_eq!(split_name(b": only colon\n next: x\n"), Err(13)); + assert_eq!(split_name(b"no colon here"), Err(13)); + assert_eq!(split_name(b"no colon\n here: x"), Err(9)); + assert_eq!(split_name(b""), Err(0)); + } + + #[test] + fn transfer_encodings() { + assert_eq!(declared_encoding(b" base64\r\n"), Encoding::Base64); + assert_eq!(declared_encoding(b" BASE64 (comment)\n"), Encoding::Base64); + assert_eq!( + declared_encoding(b"\r\n Quoted-Printable\r\n"), + Encoding::QuotedPrintable + ); + assert_eq!(declared_encoding(b" 8bit\n"), Encoding::None); + assert_eq!(declared_encoding(b" base64;\n"), Encoding::None); + } +} diff --git a/src/parser/mod.rs b/src/parser/mod.rs new file mode 100644 index 0000000..8e78955 --- /dev/null +++ b/src/parser/mod.rs @@ -0,0 +1,310 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod builder; +mod classify; +mod delimiter; +mod header_block; + +#[cfg(test)] +mod tests; + +pub(crate) use builder::Frame; + +use crate::{ + HeaderForm, HeaderName, Message, MessageBuffers, + header_name::{FIRST_VENDOR, HeaderId, KNOWN_NAMES, OTHER_ID}, + scan::Kernel, + store::MessageData, +}; +use builder::Builder; +use std::borrow::Cow; + +const FIRST_VENDOR_ID: usize = FIRST_VENDOR as usize; +const CONTENT_TYPE: u16 = HeaderId::ContentType as u16; +const CONTENT_DISPOSITION: u16 = HeaderId::ContentDisposition as u16; +const CONTENT_TRANSFER_ENCODING: u16 = HeaderId::ContentTransferEncoding as u16; +const DEFAULT_MAX_DEPTH: u32 = 64; +const DEFAULT_MAX_PARTS: u32 = 10_000; +const DEFAULT_MAX_ENCODED_NESTING: u32 = 3; + +const TEXT: [HeaderId; 5] = [ + HeaderId::Subject, + HeaderId::Comments, + HeaderId::ContentDescription, + HeaderId::ContentLocation, + HeaderId::ContentTransferEncoding, +]; + +const ADDRESSES: [HeaderId; 18] = [ + HeaderId::From, + HeaderId::To, + HeaderId::Cc, + HeaderId::Bcc, + HeaderId::ReplyTo, + HeaderId::Sender, + HeaderId::ResentTo, + HeaderId::ResentFrom, + HeaderId::ResentBcc, + HeaderId::ResentCc, + HeaderId::ResentSender, + HeaderId::ListArchive, + HeaderId::ListHelp, + HeaderId::ListId, + HeaderId::ListOwner, + HeaderId::ListPost, + HeaderId::ListSubscribe, + HeaderId::ListUnsubscribe, +]; + +const DATES: [HeaderId; 2] = [HeaderId::Date, HeaderId::ResentDate]; + +const MESSAGE_IDS: [HeaderId; 6] = [ + HeaderId::MessageId, + HeaderId::References, + HeaderId::InReplyTo, + HeaderId::ReturnPath, + HeaderId::ContentId, + HeaderId::ResentMessageId, +]; + +const COMMA_LISTS: [HeaderId; 2] = [HeaderId::Keywords, HeaderId::ContentLanguage]; + +const CONTENT_TYPES: [HeaderId; 2] = [HeaderId::ContentType, HeaderId::ContentDisposition]; + +const fn assign( + mut forms: [HeaderForm; KNOWN_NAMES], + ids: &[HeaderId], + form: HeaderForm, +) -> [HeaderForm; KNOWN_NAMES] { + let mut index = 0; + while index < ids.len() { + forms[ids[index] as usize] = form; + index += 1; + } + forms +} + +const DEFAULT_FORMS: [HeaderForm; KNOWN_NAMES] = { + let forms = [HeaderForm::Raw; KNOWN_NAMES]; + let forms = assign(forms, &TEXT, HeaderForm::Text); + let forms = assign(forms, &ADDRESSES, HeaderForm::Addresses); + let forms = assign(forms, &DATES, HeaderForm::Date); + let forms = assign(forms, &MESSAGE_IDS, HeaderForm::MessageIds); + let forms = assign(forms, &COMMA_LISTS, HeaderForm::CommaList); + let forms = assign(forms, &[HeaderId::Received], HeaderForm::Received); + assign(forms, &CONTENT_TYPES, HeaderForm::ContentType) +}; + +/// RFC 5322 message parser and its configuration. +/// +/// Build a parser once and reuse it; it is `Send + Sync`. The default +/// configuration parses the header fields that 0.11 parsed into structured +/// values the same way and keeps every other field raw. +/// +/// ``` +/// use mail_parser::{HeaderForm, HeaderName, MessageParser}; +/// +/// let parser = MessageParser::new() +/// .header(HeaderName::Received, HeaderForm::Raw) +/// .header("X-Sender", HeaderForm::Addresses) +/// .max_parts(1_000); +/// let message = parser +/// .parse(b"X-Sender: <sender@example.com>\r\n\r\nbody") +/// .expect("message"); +/// let sender = message.headers().value("x-sender").and_then(|value| value.as_address()); +/// let address = sender.and_then(|list| list.first()).and_then(|mailbox| mailbox.address()); +/// assert_eq!(address, Some("sender@example.com")); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MessageParser { + forms: [HeaderForm; KNOWN_NAMES], + configured_vendor: Vec<u16>, + custom: Vec<(Box<str>, HeaderForm)>, + unknown: HeaderForm, + max_depth: u32, + max_parts: u32, + max_encoded_nesting: u32, + kernel: Kernel, +} + +impl Default for MessageParser { + fn default() -> Self { + MessageParser::new() + } +} + +impl MessageParser { + /// A parser with the default header table: every header 0.11 parsed + /// into a structured value is parsed the same way, every other header is + /// kept raw. Limits: nesting depth 64, 10,000 parts, 3 levels of + /// transfer-encoded nested messages. + pub fn new() -> Self { + MessageParser { + forms: DEFAULT_FORMS, + configured_vendor: Vec::new(), + custom: Vec::new(), + unknown: HeaderForm::Raw, + max_depth: DEFAULT_MAX_DEPTH, + max_parts: DEFAULT_MAX_PARTS, + max_encoded_nesting: DEFAULT_MAX_ENCODED_NESTING, + kernel: Kernel::best(), + } + } + + /// Parses the header `name` as `form`, in place of its default form. + /// Content-Type, Content-Disposition and Content-Transfer-Encoding + /// always keep their MIME form. Names compare ASCII case-insensitively, + /// and a [`HeaderName::Other`] spelled like a known name configures that + /// name; any other name is added to a short list checked for every + /// unknown name. + pub fn header(mut self, name: impl Into<HeaderName<'static>>, form: HeaderForm) -> Self { + let name = name.into(); + match (name.resolved_id(), name) { + (CONTENT_TYPE | CONTENT_DISPOSITION | CONTENT_TRANSFER_ENCODING, _) => {} + (OTHER_ID, HeaderName::Other(name)) if name.is_empty() => {} + (OTHER_ID, HeaderName::Other(name)) => { + match self + .custom + .iter_mut() + .find(|(custom, _)| custom.eq_ignore_ascii_case(&name)) + { + Some((_, custom_form)) => *custom_form = form, + None => self.custom.push((name.into_owned().into_boxed_str(), form)), + } + } + (id, _) => { + if let Some(slot) = self.forms.get_mut(usize::from(id)) { + *slot = form; + if id >= FIRST_VENDOR && !self.configured_vendor.contains(&id) { + self.configured_vendor.push(id); + } + } + } + } + self + } + + /// The form used for header names that are neither known nor + /// registered with [`MessageParser::header`]; [`HeaderForm::Raw`] by + /// default. + /// + /// It also applies to the vendor names that are known since 1.0 but were + /// unknown to 0.11 (from [`HeaderName::XOriginalTo`] on: X-Mailer, + /// User-Agent, X-Priority, the X-MS-Exchange, X-Google and X-GitHub + /// fields, ...), except those registered with `header`, whatever the + /// order of the calls. + pub fn unknown_headers(mut self, form: HeaderForm) -> Self { + self.unknown = form; + let vendor_forms = self.forms.get_mut(FIRST_VENDOR_ID..).unwrap_or_default(); + for (slot, id) in vendor_forms.iter_mut().zip(FIRST_VENDOR..) { + if !self.configured_vendor.contains(&id) { + *slot = form; + } + } + self + } + + /// Maximum number of nested containers (multiparts and messages), the + /// root message included: with the default of 64, a part can be nested + /// in at most 63 containers below the root message. + pub fn max_depth(mut self, depth: usize) -> Self { + self.max_depth = u32::try_from(depth).unwrap_or(u32::MAX).max(1); + self + } + + /// Maximum number of parts; the content past the limit stays unparsed + /// in the part flagged [`PartFlags::LIMIT_REACHED`](crate::PartFlags::LIMIT_REACHED). + pub fn max_parts(mut self, parts: usize) -> Self { + self.max_parts = u32::try_from(parts).unwrap_or(u32::MAX).max(1); + self + } + + /// Maximum nesting of transfer-encoded `message/rfc822` parts that are + /// decoded and parsed; 0 leaves them as binary parts. + pub fn max_encoded_nesting(mut self, levels: usize) -> Self { + self.max_encoded_nesting = u32::try_from(levels).unwrap_or(u32::MAX); + self + } + + #[cfg(test)] + pub(crate) fn kernel(mut self, kernel: Kernel) -> Self { + self.kernel = kernel; + self + } + + pub(crate) fn known_form(&self, id: u16) -> HeaderForm { + self.forms.get(id as usize).copied().unwrap_or(self.unknown) + } + + pub(crate) fn other_form(&self, name: &[u8]) -> HeaderForm { + self.custom + .iter() + .find(|(custom, _)| custom.as_bytes().eq_ignore_ascii_case(name)) + .map_or(self.unknown, |(_, form)| *form) + } + + /// Parses a message that borrows `raw`. Returns `None` when the input + /// has no header and no blank line, or is 4 GiB or larger. + pub fn parse<'x>(&self, raw: &'x (impl AsRef<[u8]> + ?Sized)) -> Option<Message<'x>> { + let mut message = Message::new(Cow::Borrowed(raw.as_ref()), MessageData::default()); + self.fill(&mut message, false).then_some(message) + } + + /// Parses a message and takes ownership of its bytes, giving a + /// `Message<'static>` that can be moved to another task. + pub fn parse_owned(&self, raw: Vec<u8>) -> Option<Message<'static>> { + let mut message = Message::new(Cow::Owned(raw), MessageData::default()); + self.fill(&mut message, false).then_some(message) + } + + /// Parses only the root header block, for callers that do not need the + /// MIME structure (DKIM verification, header indexing). + /// + /// The message has a single part, the root part, which covers the whole + /// body and keeps the kind its Content-Type gives (a multipart root has + /// no children). No part is in a body list or in the attachments: + /// [`crate::MessageRef::has_attachments`] is false, and a root that is + /// not a multipart is reported by [`crate::MessageRef::other_parts`]. + pub fn parse_headers<'x>(&self, raw: &'x (impl AsRef<[u8]> + ?Sized)) -> Option<Message<'x>> { + let mut message = Message::new(Cow::Borrowed(raw.as_ref()), MessageData::default()); + self.fill(&mut message, true).then_some(message) + } + + /// Parses a message into the storage held by `buffers`, which a + /// previous message gave back with [`Message::into_buffers`]; once the + /// storage fits the messages, parsing allocates nothing. See + /// [`MessageBuffers`] for a loop. + /// + /// The message takes the storage out of `buffers`, which stay usable: + /// when the input does not parse, the storage is dropped and the next + /// parse allocates. + pub fn parse_with<'x>( + &self, + raw: &'x (impl AsRef<[u8]> + ?Sized), + buffers: &mut MessageBuffers, + ) -> Option<Message<'x>> { + let mut message = Message::new( + Cow::Borrowed(raw.as_ref()), + std::mem::take(&mut buffers.data), + ); + message.split_mut().1.clear(); + self.fill(&mut message, false).then_some(message) + } + + fn fill(&self, message: &mut Message<'_>, headers_only: bool) -> bool { + let (raw, data) = message.split_mut(); + u32::try_from(raw.len()).is_ok() && Builder::new(self, data, headers_only).run(raw) + } + + pub(crate) fn scan_kernel(&self) -> Kernel { + self.kernel + } + + pub(crate) fn limits(&self) -> (u32, u32, u32) { + (self.max_depth, self.max_parts, self.max_encoded_nesting) + } +} diff --git a/src/parser/tests.rs b/src/parser/tests.rs new file mode 100644 index 0000000..bdd78ca --- /dev/null +++ b/src/parser/tests.rs @@ -0,0 +1,878 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use crate::{ + Address, DecodeProblems, HeaderForm, HeaderName, HeaderValue, Message, MessageBuffers, + MessageParser, PartFlags, PartKind, Source, + scan::{ + Kernel, + tests::{fixture_files, with_crlf, with_lf}, + }, +}; +use encodify::base64; +use std::fmt::Write; + +fn parse(raw: &[u8]) -> Message<'_> { + MessageParser::new().parse(raw).expect("message parses") +} + +fn value_text(value: HeaderValue<'_>) -> String { + match value { + HeaderValue::Empty => "empty".to_string(), + HeaderValue::Text(text) => format!("text {text:?}"), + HeaderValue::TextList(list) => format!("list {:?}", list.iter().collect::<Vec<_>>()), + HeaderValue::Address(list) => list + .iter() + .map(|address| match address { + Address::Mailbox(mailbox) => { + format!("<{:?} {:?}>", mailbox.name(), mailbox.address()) + } + Address::Group(group) => format!("group {:?} {}", group.name(), group.len()), + }) + .collect(), + HeaderValue::DateTime(date) => date.to_rfc3339(), + HeaderValue::ContentType(content_type) => format!( + "ct {} {:?} {:?}", + content_type.ctype(), + content_type.subtype(), + content_type.attributes().collect::<Vec<_>>() + ), + HeaderValue::Received(received) => format!("received {:?}", received.from()), + } +} + +pub(crate) fn dump(message: &Message<'_>) -> String { + let mut out = String::new(); + for nested in message.messages() { + let ids = |parts: &mut dyn Iterator<Item = crate::MessagePart<'_>>| { + parts.map(|part| part.id()).collect::<Vec<_>>() + }; + let _ = writeln!( + out, + "message {} root {} container {:?} source {:?} text {:?} html {:?} attachments {:?}", + nested.id(), + nested.root_part().id(), + nested.container().map(|part| part.id()), + nested.source(), + ids(&mut nested.text_body()), + ids(&mut nested.html_body()), + ids(&mut nested.attachments()), + ); + } + for part in message.parts() { + let _ = writeln!( + out, + "part {} message {} parent {:?} kind {:?} children {:?} encoding {:?} flags {:?} roles {} {} {} {} offsets {} {} {}", + part.id(), + part.message().id(), + part.parent().map(|parent| parent.id()), + std::mem::discriminant(&part.kind()), + part.children().map(|child| child.id()).collect::<Vec<_>>(), + part.encoding(), + part.flags().names().collect::<Vec<_>>(), + part.in_text_body(), + part.in_html_body(), + part.is_attachment(), + part.is_inline(), + part.offset_header(), + part.offset_body(), + part.offset_end(), + ); + for header in part.headers().iter() { + let _ = writeln!( + out, + " {:?} {:?} {} {} {} {}", + header.name().as_str(), + header.raw_name(), + value_text(header.value()), + header.offset_field(), + header.offset_start(), + header.offset_end() + ); + } + let _ = writeln!(out, " body {:?}", part.decoded()); + if let Some(text) = part.text() { + let _ = writeln!(out, " text {text:?}"); + } + } + out +} + +fn text_of(message: &Message<'_>, part: u32) -> String { + message + .part(part) + .and_then(|part| part.text()) + .map(|text| text.into_owned()) + .unwrap_or_default() +} + +#[test] +fn single_part_offsets() { + let raw = b"From: a@b\nSubject: Hi\n\nbody\n"; + let message = parse(raw); + assert_eq!(message.parts().len(), 1); + let root = message.root_part(); + assert_eq!( + (root.offset_header(), root.offset_body(), root.offset_end()), + (0, 23, raw.len() as u32) + ); + let headers: Vec<_> = root + .headers() + .iter() + .map(|h| (h.name(), h.offset_field(), h.offset_start(), h.offset_end())) + .collect(); + assert_eq!( + headers, + [ + (HeaderName::From, 0, 5, 10), + (HeaderName::Subject, 10, 18, 22) + ] + ); + assert_eq!(root.raw_body(), b"body\n"); + assert_eq!(message.subject(), Some("Hi")); + assert!(root.flags().is_empty()); + assert_eq!(message.text_body().map(|p| p.id()).collect::<Vec<_>>(), [0]); + assert_eq!(message.html_body().map(|p| p.id()).collect::<Vec<_>>(), [0]); + assert_eq!(message.attachments().len(), 0); + assert_eq!(message.body_text(0).as_deref(), Some("body\n")); + assert_eq!(message.root().source(), Source::Raw); +} + +#[test] +fn header_block_edge_cases() { + let message = parse(b"Sub ject: x\n:Weird: v\nfoo bar\n baz: qux\nX-Custom : y\n\nbody"); + let names: Vec<_> = message + .headers() + .iter() + .map(|h| (h.name().as_str().to_string(), h.raw_name().to_string())) + .collect(); + assert_eq!( + names, + [ + ("Sub ject".to_string(), "Sub ject".to_string()), + (":Weird".to_string(), ":Weird".to_string()), + ("baz".to_string(), "baz".to_string()), + ("X-Custom".to_string(), "X-Custom".to_string()), + ] + ); + assert_eq!( + message.headers().get("x-custom").map(|h| h.raw_value()), + Some(&b" y\n"[..]) + ); + assert_eq!( + message.headers().get(":weird").map(|h| h.offset_field()), + Some(12) + ); + assert_eq!(message.root_part().raw_body(), b"body"); + + let message = parse(b" \r\n body"); + assert!(message.headers().is_empty()); + assert_eq!(message.root_part().raw_body(), b" body"); + + let message = parse(b"Subject: last"); + assert_eq!(message.subject(), Some("last")); + assert!( + message + .root_part() + .flags() + .contains(PartFlags::NO_BLANK_LINE) + ); + + let message = parse(b"Subject: a\r\n \r\nFrom: x\r\n\r\nbody"); + assert_eq!(message.headers().len(), 2); + assert_eq!(message.root_part().raw_body(), b"body"); + + let message = parse(b"\n"); + assert_eq!(message.parts().len(), 1); + assert!(message.headers().is_empty()); + + assert!(MessageParser::new().parse(b"").is_none()); + assert!(MessageParser::new().parse(b"hello").is_none()); + assert!( + MessageParser::new() + .parse(b"hello world\nfoo bar\n") + .is_none() + ); +} + +const MULTIPART: &[u8] = b"Content-Type: multipart/mixed; boundary=\"b\"\n\n\ +preamble\n--b\nContent-Type: text/plain\n\nhello\n--b\nContent-Type: text/html\n\n<p>x</p>\n\ +--b--\nepilogue\n"; + +#[test] +fn multipart_structure() { + for raw in [MULTIPART.to_vec(), with_crlf(MULTIPART)] { + let message = parse(&raw); + let root = message.root_part(); + assert!(matches!(root.kind(), PartKind::Multipart)); + assert_eq!(root.children().map(|p| p.id()).collect::<Vec<_>>(), [1, 2]); + assert_eq!(root.offset_end(), raw.len() as u32); + assert_eq!(root.boundary(), Some("b")); + assert_eq!(text_of(&message, 1), "hello"); + assert_eq!(text_of(&message, 2), "<p>x</p>"); + let second = message.part(2).expect("part"); + assert!(matches!(second.kind(), PartKind::Html)); + assert_eq!(second.delimiter(), Some("b")); + assert_eq!(second.parent().map(|p| p.id()), Some(0)); + assert!(message.parts().all(|part| part.flags().is_empty())); + assert_eq!(message.part_by_boundary("b").map(|p| p.id()), Some(0)); + assert_eq!( + second.raw(), + if raw.contains(&b'\r') { + &b"Content-Type: text/html\r\n\r\n<p>x</p>"[..] + } else { + &b"Content-Type: text/html\n\n<p>x</p>"[..] + } + ); + } +} + +#[test] +fn delimiter_rule() { + let raw = b"Content-Type: multipart/mixed; boundary=\"BND\"\n\n--BND\nContent-Type: text/plain\n\n\ +visit --BND for details\n--BNDX not a delimiter\n--BND \t\nContent-Type: text/plain\n\nsecond\n--BND--"; + let message = parse(raw); + assert_eq!( + text_of(&message, 1), + "visit --BND for details\n--BNDX not a delimiter" + ); + assert_eq!(text_of(&message, 2), "second"); + assert!(message.parts().all(|part| part.flags().is_empty())); +} + +#[test] +fn fallback_and_missing_delimiters() { + let raw = b"Content-Type: multipart/mixed; boundary=\"1\"\n\n--1\nContent-Type: text/plain\n\ntext invalid--1--\n"; + let message = parse(raw); + let part = message.part(1).expect("part"); + assert_eq!(text_of(&message, 1), "text invalid"); + assert!(part.flags().contains(PartFlags::FALLBACK_DELIMITER)); + assert!(message.root_part().flags().is_empty()); + + let raw = b"Content-Type: multipart/mixed; boundary=\"b\"\n\n--b\nContent-Type: text/plain\n\nno end\n"; + let message = parse(raw); + let part = message.part(1).expect("part"); + assert!(part.flags().contains(PartFlags::MISSING_DELIMITER)); + assert_eq!(text_of(&message, 1), "no end\n"); + assert!( + message + .root_part() + .flags() + .contains(PartFlags::UNTERMINATED) + ); + + let raw = b"Content-Type: multipart/mixed; boundary=\"b\"\n\n--b\nContent-Type: text/plain\n--b\nContent-Type: text/plain\n\nok\n--b--\n"; + let message = parse(raw); + let first = message.part(1).expect("part"); + assert!(first.flags().contains(PartFlags::NO_BLANK_LINE)); + assert_eq!(first.raw_body(), b""); + assert_eq!(text_of(&message, 2), "ok"); +} + +#[test] +fn inner_multipart_closed_by_outer_delimiter() { + let raw = b"Content-Type: multipart/mixed; boundary=\"outer\"\n\n--outer\n\ +Content-Type: multipart/alternative; boundary=\"inner\"\n\n--inner\nContent-Type: text/plain\n\na\n\ +--outer\nContent-Type: text/plain\n\nb\n--outer--\n"; + let message = parse(raw); + assert_eq!(message.parts().len(), 4); + assert!( + message + .part(1) + .expect("inner") + .flags() + .contains(PartFlags::UNTERMINATED) + ); + assert_eq!(text_of(&message, 2), "a"); + assert_eq!(text_of(&message, 3), "b"); + assert_eq!( + message.part(3).and_then(|p| p.parent()).map(|p| p.id()), + Some(0) + ); +} + +const NESTED_INLINE: &[u8] = b"Content-Type: multipart/mixed; boundary=\"outer\"\n\n--outer\n\ +Content-Type: text/plain\n\nintro\n--outer\nContent-Type: message/rfc822\n\n\ +Subject: nested\nContent-Type: text/plain\n\nnested body\n--outer--\n"; + +#[test] +fn nested_inline_message() { + for raw in [NESTED_INLINE.to_vec(), with_crlf(NESTED_INLINE)] { + let message = parse(&raw); + assert_eq!(message.messages().len(), 2); + assert_eq!(message.parts().len(), 4); + let container = message.part(2).expect("container"); + let nested = container.nested().expect("nested"); + assert_eq!(nested.subject(), Some("nested")); + assert_eq!(nested.root_part().id(), 3); + assert_eq!(nested.container().map(|p| p.id()), Some(2)); + assert_eq!(nested.source(), Source::Raw); + assert_eq!(nested.root_part().offset_header(), container.offset_body()); + assert_eq!(text_of(&message, 3), "nested body"); + assert_eq!(nested.body_text(0).as_deref(), Some("nested body")); + assert!(container.is_attachment()); + assert_eq!( + message.attachments().map(|p| p.id()).collect::<Vec<_>>(), + [2] + ); + assert_eq!( + message + .root_part() + .children() + .map(|p| p.id()) + .collect::<Vec<_>>(), + [1, 2] + ); + assert_eq!(container.offset_end(), nested.root_part().offset_end()); + } +} + +fn encoded_message(subject: &str, body: &str) -> String { + format!( + "Content-Type: multipart/mixed; boundary=\"outer\"\n\n--outer\n\ +Content-Type: message/rfc822\nContent-Transfer-Encoding: base64\n\n{}\n\ +--outer\nContent-Type: text/plain\n\nafter\n--outer--\n", + base64::MIME.encode(format!("Subject: {subject}\n\n{body}")) + ) +} + +#[test] +fn nested_encoded_message() { + let raw = encoded_message("inner", "inner body\n"); + for raw in [raw.as_bytes().to_vec(), with_crlf(raw.as_bytes())] { + let message = parse(&raw); + assert_eq!(message.messages().len(), 2); + assert_eq!(message.parts().len(), 4); + let container = message.part(1).expect("container"); + assert!(matches!(container.kind(), PartKind::Message(_))); + let nested = container.nested().expect("nested"); + assert_eq!(nested.subject(), Some("inner")); + assert_eq!(nested.source(), Source::Decoded(1)); + assert_eq!(nested.root_part().id(), 2); + assert_eq!(nested.root_part().offset_header(), 0); + assert_eq!( + nested.root_part().offset_end() as usize, + nested.source_bytes().len() + ); + assert_eq!(text_of(&message, 2), "inner body\n"); + assert_eq!(text_of(&message, 3), "after"); + assert_eq!( + message.part(3).and_then(|p| p.parent()).map(|p| p.id()), + Some(0) + ); + assert_eq!( + message + .root_part() + .children() + .map(|p| p.id()) + .collect::<Vec<_>>(), + [1, 3] + ); + assert_eq!(container.decoded().as_ref(), nested.source_bytes()); + } +} + +fn wrap_encoded(inner: &str, levels: usize) -> String { + let mut message = inner.to_string(); + for level in 0..levels { + message = format!( + "Subject: level {level}\nContent-Type: message/rfc822\nContent-Transfer-Encoding: base64\n\n{}\n", + base64::MIME.encode(&message) + ); + } + message +} + +#[test] +fn encoded_inside_encoded_and_limits() { + let raw = wrap_encoded("Subject: core\n\ncore body\n", 2); + let message = parse(raw.as_bytes()); + assert_eq!(message.messages().len(), 3); + assert_eq!(message.parts().len(), 3); + let innermost = message.messages().last().expect("innermost"); + assert_eq!(innermost.subject(), Some("core")); + assert_eq!(innermost.body_text(0).as_deref(), Some("core body\n")); + assert_eq!(innermost.source(), Source::Decoded(1)); + + let raw = wrap_encoded("Subject: core\n\ncore body\n", 4); + let message = parse(raw.as_bytes()); + assert_eq!(message.messages().len(), 4); + let last = message.parts().last().expect("part"); + assert!(matches!(last.kind(), PartKind::Binary)); + assert!(last.flags().contains(PartFlags::NESTING_LIMIT)); + + let message = MessageParser::new() + .max_encoded_nesting(1) + .parse(raw.as_bytes()) + .expect("parses"); + assert_eq!(message.messages().len(), 2); + assert!( + message + .part(1) + .expect("part") + .flags() + .contains(PartFlags::NESTING_LIMIT) + ); + + let message = MessageParser::new() + .max_encoded_nesting(0) + .parse(raw.as_bytes()) + .expect("parses"); + assert_eq!(message.messages().len(), 1); + let root = message.root_part(); + assert!(matches!(root.kind(), PartKind::Binary)); + assert!(root.flags().is_empty()); +} + +#[test] +fn empty_nested_messages() { + let raw = b"Content-Type: multipart/mixed; boundary=\"b\"\n\n--b\nContent-Type: message/rfc822\n\n--b--\n"; + let message = parse(raw); + assert_eq!(message.messages().len(), 1); + let part = message.part(1).expect("part"); + assert!(part.flags().contains(PartFlags::NO_BLANK_LINE)); + assert!(part.nested().is_none()); + + let raw = format!( + "Content-Type: message/rfc822\nContent-Transfer-Encoding: base64\n\n{}\n", + base64::MIME.encode("no headers at all") + ); + let message = parse(raw.as_bytes()); + assert_eq!(message.messages().len(), 1); + let root = message.root_part(); + assert!(matches!(root.kind(), PartKind::Binary)); + assert!(root.flags().contains(PartFlags::NO_BLANK_LINE)); + assert_eq!(root.decoded().as_ref(), b"no headers at all"); +} + +#[test] +fn depth_and_part_limits() { + let raw = b"Content-Type: multipart/mixed; boundary=\"a\"\n\n--a\n\ +Content-Type: multipart/mixed; boundary=\"b\"\n\n--b\nContent-Type: text/plain\n\ndeep\n--b--\n--a--\n"; + let message = MessageParser::new() + .max_depth(2) + .parse(raw) + .expect("parses"); + assert_eq!(message.parts().len(), 2); + let inner = message.part(1).expect("inner"); + assert!(inner.flags().contains(PartFlags::LIMIT_REACHED)); + assert!(matches!(inner.kind(), PartKind::Text)); + + let message = MessageParser::new() + .max_parts(2) + .parse(MULTIPART) + .expect("parses"); + assert_eq!(message.parts().len(), 2); + let last = message.part(1).expect("last"); + assert!(last.flags().contains(PartFlags::LIMIT_REACHED)); + assert_eq!(last.offset_end() as usize, MULTIPART.len()); + + let mut deep = String::new(); + for level in 0..200 { + deep.push_str(&format!( + "Content-Type: multipart/mixed; boundary=\"b{level}\"\n\n--b{level}\n" + )); + } + let message = parse(deep.as_bytes()); + assert!(message.parts().len() <= 64); + assert!( + message + .parts() + .any(|part| part.flags().contains(PartFlags::LIMIT_REACHED)) + ); +} + +#[test] +fn headers_only() { + let raw = MULTIPART; + let message = MessageParser::new().parse_headers(raw).expect("parses"); + let full = parse(raw); + assert_eq!(message.parts().len(), 1); + let root = message.root_part(); + assert_eq!(root.offset_body(), full.root_part().offset_body()); + assert_eq!(root.offset_end() as usize, raw.len()); + assert_eq!(message.headers().len(), full.headers().len()); + assert_eq!(message.text_body().len(), 0); +} + +#[test] +fn buffer_reuse_and_ownership() { + let parser = MessageParser::new(); + let mut buffers = MessageBuffers::new(); + for raw in [ + MULTIPART, + b"", + NESTED_INLINE, + b"Subject: x\n\nbody".as_slice(), + ] { + let Some(reused) = parser.parse_with(raw, &mut buffers) else { + assert!(parser.parse(raw).is_none()); + assert_eq!(buffers.data.headers.capacity(), 0); + continue; + }; + assert_eq!(dump(&reused), dump(&parse(raw))); + assert_eq!(buffers.data.headers.capacity(), 0); + buffers = reused.into_buffers(); + assert!(buffers.data.parts.is_empty() && buffers.data.headers.capacity() > 0); + } + let owned = parser.parse_owned(MULTIPART.to_vec()).expect("parses"); + assert_eq!(dump(&owned), dump(&parse(MULTIPART))); + let copied: Message<'static> = parse(MULTIPART).into_owned(); + assert_eq!(dump(&copied), dump(&owned)); +} + +#[test] +fn unknown_headers_apply_to_vendor_names() { + let raw = b"X-Mailer: =?utf-8?q?caf=C3=A9?=\nX-Priority: =?utf-8?q?1?=\n\ +X-Custom: =?utf-8?q?a?=\nOrganization: =?utf-8?q?o?=\nSubject: =?utf-8?q?s?=\n\nbody"; + let values = |parser: MessageParser| { + let message = parser.parse(raw).expect("parses"); + message + .headers() + .iter() + .map(|header| header.value().as_text().unwrap_or_default().to_string()) + .collect::<Vec<_>>() + }; + let raw_values = [ + "=?utf-8?q?caf=C3=A9?=", + "=?utf-8?q?1?=", + "=?utf-8?q?a?=", + "=?utf-8?q?o?=", + "s", + ]; + assert_eq!(values(MessageParser::new()), raw_values); + assert_eq!( + values(MessageParser::new().unknown_headers(HeaderForm::Text)), + ["caf\u{e9}", "1", "a", "=?utf-8?q?o?=", "s"] + ); + for parser in [ + MessageParser::new() + .header(HeaderName::XMailer, HeaderForm::Raw) + .unknown_headers(HeaderForm::Text), + MessageParser::new() + .unknown_headers(HeaderForm::Text) + .header(HeaderName::XMailer, HeaderForm::Raw), + ] { + assert_eq!( + values(parser), + ["=?utf-8?q?caf=C3=A9?=", "1", "a", "=?utf-8?q?o?=", "s"] + ); + } + assert_eq!( + values( + MessageParser::new() + .unknown_headers(HeaderForm::Text) + .unknown_headers(HeaderForm::Raw) + ), + raw_values + ); + assert_eq!( + MessageParser::new().unknown_headers(HeaderForm::Raw), + MessageParser::new() + ); +} + +#[test] +fn message_is_send_sync_and_covariant() { + fn send_sync<T: Send + Sync + Clone + Default>() {} + send_sync::<Message<'static>>(); + fn covariant<'a>(message: Message<'static>) -> Message<'a> { + message + } + let message = covariant(parse(MULTIPART).into_owned()); + assert_eq!(message.parts().len(), 3); +} + +#[test] +fn fixtures_parse_with_every_kernel() { + let files = fixture_files(); + assert!(files.len() > 100); + for file in files { + for raw in [with_lf(&file), with_crlf(&file)] { + let reference = MessageParser::new() + .kernel(Kernel::SCALAR) + .parse(&raw) + .map(|message| dump(&message)); + for kernel in Kernel::available() { + let parsed = MessageParser::new() + .kernel(kernel) + .parse(&raw) + .map(|message| dump(&message)); + assert_eq!(parsed, reference, "{} differs", kernel.name()); + } + } + } +} + +#[test] +fn truncated_inputs_never_panic() { + for file in fixture_files() { + let raw = with_crlf(&file); + for end in (0..raw.len()).step_by(7) { + if let Some(message) = MessageParser::new().parse(raw.get(..end).unwrap_or_default()) { + let _ = dump(&message); + } + } + } +} + +#[test] +fn decoding_accessors() { + let raw = b"Content-Type: multipart/mixed; boundary=\"b\"\n\n--b\n\ +Content-Type: text/plain; charset=iso-8859-1\nContent-Transfer-Encoding: quoted-printable\n\n\ +caf=E9 soft=\n break\n--b\nContent-Type: application/octet-stream\nContent-Transfer-Encoding: base64\n\n\ +SGVs\nbG8=\n--b--\n"; + let message = parse(raw); + let text = message.part(1).expect("text"); + assert_eq!(text.encoding(), crate::Encoding::QuotedPrintable); + assert_eq!(text.decoded().as_ref(), b"caf\xe9 soft break"); + assert_eq!(text.decoded_len(), 15); + assert_eq!(text.text().as_deref(), Some("café soft break")); + let mut out = String::from(">"); + assert!(text.text_into(&mut out)); + assert_eq!(out, ">café soft break"); + let binary = message.part(2).expect("binary"); + assert!(matches!(binary.kind(), PartKind::Binary)); + assert_eq!(binary.decoded().as_ref(), b"Hello"); + assert_eq!(binary.decoded_len(), 5); + assert!(binary.text().is_none()); + let mut bytes = b"<".to_vec(); + binary.decode_into(&mut bytes); + assert_eq!(bytes, b"<Hello"); + assert!(!binary.text_into(&mut out)); + assert_eq!(message.root_part().children().len(), 2); +} + +#[test] +fn header_views() { + let raw = b"Subject: hello\nX-Te\xffst: value\nReply-To: a@b\nKeywords: a, b\n\nbody"; + let message = parse(raw); + let headers = message.headers(); + assert_eq!(headers.len(), 4); + let odd = headers.iter().nth(1).expect("header"); + assert_eq!(odd.raw_name(), "X-Te\u{fffd}st"); + assert!(odd.name().is_other()); + assert_eq!(odd.value().as_text(), Some("value")); + let subject = headers.get(HeaderName::Subject).expect("subject"); + assert_eq!(subject.raw_value(), b" hello\n"); + let reparsed = subject.parse_as(crate::HeaderForm::ContentType); + assert_eq!( + reparsed.value().as_content_type().map(|ct| ct.ctype()), + Some("hello") + ); + assert!(headers.contains("reply-to")); + assert!(headers.has_known()); + assert_eq!(headers.all(HeaderName::Subject).count(), 1); + assert_eq!(headers.all("x-te\u{fffd}st").count(), 1); +} + +#[test] +fn decode_problems() { + let raw = b"Content-Type: multipart/mixed; boundary=\"b\"\n\n\ +--b\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: base64\n\nY2Fmw6k=\n\ +--b\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: base64\n\nY2Fm-w6k=\n\ +--b\nContent-Type: text/plain; charset=iso-8859-1\nContent-Transfer-Encoding: quoted-printable\n\ncaf=E9 =ZZ\n\ +--b\nContent-Type: text/plain; charset=x-unknown\n\ncaf\xc3\xa9\n\ +--b\nContent-Type: text/plain; charset=utf-8\n\ncaf\xe9\n\ +--b\nContent-Type: application/octet-stream\nContent-Transfer-Encoding: x-uuencode\n\nbegin 644 x\n\ +--b\nContent-Type: text/plain; charset=\"iso-8859-3\"\nContent-Transfer-Encoding: 8BIT (raw)\n\n\xa5\n\ +--b\nContent-Type: text/plain; charset=shift_jis\n\n\x83n\n\ +--b--\n"; + let message = parse(raw); + let shift_jis = if cfg!(feature = "full_encoding") { + ("\u{30cf}", DecodeProblems::default()) + } else { + ( + "\u{fffd}n", + DecodeProblems::UNKNOWN_CHARSET | DecodeProblems::MALFORMED_CHARSET, + ) + }; + let expected = [ + ("caf\u{e9}", DecodeProblems::default()), + ("caf\u{e9}", DecodeProblems::MALFORMED_TRANSFER_ENCODING), + ("caf\u{e9} =ZZ", DecodeProblems::MALFORMED_TRANSFER_ENCODING), + ("caf\u{e9}", DecodeProblems::UNKNOWN_CHARSET), + ("caf\u{fffd}", DecodeProblems::MALFORMED_CHARSET), + ("", DecodeProblems::UNKNOWN_TRANSFER_ENCODING), + ("\u{fffd}", DecodeProblems::MALFORMED_CHARSET), + shift_jis, + ]; + assert_eq!(message.parts().len(), expected.len() + 1); + for (part, (text, problems)) in message.parts().skip(1).zip(expected) { + let (decoded, transfer) = part.decoded_checked(); + assert_eq!(decoded, part.decoded(), "part {}", part.id()); + let checked = part.text_checked(); + assert_eq!(checked.clone().map(|(text, _)| text), part.text()); + match checked { + Some((checked, found)) => { + assert_eq!( + (checked.as_ref(), found), + (text, problems), + "part {}", + part.id() + ); + assert!(found.contains(transfer), "part {}", part.id()); + } + None => assert_eq!(transfer, problems, "part {}", part.id()), + } + } + assert_eq!( + DecodeProblems::MALFORMED_TRANSFER_ENCODING + .names() + .collect::<Vec<_>>(), + ["malformed_transfer_encoding"] + ); +} + +#[test] +fn checked_decoding_matches_the_fast_path_on_fixtures() { + for file in fixture_files() { + for raw in [with_lf(&file), with_crlf(&file)] { + let Some(message) = MessageParser::new().parse(&raw) else { + continue; + }; + for part in message.parts() { + assert_eq!(part.decoded_checked().0, part.decoded()); + assert_eq!(part.text_checked().map(|(text, _)| text), part.text()); + } + } + } +} + +fn spelled_name(raw: &[u8], offset_field: u32, offset_start: u32) -> String { + let region = raw + .get(offset_field as usize..(offset_start as usize).saturating_sub(1)) + .unwrap_or_default(); + String::from_utf8_lossy(crate::header_name::trim_blank_end(region)).into_owned() +} + +#[test] +fn raw_names_keep_the_original_spelling() { + let mut raw = Vec::new(); + let mut known = Vec::new(); + for id in 0..crate::header_name::KNOWN_NAMES as u16 { + let name = crate::header_name::canonical(id); + let (head, tail) = name.split_at(name.len() / 2); + for (spelling, is_known) in [ + (name.to_string(), true), + (name.to_ascii_lowercase(), true), + (name.to_ascii_uppercase(), true), + (format!(":{name}"), false), + (format!("{name} \t"), true), + (format!("{head} {tail}"), false), + ] { + raw.extend_from_slice(spelling.as_bytes()); + raw.extend_from_slice(b": value\r\n"); + known.push(is_known); + } + } + raw.extend_from_slice(b"X-Other: v\nx-caf\xc3\xa9 : v\nX-\xff: v\n\nbody"); + known.extend([false; 3]); + let message = parse(&raw); + let headers = message.headers(); + assert_eq!(headers.len(), known.len()); + for ((index, header), is_known) in headers.iter().enumerate().zip(known) { + assert_eq!( + header.raw_name(), + spelled_name(&raw, header.offset_field(), header.offset_start()), + "header {index}" + ); + assert_eq!(header.name().is_other(), !is_known, "header {index}"); + if is_known { + assert!( + header + .raw_name() + .eq_ignore_ascii_case(header.name().as_str()) + ); + } + } +} + +#[cfg(feature = "serde")] +#[test] +fn serialize_message() { + let message = parse(NESTED_INLINE); + let json = serde_json::to_value(&message).expect("serializes"); + assert_eq!(json["messages"].as_array().map(Vec::len), Some(2)); + assert_eq!(json["messages"][1]["container"], 2); + assert_eq!(json["parts"][0]["kind"], "multipart"); + assert_eq!(json["parts"][0]["children"], serde_json::json!([1, 2])); + assert_eq!(json["parts"][2]["nested"], 1); + assert_eq!(json["parts"][3]["text"], "nested body"); + assert_eq!( + json["parts"][0]["headers"][0]["value"]["content_type"]["attributes"][0], + serde_json::json!(["boundary", "outer"]) + ); + let raw = encoded_message("inner", "inner body\n"); + let message = parse(raw.as_bytes()); + let json = serde_json::to_value(&message).expect("serializes"); + assert_eq!(json["messages"][1]["source"]["decoded"], 1); + let binary = MessageParser::new() + .max_encoded_nesting(0) + .parse(raw.as_bytes()) + .expect("parses"); + let json = serde_json::to_value(&binary).expect("serializes"); + assert_eq!(json["parts"][1]["kind"], "binary"); + assert!( + json["parts"][1]["binary"] + .as_str() + .is_some_and(|b64| !b64.is_empty()) + ); +} + +#[test] +fn mutated_inputs_never_panic() { + const TOKENS: [&[u8]; 12] = [ + b"\n", + b"\r\n", + b"\n--", + b"--b", + b"--outer--", + b":", + b"=?utf-8?q?a?=", + b"\n\n", + b" ", + b"Content-Type: message/rfc822\n", + b"Content-Transfer-Encoding: base64\n", + b"\"", + ]; + let mut rng = crate::scan::tests::Rng(0x0123_4567_89ab_cdef); + let encoded = encoded_message("m", "body\n").into_bytes(); + let seeds: [&[u8]; 3] = [MULTIPART, NESTED_INLINE, &encoded]; + for seed in seeds { + for _ in 0..1500 { + let mut raw = seed.to_vec(); + for _ in 0..1 + rng.below(4) { + let at = rng.below(raw.len() + 1); + match rng.below(3) { + 0 => { + let token = TOKENS + .get(rng.below(TOKENS.len())) + .copied() + .unwrap_or_default(); + raw.splice(at..at, token.iter().copied()); + } + 1 => { + let end = (at + rng.below(16)).min(raw.len()); + raw.drain(at..end); + } + _ => { + if let Some(byte) = raw.get_mut(at) { + *byte = rng.next() as u8; + } + } + } + } + let [scalar, best] = [Kernel::SCALAR, Kernel::best()].map(|kernel| { + MessageParser::new() + .kernel(kernel) + .parse(&raw) + .map(|message| dump(&message)) + }); + assert_eq!(scalar, best, "{raw:?}"); + } + } +} diff --git a/src/parsers/fields/address.rs b/src/parsers/fields/address.rs deleted file mode 100644 index b5d56aa..0000000 --- a/src/parsers/fields/address.rs +++ /dev/null @@ -1,501 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use crate::{Addr, Address, Group, HeaderValue, parsers::MessageStream}; -use std::borrow::Cow; - -#[derive(PartialEq, Clone, Copy, Debug)] -enum AddressState { - Address, - Name, - Quote, - Comment, -} - -pub struct AddressParser<'x> { - token_start: usize, - token_end: usize, - - is_token_email: bool, - is_token_start: bool, - is_escaped: bool, - last_is_encoded: bool, - - name_tokens: Vec<Cow<'x, str>>, - mail_tokens: Vec<Cow<'x, str>>, - comment_tokens: Vec<Cow<'x, str>>, - - state: AddressState, - state_stack: Vec<AddressState>, - - addresses: Vec<Addr<'x>>, - group_name: Option<Cow<'x, str>>, - group_comment: Option<Cow<'x, str>>, - result: Vec<Group<'x>>, -} - -impl<'x> AddressParser<'x> { - pub fn add_token(&mut self, stream: &MessageStream<'x>) { - if self.token_start > 0 { - let token = String::from_utf8_lossy(&stream.data[self.token_start - 1..self.token_end]); - let mut add_space = false; - let list = match self.state { - AddressState::Address => &mut self.mail_tokens, - AddressState::Name => { - if self.is_token_email { - &mut self.mail_tokens - } else { - add_space = true; - &mut self.name_tokens - } - } - AddressState::Quote => &mut self.name_tokens, - AddressState::Comment => { - add_space = true; - &mut self.comment_tokens - } - }; - - if add_space && !list.is_empty() { - list.push(" ".into()); - } - - list.push(token); - - self.token_start = 0; - self.is_token_email = false; - self.is_token_start = true; - self.is_escaped = false; - self.last_is_encoded = false; - } - } - - pub fn add_rfc2047(&mut self, token: String) { - let add_space = !self.last_is_encoded && self.state != AddressState::Quote; - let list = if self.state != AddressState::Comment { - &mut self.name_tokens - } else { - &mut self.comment_tokens - }; - - if add_space && !list.is_empty() { - list.push(" ".into()); - } - - list.push(token.into()); - self.last_is_encoded = true; - } - - pub fn add_address(&mut self) { - let has_mail = !self.mail_tokens.is_empty(); - let has_name = !self.name_tokens.is_empty(); - let has_comment = !self.comment_tokens.is_empty(); - - self.addresses.push(if has_mail && has_name && has_comment { - Addr { - name: Some( - format!( - "{} ({})", - concat_tokens(&mut self.name_tokens), - concat_tokens(&mut self.comment_tokens) - ) - .into(), - ), - address: concat_tokens(&mut self.mail_tokens).into(), - } - } else if has_name && has_mail { - Addr { - name: concat_tokens(&mut self.name_tokens).into(), - address: concat_tokens(&mut self.mail_tokens).into(), - } - } else if has_mail && has_comment { - Addr { - name: concat_tokens(&mut self.comment_tokens).into(), - address: concat_tokens(&mut self.mail_tokens).into(), - } - } else if has_mail { - Addr { - name: None, - address: concat_tokens(&mut self.mail_tokens).into(), - } - } else if has_name && has_comment { - let name = concat_tokens(&mut self.name_tokens); - let comment = concat_tokens(&mut self.comment_tokens); - - if !name.chars().any(char::is_whitespace) { - Addr { - name: comment.into(), - address: name.into(), - } - } else { - Addr { - name: Some(format!("{name} ({comment})").into()), - address: None, - } - } - } else if has_name { - Addr { - name: concat_tokens(&mut self.name_tokens).into(), - address: None, - } - } else if has_comment { - Addr { - name: concat_tokens(&mut self.comment_tokens).into(), - address: None, - } - } else { - return; - }); - } - - pub fn add_group_details(&mut self) { - if !self.name_tokens.is_empty() { - self.group_name = concat_tokens(&mut self.name_tokens).into(); - } - - if !self.comment_tokens.is_empty() { - self.group_comment = concat_tokens(&mut self.comment_tokens).into(); - } - - if !self.mail_tokens.is_empty() { - if let Some(group_name) = &self.group_name { - self.group_name = - Some(format!("{} {}", group_name, concat_tokens(&mut self.mail_tokens)).into()); - } else { - self.group_name = concat_tokens(&mut self.mail_tokens).into(); - } - } - } - - pub fn add_group(&mut self) { - let has_name = self.group_name.is_some(); - let has_comment = self.group_comment.is_some(); - let has_addresses = !self.addresses.is_empty(); - - self.result - .push(if has_name && has_addresses && has_comment { - Group { - name: Some( - format!( - "{} ({})", - self.group_name.take().unwrap(), - self.group_comment.take().unwrap() - ) - .into(), - ), - addresses: std::mem::take(&mut self.addresses), - } - } else if has_addresses && has_name { - Group { - name: self.group_name.take(), - addresses: std::mem::take(&mut self.addresses), - } - } else if has_addresses { - Group { - name: self.group_comment.take(), - addresses: std::mem::take(&mut self.addresses), - } - } else if has_name { - Group { - name: self.group_name.take(), - addresses: Vec::new(), - } - } else { - return; - }); - } -} - -impl<'x> MessageStream<'x> { - pub fn parse_address(&mut self) -> HeaderValue<'x> { - let mut parser = AddressParser { - token_start: 0, - token_end: 0, - - is_token_email: false, - is_token_start: true, - is_escaped: false, - last_is_encoded: true, - - name_tokens: Vec::with_capacity(3), - mail_tokens: Vec::with_capacity(3), - comment_tokens: Vec::with_capacity(3), - - state: AddressState::Name, - state_stack: Vec::with_capacity(5), - - addresses: Vec::new(), - group_name: None, - group_comment: None, - result: Vec::new(), - }; - - while let Some(ch) = self.next() { - match ch { - b'\n' => { - parser.add_token(self); - if parser.state == AddressState::Quote { - if self.peek_next_is_space() { - continue; - } else { - break; - } - } - if self.try_next_is_space() { - if !parser.is_token_start { - parser.is_token_start = true; - } - continue; - } else { - break; - } - } - b'\\' if parser.state != AddressState::Name && !parser.is_escaped => { - if parser.token_start > 0 { - if parser.state == AddressState::Quote { - parser.token_end = self.offset() - 1; - } - parser.add_token(self); - } - parser.is_escaped = true; - continue; - } - b',' if parser.state == AddressState::Name => { - parser.add_token(self); - parser.add_address(); - continue; - } - b'<' if parser.state == AddressState::Name => { - parser.is_token_email = false; - parser.add_token(self); - parser.state_stack.push(AddressState::Name); - parser.state = AddressState::Address; - continue; - } - b'>' if parser.state == AddressState::Address => { - parser.add_token(self); - parser.state = parser.state_stack.pop().unwrap(); - continue; - } - b'"' if !parser.is_escaped => match parser.state { - AddressState::Name => { - parser.state_stack.push(AddressState::Name); - parser.state = AddressState::Quote; - parser.add_token(self); - continue; - } - AddressState::Quote => { - parser.add_token(self); - parser.state = parser.state_stack.pop().unwrap(); - continue; - } - _ => (), - }, - b'@' if parser.state == AddressState::Name => { - parser.is_token_email = true; - } - b'=' if parser.is_token_start && !parser.is_escaped && self.peek_char(b'?') => { - self.checkpoint(); - if let Some(token) = self.decode_rfc2047() { - parser.add_token(self); - parser.add_rfc2047(token); - continue; - } - self.restore(); - } - b' ' | b'\t' => { - if !parser.is_token_start { - parser.is_token_start = true; - } - if parser.is_escaped { - parser.is_escaped = false; - } - if parser.state == AddressState::Quote { - if parser.token_start == 0 { - parser.token_start = self.offset(); - parser.token_end = parser.token_start; - } else { - parser.token_end = self.offset(); - } - } - continue; - } - b'\r' => continue, - b'(' if parser.state != AddressState::Quote && !parser.is_escaped => { - parser.state_stack.push(parser.state); - if parser.state != AddressState::Comment { - parser.add_token(self); - parser.state = AddressState::Comment; - parser.last_is_encoded = false; - continue; - } - } - b')' if parser.state == AddressState::Comment && !parser.is_escaped => { - let new_state = parser.state_stack.pop().unwrap(); - if parser.state != new_state { - parser.add_token(self); - parser.state = new_state; - parser.last_is_encoded = false; - continue; - } - } - b':' if parser.state == AddressState::Name && !parser.is_escaped => { - parser.add_group(); - parser.add_token(self); - parser.add_group_details(); - continue; - } - b';' if parser.state == AddressState::Name => { - parser.add_token(self); - parser.add_address(); - parser.add_group(); - continue; - } - _ => (), - } - - if parser.is_escaped { - parser.is_escaped = false; - } - - if parser.is_token_start { - parser.is_token_start = false; - } - - if parser.token_start == 0 { - parser.token_start = self.offset(); - parser.token_end = parser.token_start; - } else { - parser.token_end = self.offset(); - } - } - - parser.add_address(); - - if parser.group_name.is_some() || !parser.result.is_empty() { - parser.add_group(); - HeaderValue::Address(Address::Group(parser.result)) - } else if !parser.addresses.is_empty() { - HeaderValue::Address(Address::List(parser.addresses)) - } else { - HeaderValue::Empty - } - } -} - -fn concat_tokens<'x>(tokens: &mut Vec<Cow<'x, str>>) -> Cow<'x, str> { - if tokens.len() == 1 { - tokens.pop().unwrap() - } else { - let result = tokens.concat(); - tokens.clear(); - result.into() - } -} - -pub fn parse_address_local_part(addr: &str) -> Option<&str> { - let addr = addr.as_bytes(); - let mut iter = addr.iter().enumerate(); - while let Some((pos, &ch)) = iter.next() { - if ch == b'@' { - return if pos > 0 && iter.next().is_some() { - std::str::from_utf8(addr.get(..pos)?).ok() - } else { - None - }; - } else if !ch.is_ascii() { - return None; - } - } - - None -} - -pub fn parse_address_domain(addr: &str) -> Option<&str> { - let addr = addr.as_bytes(); - for (pos, &ch) in addr.iter().enumerate() { - if ch == b'@' { - return if pos > 0 && pos + 1 < addr.len() { - std::str::from_utf8(addr.get(pos + 1..)?).ok() - } else { - None - }; - } else if !ch.is_ascii() { - return None; - } - } - - None -} - -pub fn parse_address_user_part(addr: &str) -> Option<&str> { - let addr = addr.as_bytes(); - - let mut iter = addr.iter().enumerate(); - while let Some((pos, &ch)) = iter.next() { - if ch == b'+' { - if pos > 0 { - while let Some((_, &ch)) = iter.next() { - if ch == b'@' && iter.next().is_some() { - return std::str::from_utf8(addr.get(..pos)?).ok(); - } - } - } - return None; - } else if ch == b'@' { - return if pos > 0 && iter.next().is_some() { - std::str::from_utf8(addr.get(..pos)?).ok() - } else { - None - }; - } else if !ch.is_ascii() { - return None; - } - } - - None -} - -pub fn parse_address_detail_part(addr: &str) -> Option<&str> { - let addr = addr.as_bytes(); - let mut plus_pos = usize::MAX; - - let mut iter = addr.iter().enumerate(); - while let Some((pos, &ch)) = iter.next() { - if ch == b'+' { - plus_pos = pos + 1; - } else if ch == b'@' { - if plus_pos != usize::MAX && iter.next().is_some() { - return std::str::from_utf8(addr.get(plus_pos..pos)?).ok(); - } else { - return None; - } - } else if !ch.is_ascii() { - return None; - } - } - - None -} - -#[cfg(test)] -mod tests { - use crate::parsers::{MessageStream, fields::load_tests}; - - #[test] - fn parse_addresses() { - for test in load_tests("address.json") { - assert_eq!( - MessageStream::new(test.header.as_bytes()) - .parse_address() - .unwrap_address(), - test.expected, - "failed for {:?}", - test.header - ); - } - } -} diff --git a/src/parsers/fields/content_type.rs b/src/parsers/fields/content_type.rs deleted file mode 100644 index 1f0c7e4..0000000 --- a/src/parsers/fields/content_type.rs +++ /dev/null @@ -1,547 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::borrow::Cow; - -use crate::{ - Attribute, ContentType, HeaderValue, - decoders::{charsets::map::charset_decoder, hex::decode_hex}, - parsers::MessageStream, -}; - -#[derive(Clone, Copy, PartialEq, Debug)] -enum ContentState { - Type, - SubType, - AttributeName, - AttributeValue, - AttributeQuotedValue, - Comment, -} - -type Continuation<'x> = (Cow<'x, str>, u32, Cow<'x, str>); - -struct ContentTypeParser<'x> { - state: ContentState, - state_stack: Vec<ContentState>, - - c_type: Option<Cow<'x, str>>, - c_subtype: Option<Cow<'x, str>>, - - attr_name: Option<Cow<'x, str>>, - attr_charset: Option<Cow<'x, str>>, - attr_position: u32, - - values: Vec<Cow<'x, str>>, - attributes: Vec<Attribute<'x>>, - continuations: Option<Vec<Continuation<'x>>>, - - token_start: usize, - token_end: usize, - - is_continuation: bool, - is_encoded_attribute: bool, - is_escaped: bool, - remove_crlf: bool, - is_lower_case: bool, - is_token_start: bool, -} - -impl<'x> ContentTypeParser<'x> { - #[inline(always)] - fn reset_parser(&mut self) { - self.token_start = 0; - self.is_token_start = true; - } - - fn add_attribute(&mut self, stream: &MessageStream<'x>) -> bool { - if self.token_start > 0 { - let mut attr = Some(String::from_utf8_lossy( - &stream.data[self.token_start - 1..self.token_end], - )); - - if !self.is_lower_case { - attr.as_mut().unwrap().to_mut().make_ascii_lowercase(); - self.is_lower_case = true; - } - - match self.state { - ContentState::AttributeName => self.attr_name = attr, - ContentState::Type => self.c_type = attr, - ContentState::SubType => self.c_subtype = attr, - _ => unreachable!(), - } - - self.reset_parser(); - true - } else { - false - } - } - - fn add_attribute_parameter(&mut self, stream: &MessageStream<'x>) { - if self.token_start > 0 { - let attr_part = - String::from_utf8_lossy(&stream.data[self.token_start - 1..self.token_end]); - - if self.attr_charset.is_none() { - self.attr_charset = attr_part.into(); - } else { - let attr_name = - self.attr_name.as_ref().unwrap_or(&"unknown".into()).clone() + "-language"; - - if !self.attributes.iter().any(|a| a.name == attr_name) { - self.attributes.push(Attribute { - name: attr_name, - value: attr_part, - }); - } else { - self.values.push("'".into()); - self.values.push(attr_part); - } - } - - self.reset_parser(); - } - } - - fn add_partial_value(&mut self, stream: &MessageStream<'x>, to_cur_pos: bool) { - if self.token_start > 0 { - let in_quote = self.state == ContentState::AttributeQuotedValue; - - self.values.push(String::from_utf8_lossy( - &stream.data[self.token_start - 1..if in_quote && to_cur_pos { - stream.offset() - 1 - } else { - self.token_end - }], - )); - if !in_quote { - self.values.push(" ".into()); - } - - self.reset_parser(); - } - } - - fn add_value(&mut self, stream: &MessageStream<'x>) { - if self.attr_name.is_none() { - return; - } - - let has_values = !self.values.is_empty(); - let value = if self.token_start > 0 { - let value = &stream.data[self.token_start - 1..self.token_end]; - Some(if !self.remove_crlf { - String::from_utf8_lossy(value) - } else { - self.remove_crlf = false; - match String::from_utf8( - value - .iter() - .filter(|&&ch| ch != b'\r' && ch != b'\n') - .copied() - .collect::<Vec<_>>(), - ) { - Ok(value) => value.into(), - Err(err) => String::from_utf8_lossy(err.as_bytes()).into_owned().into(), - } - }) - } else { - if !has_values { - return; - } - None - }; - - if !self.is_continuation { - self.attributes.push(Attribute { - name: self.attr_name.take().unwrap(), - value: if !has_values { - value.unwrap() - } else { - if let Some(value) = value { - self.values.push(value); - } - self.values.concat().into() - }, - }); - } else { - let attr_name = self.attr_name.take().unwrap(); - let mut value = if let Some(value) = value { - if has_values { - Cow::from(self.values.concat()) + value - } else { - value - } - } else { - self.values.concat().into() - }; - - if self.is_encoded_attribute { - if let (true, decoded_bytes) = decode_hex(value.as_bytes()) { - value = if let Some(decoder) = self - .attr_charset - .as_ref() - .and_then(|c| charset_decoder(c.as_bytes())) - { - decoder(&decoded_bytes).into() - } else { - String::from_utf8(decoded_bytes) - .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()) - .into() - } - } - self.is_encoded_attribute = false; - } - - if self.attr_position > 0 { - let continuation = (attr_name, self.attr_position, value); - if let Some(continuations) = self.continuations.as_mut() { - continuations.push(continuation); - } else { - self.continuations = Some(vec![continuation]); - } - - self.attr_position = 0; - } else { - self.attributes.push(Attribute { - name: attr_name, - value, - }); - } - self.is_continuation = false; - self.attr_charset = None; - } - - if has_values { - self.values.clear(); - } - - self.reset_parser(); - } - - fn add_attr_position(&mut self, stream: &MessageStream<'_>) -> bool { - if self.token_start > 0 { - self.attr_position = - String::from_utf8_lossy(&stream.data[self.token_start - 1..self.token_end]) - .parse() - .unwrap_or(0); - - self.reset_parser(); - true - } else { - false - } - } - - fn merge_continuations(&mut self) { - let continuations = self.continuations.as_mut().unwrap(); - continuations.sort(); - for (key, _, value) in continuations.drain(..) { - if let Some(old) = self.attributes.iter_mut().find(|a| a.name == key) { - old.value = format!("{}{value}", old.value).into(); - } else { - self.attributes.push(Attribute { name: key, value }); - } - } - } -} - -impl<'x> MessageStream<'x> { - pub fn parse_content_type(&mut self) -> HeaderValue<'x> { - let mut parser = ContentTypeParser { - state: ContentState::Type, - state_stack: Vec::new(), - - c_type: None, - c_subtype: None, - - attr_name: None, - attr_charset: None, - attr_position: 0, - - attributes: Vec::new(), - values: Vec::new(), - continuations: None, - - is_continuation: false, - is_encoded_attribute: false, - is_lower_case: true, - is_token_start: true, - is_escaped: false, - remove_crlf: false, - - token_start: 0, - token_end: 0, - }; - - while let Some(ch) = self.next() { - match ch { - b' ' | b'\t' => { - if !parser.is_token_start { - parser.is_token_start = true; - } - if let ContentState::AttributeQuotedValue = parser.state { - if parser.token_start == 0 { - parser.token_start = self.offset(); - parser.token_end = parser.token_start; - } else { - parser.token_end = self.offset(); - } - } - continue; - } - b'A'..=b'Z' if parser.is_lower_case => { - if let ContentState::Type - | ContentState::SubType - | ContentState::AttributeName = parser.state - { - parser.is_lower_case = false; - } - } - b'\n' => { - let next_is_space = self.peek_next_is_space(); - match parser.state { - ContentState::Type - | ContentState::AttributeName - | ContentState::SubType => { - parser.add_attribute(self); - } - ContentState::AttributeValue => { - parser.add_value(self); - } - ContentState::AttributeQuotedValue => { - if next_is_space { - self.next(); - parser.remove_crlf = true; - continue; - } else { - parser.add_value(self); - } - } - _ => (), - } - - if next_is_space { - if parser.state == ContentState::Type { - continue; - } - parser.state = ContentState::AttributeName; - self.next(); - - if !parser.is_token_start { - parser.is_token_start = true; - } - continue; - } else { - if parser.continuations.is_some() { - parser.merge_continuations(); - } - - return if let Some(content_type) = parser.c_type { - HeaderValue::ContentType(ContentType { - c_type: content_type, - c_subtype: parser.c_subtype.take(), - attributes: if !parser.attributes.is_empty() { - Some(parser.attributes) - } else { - None - }, - }) - } else { - HeaderValue::Empty - }; - } - } - b'/' if parser.state == ContentState::Type => { - parser.add_attribute(self); - parser.state = ContentState::SubType; - continue; - } - b';' => match parser.state { - ContentState::Type | ContentState::SubType | ContentState::AttributeName => { - parser.add_attribute(self); - parser.state = ContentState::AttributeName; - continue; - } - ContentState::AttributeValue => { - if !parser.is_escaped { - parser.add_value(self); - parser.state = ContentState::AttributeName; - } else { - parser.is_escaped = false; - } - continue; - } - _ => (), - }, - b'*' if parser.state == ContentState::AttributeName => { - if !parser.is_continuation { - parser.is_continuation = parser.add_attribute(self); - } else if !parser.is_encoded_attribute { - parser.add_attr_position(self); - parser.is_encoded_attribute = true; - } else { - // Malformed data, reset parser. - parser.reset_parser(); - } - continue; - } - b'=' => match parser.state { - ContentState::AttributeName => { - if !parser.is_continuation { - if !parser.add_attribute(self) { - continue; - } - } else if !parser.is_encoded_attribute { - /* If is_continuation=true && is_encoded_attribute=false, - the last character was a '*' which means encoding */ - parser.is_encoded_attribute = !parser.add_attr_position(self); - } else { - parser.reset_parser(); - } - parser.state = ContentState::AttributeValue; - continue; - } - ContentState::AttributeValue | ContentState::AttributeQuotedValue - if parser.is_token_start && self.peek_char(b'?') => - { - self.checkpoint(); - if let Some(token) = self.decode_rfc2047() { - parser.add_partial_value(self, false); - parser.values.push(token.into()); - continue; - } - self.restore(); - } - _ => (), - }, - b'\"' => match parser.state { - ContentState::AttributeValue => { - if !parser.is_token_start { - parser.is_token_start = true; - } - parser.state = ContentState::AttributeQuotedValue; - continue; - } - ContentState::AttributeQuotedValue => { - if !parser.is_escaped { - parser.add_value(self); - parser.state = ContentState::AttributeName; - continue; - } else { - parser.is_escaped = false; - } - } - _ => continue, - }, - b'\\' => match parser.state { - ContentState::AttributeQuotedValue | ContentState::AttributeValue => { - if !parser.is_escaped { - parser.add_partial_value(self, true); - parser.is_escaped = true; - continue; - } else { - parser.is_escaped = false; - } - } - ContentState::Comment => parser.is_escaped = !parser.is_escaped, - _ => continue, - }, - b'\'' - if parser.is_encoded_attribute - && !parser.is_escaped - && (parser.state == ContentState::AttributeValue - || parser.state == ContentState::AttributeQuotedValue) => - { - parser.add_attribute_parameter(self); - continue; - } - b'(' if parser.state != ContentState::AttributeQuotedValue => { - if !parser.is_escaped { - match parser.state { - ContentState::Type - | ContentState::AttributeName - | ContentState::SubType => { - parser.add_attribute(self); - } - ContentState::AttributeValue => { - parser.add_value(self); - } - _ => (), - } - - parser.state_stack.push(parser.state); - parser.state = ContentState::Comment; - } else { - parser.is_escaped = false; - } - continue; - } - b')' if parser.state == ContentState::Comment => { - if !parser.is_escaped { - parser.state = parser.state_stack.pop().unwrap(); - parser.reset_parser(); - } else { - parser.is_escaped = false; - } - continue; - } - b'\r' => continue, - _ => (), - } - - if parser.is_escaped { - parser.is_escaped = false; - } - - if parser.is_token_start { - parser.is_token_start = false; - } - - if parser.token_start == 0 { - parser.token_start = self.offset(); - parser.token_end = parser.token_start; - } else { - parser.token_end = self.offset(); - } - } - - HeaderValue::Empty - } -} -#[cfg(test)] -mod tests { - use crate::parsers::{MessageStream, fields::load_tests}; - - #[test] - fn parse_content_fields() { - for test in load_tests("content_type.json") { - assert_eq!( - MessageStream::new(test.header.as_bytes()) - .parse_content_type() - .into_content_type(), - test.expected, - "failed for {:?}", - test.header - ); - } - - /*let mut builder = crate::parsers::fields::TestBuilder::new("content_type.json"); - - for input in inputs { - println!("Testing: {:?}", input.0); - let result = MessageStream::new(input.0.as_bytes()) - .parse_content_type() - .into_content_type(); - - builder.add(input.0.to_string(), result); - } - - builder.write();*/ - } -} diff --git a/src/parsers/fields/date.rs b/src/parsers/fields/date.rs deleted file mode 100644 index 72b67b1..0000000 --- a/src/parsers/fields/date.rs +++ /dev/null @@ -1,569 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::fmt; - -use crate::{DateTime, HeaderValue, parsers::MessageStream}; - -pub static DOW: &[&str] = &["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -pub static MONTH: &[&str] = &[ - "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", -]; - -impl DateTime { - /// Parses an RFC822 date - pub fn parse_rfc822(value: &str) -> Option<Self> { - match MessageStream::new(value.as_bytes()).parse_date() { - HeaderValue::DateTime(dt) => dt.into(), - _ => None, - } - } - - /// Parses an RFC3339 date - pub fn parse_rfc3339(value: &str) -> Option<Self> { - // 2004 - 06 - 28 T 23 : 43 : 45 . 000 Z - // 1969 - 02 - 13 T 23 : 32 : 00 - 03 : 30 - // 0 1 2 3 4 5 6 7 - - let mut pos = 0; - let mut parts = [0u32; 8]; - let mut parts_sizes = [ - 4u32, // Year (0) - 2u32, // Month (1) - 2u32, // Day (2) - 2u32, // Hour (3) - 2u32, // Minute (4) - 2u32, // Second (5) - 2u32, // TZ Hour (6) - 2u32, // TZ Minute (7) - ]; - let mut skip_digits = false; - let mut is_plus = true; - - for ch in value.as_bytes() { - match ch { - b'0'..=b'9' if !skip_digits => { - if parts_sizes[pos] > 0 { - parts_sizes[pos] -= 1; - parts[pos] += (*ch - b'0') as u32 * u32::pow(10, parts_sizes[pos]); - } else { - return None; - } - } - b'-' => { - if pos <= 1 { - pos += 1; - } else if pos == 5 { - pos += 1; - is_plus = false; - skip_digits = false; - } else { - return None; - } - } - b'T' => { - if pos == 2 { - pos += 1; - } else { - return None; - } - } - b':' => { - if [3, 4, 6].contains(&pos) { - pos += 1; - } else { - return None; - } - } - b'+' => { - if pos == 5 { - pos += 1; - skip_digits = false; - } else { - return None; - } - } - b'.' => { - if pos == 5 { - skip_digits = true; - } else { - return None; - } - } - - _ => (), - } - } - - if pos >= 5 { - DateTime { - year: parts[0] as u16, - month: parts[1] as u8, - day: parts[2] as u8, - hour: parts[3] as u8, - minute: parts[4] as u8, - second: parts[5] as u8, - tz_hour: parts[6] as u8, - tz_minute: parts[7] as u8, - tz_before_gmt: !is_plus, - } - .into() - } else { - None - } - } - - /// Return an RFC822 date - pub fn to_rfc822(&self) -> String { - format!( - "{}, {} {} {:04} {:02}:{:02}:{:02} {}{:02}{:02}", - DOW[self.day_of_week() as usize], - self.day, - MONTH - .get(self.month.saturating_sub(1) as usize) - .unwrap_or(&""), - self.year, - self.hour, - self.minute, - self.second, - if self.tz_before_gmt && (self.tz_hour > 0 || self.tz_minute > 0) { - "-" - } else { - "+" - }, - self.tz_hour, - self.tz_minute - ) - } - - /// Returns an RFC3339 representation of the parsed RFC5322 datetime field - pub fn to_rfc3339(&self) -> String { - if self.tz_hour != 0 || self.tz_minute != 0 { - format!( - "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{}{:02}:{:02}", - self.year, - self.month, - self.day, - self.hour, - self.minute, - self.second, - if self.tz_before_gmt && (self.tz_hour > 0 || self.tz_minute > 0) { - "-" - } else { - "+" - }, - self.tz_hour, - self.tz_minute - ) - } else { - format!( - "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", - self.year, self.month, self.day, self.hour, self.minute, self.second, - ) - } - } - - /// Returns true if the date is valid - pub fn is_valid(&self) -> bool { - (0..=23).contains(&self.tz_hour) - && (1900..=3000).contains(&self.year) - && (0..=59).contains(&self.tz_minute) - && (1..=12).contains(&self.month) - && (1..=31).contains(&self.day) - && (0..=23).contains(&self.hour) - && (0..=59).contains(&self.minute) - && (0..=59).contains(&self.second) - } - - /// Returns the numbers of seconds since 1970-01-01T00:00:00Z (Unix epoch) - /// or None if the date is invalid. - pub fn to_timestamp(&self) -> i64 { - self.to_timestamp_local() - + ((self.tz_hour as i64 * 3600 + self.tz_minute as i64 * 60) - * if self.tz_before_gmt { 1 } else { -1 }) - } - - /// Returns the numbers of seconds since 1970-01-01T00:00:00Z (Unix epoch) in local time - /// or None if the date is invalid. - pub fn to_timestamp_local(&self) -> i64 { - // Ported from https://github.com/protocolbuffers/upb/blob/22182e6e/upb/json_decode.c#L982-L992 - let month = self.month as u32; - let year_base = 4800; /* Before min year, multiple of 400. */ - let m_adj = month.wrapping_sub(3); /* March-based month. */ - let carry = i64::from(m_adj > month); - let adjust = if carry > 0 { 12 } else { 0 }; - let y_adj = self.year as i64 + year_base - carry; - let month_days = ((m_adj.wrapping_add(adjust)) * 62719 + 769) / 2048; - let leap_days = y_adj / 4 - y_adj / 100 + y_adj / 400; - (y_adj * 365 + leap_days + month_days as i64 + (self.day as i64 - 1) - 2472632) * 86400 - + self.hour as i64 * 3600 - + self.minute as i64 * 60 - + self.second as i64 - } - - /// Creates a DateTime object from a timestamp - pub fn from_timestamp(timestamp: i64) -> Self { - // Ported from http://howardhinnant.github.io/date_algorithms.html#civil_from_days - let (z, seconds) = ( - (timestamp.div_euclid(86400)) + 719468, - timestamp.rem_euclid(86400), - ); - let era: i64 = (if z >= 0 { z } else { z - 146096 }) / 146097; - let doe: u64 = (z - era * 146097) as u64; // [0, 146096] - let yoe: u64 = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399] - let y: i64 = (yoe as i64) + era * 400; - let doy: u64 = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] - let mp = (5 * doy + 2) / 153; // [0, 11] - let d: u64 = doy - (153 * mp + 2) / 5 + 1; // [1, 31] - let m: u64 = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12] - let (h, mn, s) = (seconds / 3600, (seconds / 60) % 60, seconds % 60); - - DateTime { - year: (y + i64::from(m <= 2)) as u16, - month: m as u8, - day: d as u8, - hour: h as u8, - minute: mn as u8, - second: s as u8, - tz_before_gmt: false, - tz_hour: 0, - tz_minute: 0, - } - } - - /// Returns the day of week where [0, 6] represents [Sun, Sat]. - pub fn day_of_week(&self) -> u8 { - (((self.to_timestamp_local() as f64 / 86400.0).floor() as i64 + 4).rem_euclid(7)) as u8 - } - - /// Returns the julian day - pub fn julian_day(&self) -> i64 { - let day = self.day as i64; - let (month, year) = if self.month > 2 { - ((self.month - 3) as i64, self.year as i64) - } else { - ((self.month + 9) as i64, (self.year - 1) as i64) - }; - - let c = year / 100; - c * 146097 / 4 + (year - c * 100) * 1461 / 4 + (month * 153 + 2) / 5 + day + 1721119 - } - - /// Converts the DateTime to the given timezone - pub fn to_timezone(&self, tz: i64) -> DateTime { - let mut dt = DateTime::from_timestamp(self.to_timestamp() + tz); - dt.tz_before_gmt = tz < 0; - let tz = tz.abs(); - dt.tz_hour = (tz / 3600) as u8; - dt.tz_minute = ((tz % 3600) / 60) as u8; - dt - } -} - -impl PartialOrd for DateTime { - fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { - Some(self.cmp(other)) - } -} - -impl Ord for DateTime { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - match self.to_timestamp() - other.to_timestamp() { - 0 => std::cmp::Ordering::Equal, - x if x > 0 => std::cmp::Ordering::Greater, - _ => std::cmp::Ordering::Less, - } - } -} - -impl fmt::Display for DateTime { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.write_str(&self.to_rfc3339()) - } -} - -impl<'x> MessageStream<'x> { - pub fn parse_date(&mut self) -> HeaderValue<'x> { - let mut pos = 0; - let mut parts = [0u32; 7]; - let mut parts_sizes = [ - 2u32, // Day (0) - 2u32, // Month (1) - 4u32, // Year (2) - 2u32, // Hour (3) - 2u32, // Minute (4) - 2u32, // Second (5) - 4u32, // TZ (6) - ]; - let mut month_hash: usize = 0; - let mut month_pos: usize = 0; - - let mut is_plus = true; - let mut is_new_token = true; - let mut ignore = true; - let mut comment_count = 0; - - while let Some(ch) = self.next() { - let mut next_part = false; - - match ch { - b'\n' => { - if self.try_next_is_space() { - if !is_new_token && !ignore && comment_count == 0 { - next_part = true; - } else { - continue; - } - } else { - break; - } - } - _ if comment_count > 0 => { - if *ch == b')' { - comment_count -= 1; - } else if *ch == b'(' { - comment_count += 1; - } else if *ch == b'\\' { - self.try_skip_char(b')'); - } - continue; - } - b'0'..=b'9' => { - if pos < 7 && parts_sizes[pos] > 0 { - parts_sizes[pos] -= 1; - parts[pos] += (*ch - b'0') as u32 * u32::pow(10, parts_sizes[pos]); - - ignore = false; - } - is_new_token = false; - } - b':' if !is_new_token && !ignore && (pos == 3 || pos == 4) => { - next_part = true; - } - b'+' => { - pos = 6; - } - b'-' => { - is_plus = false; - pos = 6; - } - b' ' | b'\t' if !is_new_token && !ignore => { - next_part = true; - } - b'a'..=b'z' | b'A'..=b'Z' => { - if pos == 1 { - if (1..=2).contains(&month_pos) { - month_hash += MONTH_HASH - [(if *ch <= b'Z' { *ch + 32 } else { *ch }) as usize] - as usize; - } - month_pos += 1; - } - if pos == 6 { - let mut buf = [*ch, 0, 0]; - let zone = self.obs_zone(&mut buf); - is_plus = !zone.is_negative(); - parts[pos] = 100 * zone.unsigned_abs(); - parts_sizes[pos] = 0; - next_part = true; - } - is_new_token = false; - } - b'(' => { - comment_count += 1; - is_new_token = true; - continue; - } - b',' | b'\r' => (), - b';' => { - // May be parsing Received field, reset state. - pos = 0; - parts = [0u32; 7]; - parts_sizes = [ - 2u32, // Day (0) - 2u32, // Month (1) - 4u32, // Year (2) - 2u32, // Hour (3) - 2u32, // Minute (4) - 2u32, // Second (5) - 4u32, // TZ (6) - ]; - month_hash = 0; - month_pos = 0; - - is_plus = true; - is_new_token = true; - ignore = true; - continue; - } - _ => (), - } - - if next_part { - if pos < 7 && parts_sizes[pos] > 0 { - parts[pos] /= u32::pow(10, parts_sizes[pos]); - } - pos += 1; - is_new_token = true; - } - } - - if pos >= 6 { - let month: u8 = if month_pos == 3 { - MONTH_MAP.get(month_hash).copied().unwrap_or(0) - } else { - parts[1] as u8 - }; - if !(1..=12).contains(&month) { - return HeaderValue::Empty; - } - HeaderValue::DateTime(DateTime { - year: if (0..=49).contains(&parts[2]) { - parts[2] + 2000 - } else if (50..=99).contains(&parts[2]) { - parts[2] + 1900 - } else { - parts[2] - } as u16, - month, - day: parts[0] as u8, - hour: parts[3] as u8, - minute: parts[4] as u8, - second: parts[5] as u8, - tz_hour: ((parts[6] / 100) % 24) as u8, - tz_minute: ((parts[6] % 100) % 60) as u8, - tz_before_gmt: !is_plus, - }) - } else { - HeaderValue::Empty - } - } - // 4.3 obsolete date and time - fn obs_zone(&mut self, buf: &mut [u8; 3]) -> i32 { - let mut i = 1; - for &b in self.by_ref() { - buf[i] = b; - i += 1; - if i == 3 { - break; - } - } - - hashify::map! { buf.as_ref(), i32, - "EDT" => -4, - "EST" => -5, - "CDT" => -5, - "CST" => -6, - "MDT" => -6, - "MST" => -7, - "PDT" => -7, - "PST" => -8, - } - .copied() - .unwrap_or(0) - } -} - -static MONTH_HASH: &[u8] = &[ - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 0, 14, 4, 31, 10, 31, 14, 31, 31, 31, 31, 4, 31, 10, 15, 15, 31, 5, 31, 0, 5, 15, 31, 31, - 0, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, - 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, -]; - -pub static MONTH_MAP: &[u8; 31] = &[ - 5, 0, 0, 0, 10, 3, 0, 0, 0, 7, 1, 0, 0, 0, 12, 6, 0, 0, 0, 8, 4, 0, 0, 0, 2, 9, 0, 0, 0, 0, 11, -]; - -#[cfg(test)] -mod tests { - use chrono::{FixedOffset, LocalResult, SecondsFormat, TimeZone, Utc}; - - use crate::{ - DateTime, - parsers::{MessageStream, fields::load_tests}, - }; - - #[test] - fn parse_dates() { - for test in load_tests("date.json") { - let datetime = MessageStream::new(test.header.as_bytes()) - .parse_date() - .into_datetime(); - assert_eq!(datetime, test.expected, "failed for {:?}", test.header); - - match datetime { - Some(datetime) if datetime.is_valid() => { - if let LocalResult::Single(chrono_datetime) - | LocalResult::Ambiguous(chrono_datetime, _) = FixedOffset::west_opt( - ((datetime.tz_hour as i32 * 3600i32) + datetime.tz_minute as i32 * 60) - * if datetime.tz_before_gmt { 1i32 } else { -1i32 }, - ) - .unwrap_or_else(|| FixedOffset::east_opt(0).unwrap()) - .with_ymd_and_hms( - datetime.year as i32, - datetime.month as u32, - datetime.day as u32, - datetime.hour as u32, - datetime.minute as u32, - datetime.second as u32, - ) { - assert_eq!( - chrono_datetime.timestamp(), - datetime.to_timestamp(), - "{} -> {} ({}) -> {} ({})", - test.header.escape_debug(), - datetime.to_timestamp(), - Utc.timestamp_opt(datetime.to_timestamp(), 0) - .unwrap() - .to_rfc3339_opts(SecondsFormat::Secs, true), - chrono_datetime.timestamp(), - Utc.timestamp_opt(chrono_datetime.timestamp(), 0) - .unwrap() - .to_rfc3339_opts(SecondsFormat::Secs, true) - ); - let ts = datetime.to_timestamp(); - assert_eq!(DateTime::from_timestamp(ts).to_timestamp(), ts); - } - } - _ => {} - } - } - } - - #[test] - fn datetime_to_timezone() { - let dt = DateTime::parse_rfc3339("2021-01-01T00:00:00Z").unwrap(); - - for (tz, expected) in [ - (0i64, "2021-01-01T00:00:00Z"), - (3600, "2021-01-01T01:00:00+01:00"), - (-3600, "2020-12-31T23:00:00-01:00"), - (19800, "2021-01-01T05:30:00+05:30"), - (-12600, "2020-12-31T20:30:00-03:30"), - (20700, "2021-01-01T05:45:00+05:45"), - (16200, "2021-01-01T04:30:00+04:30"), - (34200, "2021-01-01T09:30:00+09:30"), - (-45900, "2020-12-31T11:15:00-12:45"), - ] { - let converted = dt.to_timezone(tz); - assert_eq!(converted.to_rfc3339(), expected, "failed for tz {tz}"); - assert!(converted.is_valid(), "invalid datetime for tz {tz}"); - assert_eq!( - converted.to_timestamp(), - dt.to_timestamp(), - "roundtrip failed for tz {tz}" - ); - } - } -} diff --git a/src/parsers/fields/id.rs b/src/parsers/fields/id.rs deleted file mode 100644 index 7ebf4b0..0000000 --- a/src/parsers/fields/id.rs +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use crate::{HeaderValue, parsers::MessageStream}; - -impl<'x> MessageStream<'x> { - pub fn parse_id(&mut self) -> HeaderValue<'x> { - let mut token_start: usize = 0; - let mut token_end: usize = 0; - let mut token_invalid_start: usize = 0; // Handle broken clients - let mut token_invalid_end: usize = 0; // Handle broken clients - let mut is_id_part = false; - let mut ids = Vec::new(); - - while let Some(&ch) = self.next() { - match ch { - b'\n' => { - if !self.try_next_is_space() { - return match ids.len() { - 1 => HeaderValue::Text(ids.pop().unwrap()), - 0 => { - if token_invalid_start > 0 { - HeaderValue::Text(String::from_utf8_lossy( - self.bytes(token_invalid_start - 1..token_invalid_end), - )) - } else { - HeaderValue::Empty - } - } - _ => HeaderValue::TextList(ids), - }; - } else { - continue; - } - } - b'<' => { - is_id_part = true; - continue; - } - b'>' => { - is_id_part = false; - if token_start > 0 { - ids.push(String::from_utf8_lossy( - self.bytes(token_start - 1..token_end), - )); - token_start = 0; - } else { - continue; - } - } - b' ' | b'\t' | b'\r' => continue, - _ => {} - } - if is_id_part { - if token_start == 0 { - token_start = self.offset(); - } - token_end = self.offset(); - } else { - if token_invalid_start == 0 { - token_invalid_start = self.offset(); - } - token_invalid_end = self.offset(); - } - } - - HeaderValue::Empty - } -} -#[cfg(test)] -mod tests { - use std::borrow::Cow; - - use crate::parsers::{MessageStream, fields::load_tests}; - - #[test] - fn parse_message_ids() { - for test in load_tests::<Option<Vec<Cow<'static, str>>>>("id.json") { - assert_eq!( - MessageStream::new(test.header.as_bytes()) - .parse_id() - .into_text_list(), - test.expected, - "failed for {:?}", - test.header - ); - } - } -} diff --git a/src/parsers/fields/list.rs b/src/parsers/fields/list.rs deleted file mode 100644 index 6d0c2ac..0000000 --- a/src/parsers/fields/list.rs +++ /dev/null @@ -1,132 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::borrow::Cow; - -use crate::{HeaderValue, parsers::MessageStream}; - -struct ListParser<'x> { - token_start: usize, - token_end: usize, - is_token_start: bool, - tokens: Vec<Cow<'x, str>>, - list: Vec<Cow<'x, str>>, -} - -impl<'x> ListParser<'x> { - fn add_token(&mut self, stream: &MessageStream<'x>, add_space: bool) { - if self.token_start > 0 { - if !self.tokens.is_empty() { - self.tokens.push(" ".into()); - } - self.tokens.push(String::from_utf8_lossy( - &stream.data[self.token_start - 1..self.token_end], - )); - - if add_space { - self.tokens.push(" ".into()); - } - - self.token_start = 0; - self.is_token_start = true; - } - } - - fn add_tokens_to_list(&mut self) { - if !self.tokens.is_empty() { - self.list.push(if self.tokens.len() == 1 { - self.tokens.pop().unwrap() - } else { - let value = self.tokens.concat(); - self.tokens.clear(); - value.into() - }); - } - } -} - -impl<'x> MessageStream<'x> { - pub fn parse_comma_separared(&mut self) -> HeaderValue<'x> { - let mut parser = ListParser { - token_start: 0, - token_end: 0, - is_token_start: true, - tokens: Vec::new(), - list: Vec::new(), - }; - - while let Some(ch) = self.next() { - match ch { - b'\n' => { - parser.add_token(self, false); - if !self.try_next_is_space() { - parser.add_tokens_to_list(); - - return match parser.list.len() { - 1 => HeaderValue::Text(parser.list.pop().unwrap()), - 0 => HeaderValue::Empty, - _ => HeaderValue::TextList(parser.list), - }; - } else { - continue; - } - } - b' ' | b'\t' => { - if !parser.is_token_start { - parser.is_token_start = true; - } - continue; - } - b'=' if parser.is_token_start && self.peek_char(b'?') => { - self.checkpoint(); - if let Some(token) = self.decode_rfc2047() { - parser.add_token(self, true); - parser.tokens.push(token.into()); - continue; - } - self.restore(); - } - b',' => { - parser.add_token(self, false); - parser.add_tokens_to_list(); - continue; - } - b'\r' => continue, - _ => (), - } - - if parser.is_token_start { - parser.is_token_start = false; - } - - if parser.token_start == 0 { - parser.token_start = self.offset(); - } - - parser.token_end = self.offset(); - } - - HeaderValue::Empty - } -} -#[cfg(test)] -mod tests { - use crate::parsers::{MessageStream, fields::load_tests}; - - #[test] - fn parse_comma_separated_text() { - for test in load_tests::<Vec<String>>("list.json") { - assert_eq!( - MessageStream::new(test.header.as_bytes()) - .parse_comma_separared() - .unwrap_text_list(), - test.expected, - "failed for {:?}", - test.header - ); - } - } -} diff --git a/src/parsers/fields/mod.rs b/src/parsers/fields/mod.rs deleted file mode 100644 index 299c059..0000000 --- a/src/parsers/fields/mod.rs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -pub mod address; -pub mod content_type; -pub mod date; -pub mod id; -pub mod list; -pub mod raw; -pub mod received; -pub mod thread; -pub mod unstructured; - -#[cfg(test)] -use serde::{Deserialize, Serialize}; - -#[cfg(test)] -#[derive(Debug, Serialize, Deserialize)] -pub struct Test<T> { - pub header: String, - pub expected: T, -} - -#[cfg(test)] -pub fn load_tests<T: serde::de::DeserializeOwned>(test_name: &str) -> Vec<Test<T>> { - serde_json::from_slice::<Vec<Test<T>>>( - &std::fs::read( - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("resources") - .join(test_name), - ) - .unwrap(), - ) - .unwrap() -} - -#[cfg(test)] -#[derive(Debug, Default)] -pub struct TestBuilder<T: Serialize> { - test: std::path::PathBuf, - tests: Vec<Test<T>>, -} - -#[cfg(test)] -impl<T: Serialize> TestBuilder<T> { - pub fn new(test: impl AsRef<str>) -> Self { - Self { - test: std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("resources") - .join(test.as_ref()), - tests: Vec::new(), - } - } - - pub fn add(&mut self, header: impl Into<String>, expected: T) { - self.tests.push(Test { - header: header.into(), - expected, - }); - } - - pub fn write(&self) { - std::fs::write( - &self.test, - serde_json::to_string_pretty(&self.tests).unwrap(), - ) - .unwrap(); - } -} diff --git a/src/parsers/fields/raw.rs b/src/parsers/fields/raw.rs deleted file mode 100644 index 2dc5df4..0000000 --- a/src/parsers/fields/raw.rs +++ /dev/null @@ -1,121 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use crate::{HeaderValue, parsers::MessageStream}; - -impl<'x> MessageStream<'x> { - pub fn parse_raw(&mut self) -> HeaderValue<'x> { - let mut token_start: usize = 0; - let mut token_end: usize = 0; - - while let Some(ch) = self.next() { - match ch { - b'\n' => { - if !self.try_next_is_space() { - break; - } else { - continue; - } - } - b' ' | b'\t' | b'\r' => continue, - _ => (), - } - - if token_start == 0 { - token_start = self.offset(); - } - - token_end = self.offset(); - } - - if token_start > 0 { - HeaderValue::Text(String::from_utf8_lossy( - self.bytes(token_start - 1..token_end), - )) - } else { - HeaderValue::Empty - } - } - - pub fn parse_and_ignore(&mut self) { - while let Some(&ch) = self.next() { - if ch == b'\n' && !self.try_next_is_space() { - break; - } - } - } -} - -#[cfg(test)] -mod tests { - use crate::{MessageParser, parsers::MessageStream}; - - #[test] - fn parse_raw_text() { - let inputs = [ - ("Saying Hello\nMessage-Id", "Saying Hello"), - ("Re: Saying Hello\r\n \r\nFrom:", "Re: Saying Hello"), - ( - concat!( - " from x.y.test\n by example.net\n via TCP\n", - " with ESMTP\n id ABC12345\n ", - "for <mary@example.net>; 21 Nov 1997 10:05:43 -0600\n" - ), - concat!( - "from x.y.test\n by example.net\n via TCP\n", - " with ESMTP\n id ABC12345\n ", - "for <mary@example.net>; 21 Nov 1997 10:05:43 -0600" - ), - ), - ("Re: Saying Hello", "Re: Saying Hello"), // No newline test - ]; - - for (input, expected) in inputs { - assert_eq!( - MessageStream::new(input.as_bytes()) - .parse_raw() - .unwrap_text(), - expected, - "Failed for '{:?}'", - input - ); - } - } - - #[test] - fn ordered_raw_headers() { - let input = br#"From: Art Vandelay <art@vandelay.com> -To: jane@example.com -Date: Sat, 20 Nov 2021 14:22:01 -0800 -Subject: Why not both importing AND exporting? =?utf-8?b?4pi6?= -Content-Type: multipart/mixed; boundary="festivus"; - -Here's a message body. -"#; - let message = MessageParser::default().parse(input).unwrap(); - let mut iter = message.headers_raw(); - assert_eq!( - iter.next().unwrap(), - ("From", " Art Vandelay <art@vandelay.com>\n") - ); - assert_eq!(iter.next().unwrap(), ("To", " jane@example.com\n")); - assert_eq!( - iter.next().unwrap(), - ("Date", " Sat, 20 Nov 2021 14:22:01 -0800\n") - ); - assert_eq!( - iter.next().unwrap(), - ( - "Subject", - " Why not both importing AND exporting? =?utf-8?b?4pi6?=\n" - ) - ); - assert_eq!( - iter.next().unwrap(), - ("Content-Type", " multipart/mixed; boundary=\"festivus\";\n") - ); - } -} diff --git a/src/parsers/fields/received.rs b/src/parsers/fields/received.rs deleted file mode 100644 index 1f0f7c4..0000000 --- a/src/parsers/fields/received.rs +++ /dev/null @@ -1,858 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use crate::{ - DateTime, Greeting, HeaderValue, Host, Protocol, Received, TlsVersion, parsers::MessageStream, -}; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Token { - BracketOpen, - BracketClose, - AngleOpen, - AngleClose, - ParenthesisOpen, - ParenthesisClose, - Semicolon, - Colon, - Equal, - Slash, - Quote, - Comma, - IpAddr(IpAddr), - Integer(i64), - Text, - Domain, - Email, - Month(Month), - Protocol(Protocol), - Greeting(Greeting), - TlsVersion(TlsVersion), - Cipher, - By, - For, - From, - Id, - Via, - With, - Ident, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct TokenData<'x> { - token: Token, - text: &'x str, - comment_depth: u32, - bracket_depth: u32, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Month { - Jan, - Feb, - Mar, - Apr, - May, - Jun, - Jul, - Aug, - Sep, - Oct, - Nov, - Dec, -} - -struct Tokenizer<'x, 'y> { - stream: &'y mut MessageStream<'x>, - next_token: Option<TokenData<'x>>, - eof: bool, - in_quote: bool, - bracket_depth: u32, - comment_depth: u32, - in_date: bool, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum State { - From, - By, - For, - Id, - With, - Via, - Date, - None, -} - -impl<'x> MessageStream<'x> { - pub fn parse_received(&mut self) -> HeaderValue<'x> { - //let c = print!("-> {}", std::str::from_utf8(self.data).unwrap()); - - let mut tokenizer = Tokenizer::new(self).peekable(); - let mut received = Received::default(); - - let mut state = State::None; - let mut date = [i64::MAX; 7]; - let mut date_part = date.iter_mut(); - - while let Some(token) = tokenizer.next() { - match token.token { - Token::From if received.from.is_none() => { - // Try obtaining hostname - while let Some(token) = tokenizer.peek() { - match token.token { - Token::BracketOpen => { - tokenizer.next(); - } - Token::IpAddr(ip) => { - tokenizer.next(); - received.from = Some(Host::IpAddr(ip)); - break; - } - _ => { - if !token.token.is_separator() { - received.from = - Some(Host::Name(tokenizer.next().unwrap().text.into())); - } - break; - } - } - } - state = State::From; - } - Token::By if token.comment_depth == 0 => { - // Try obtaining hostname - while let Some(token) = tokenizer.peek() { - match token.token { - Token::BracketOpen | Token::AngleOpen => { - tokenizer.next(); - } - Token::IpAddr(ip) => { - tokenizer.next(); - received.by = Some(Host::IpAddr(ip)); - break; - } - _ => { - if !token.token.is_separator() { - received.by = - Some(Host::Name(tokenizer.next().unwrap().text.into())); - } - break; - } - } - } - state = State::By; - } - Token::For if token.comment_depth == 0 => { - while let Some(token) = tokenizer.peek() { - match token.token { - Token::Equal | Token::AngleOpen => { - tokenizer.next(); - } - Token::Email => { - received.for_ = Some(tokenizer.next().unwrap().text.into()); - break; - } - _ => { - break; - } - } - } - state = State::For; - } - Token::Semicolon if token.comment_depth == 0 => { - state = State::Date; - } - Token::Id if token.comment_depth == 0 => { - while let Some(token) = tokenizer.peek() { - match token.token { - Token::Equal | Token::AngleOpen | Token::BracketOpen | Token::Colon => { - tokenizer.next(); - } - _ => { - if !token.token.is_separator() { - received.id = Some(tokenizer.next().unwrap().text.into()); - } - break; - } - } - } - state = State::Id; - } - Token::With if token.comment_depth == 0 => { - while let Some(token) = tokenizer.peek() { - match token.token { - Token::Protocol(proto) => { - tokenizer.next(); - received.with = Some(proto); - break; - } - Token::Semicolon - | Token::TlsVersion(_) - | Token::By - | Token::For - | Token::From - | Token::Id - | Token::Via - | Token::With => { - break; - } - _ => { - tokenizer.next(); - } - } - } - state = State::With; - } - Token::Via if token.comment_depth == 0 => { - while let Some(token) = tokenizer.peek() { - match token.token { - Token::Equal => { - tokenizer.next(); - } - _ => { - if !token.token.is_separator() { - received.via = Some(tokenizer.next().unwrap().text.into()); - } - break; - } - } - } - state = State::Via; - } - Token::Ident if token.comment_depth > 0 => { - while let Some(token) = tokenizer.peek() { - match token.token { - Token::Equal | Token::AngleOpen | Token::BracketOpen | Token::Colon => { - tokenizer.next(); - } - _ => { - if !token.token.is_separator() { - received.ident = Some(tokenizer.next().unwrap().text.into()); - } - break; - } - } - } - } - Token::Greeting(greeting) if state == State::From && token.comment_depth > 0 => { - // Try obtaining hostname - received.helo_cmd = Some(greeting); - while let Some(token) = tokenizer.peek() { - match token.token { - Token::Equal | Token::BracketOpen | Token::Colon => { - tokenizer.next(); - } - Token::IpAddr(ip) => { - tokenizer.next(); - received.helo = Some(Host::IpAddr(ip)); - break; - } - _ => { - if !token.token.is_separator() { - received.helo = - Some(Host::Name(tokenizer.next().unwrap().text.into())); - } - break; - } - } - } - } - Token::IpAddr(ip) - if state == State::From - && (token.bracket_depth > 0 - || (token.comment_depth > 0 && received.from_ip.is_none())) => - { - received.from_ip = Some(ip); - } - Token::Domain if state == State::From && token.comment_depth > 0 => { - received.from_iprev = Some(token.text.into()); - } - Token::Email if state == State::From => { - received.ident = - Some(token.text.strip_suffix('@').unwrap_or(token.text).into()); - } - Token::Integer(num) if state == State::Date => { - if let Some(part) = date_part.next() { - *part = num; - } - } - Token::Month(month) if state == State::Date => { - if let Some(part) = date_part.next() { - *part = month.to_number(); - } - } - Token::Cipher if token.comment_depth > 0 || received.tls_cipher.is_none() => { - received.tls_cipher = Some(token.text.into()); - } - Token::TlsVersion(tls) - if token.comment_depth > 0 && received.tls_version.is_none() => - { - received.tls_version = Some(tls); - } - _ => (), - } - } - - if date[5] != i64::MAX { - let (tz, is_plus) = if date[6] != i64::MAX { - if date[6] < 0 { - (date[6].abs(), false) - } else { - (date[6], true) - } - } else { - (0, false) - }; - received.date = DateTime { - year: if (1..=99).contains(&date[2]) { - date[2] + 1900 - } else { - date[2] - } as u16, - month: date[1] as u8, - day: date[0] as u8, - hour: date[3] as u8, - minute: date[4] as u8, - second: date[5] as u8, - tz_hour: (tz / 100) as u8, - tz_minute: (tz % 100) as u8, - tz_before_gmt: !is_plus, - } - .into(); - } - - if received.from.is_some() - || received.from_ip.is_some() - || received.from_iprev.is_some() - || received.by.is_some() - || received.for_.is_some() - || received.with.is_some() - || received.tls_version.is_some() - || received.tls_cipher.is_some() - || received.id.is_some() - || received.ident.is_some() - || received.helo.is_some() - || received.helo_cmd.is_some() - || received.via.is_some() - || received.date.is_some() - { - HeaderValue::Received(Box::new(received)) - } else { - HeaderValue::Empty - } - } -} - -impl<'x> Iterator for Tokenizer<'x, '_> { - type Item = TokenData<'x>; - - fn next(&mut self) -> Option<Self::Item> { - if let Some(next_token) = self.next_token.take() { - return Some(next_token); - } else if self.eof { - return None; - } - let mut n_alpha = 0; // 1 - let mut n_digit = 0; // 2 - let mut n_hex = 0; // 3 - let mut n_dot = 0; // 4 - let mut n_at = 0; // 5 - let mut n_other = 0; // 6 - let mut n_colon = 0; // 7 - let mut n_plus = 0; // 8 - let mut n_minus = 0; // 9 - let mut n_utf = 0; // 10 - let mut n_uppercase = 0; - let mut n_underscore = 0; - - let mut n_total = 0; - - let mut hash: u128 = 0; - let mut hash_shift = 0; - - let comment_depth = self.comment_depth; - let bracket_depth = self.bracket_depth; - - let mut start_pos = self.stream.offset(); - let mut end_pos = start_pos; - - while let Some(ch) = self.stream.next() { - match ch { - b'0'..=b'9' => { - n_digit += 1; - if hash_shift < 128 { - hash |= (*ch as u128) << hash_shift; - hash_shift += 8; - } - } - b'a'..=b'f' => { - n_hex += 1; - if hash_shift < 128 { - hash |= (*ch as u128) << hash_shift; - hash_shift += 8; - } - } - b'g'..=b'z' => { - n_alpha += 1; - if hash_shift < 128 { - hash |= (*ch as u128) << hash_shift; - hash_shift += 8; - } - } - b'A'..=b'F' => { - n_hex += 1; - n_uppercase += 1; - if hash_shift < 128 { - hash |= ((*ch - b'A' + b'a') as u128) << hash_shift; - hash_shift += 8; - } - } - b'G'..=b'Z' => { - n_alpha += 1; - n_uppercase += 1; - if hash_shift < 128 { - hash |= ((*ch - b'A' + b'a') as u128) << hash_shift; - hash_shift += 8; - } - } - b'@' => { - n_at += 1; - } - b'.' => { - n_dot += 1; - } - b'+' => { - n_plus += 1; - } - b'-' => { - n_minus += 1; - } - b'\n' => { - if !self.stream.try_next_is_space() { - self.eof = true; - break; - } else if n_total > 0 { - break; - } else { - start_pos = self.stream.offset(); - end_pos = start_pos; - continue; - } - } - b'(' => { - if !self.in_quote { - self.comment_depth = self.comment_depth.saturating_add(1); - } - self.next_token = Some(Token::ParenthesisOpen.into()); - break; - } - b')' => { - if !self.in_quote { - self.comment_depth = self.comment_depth.saturating_sub(1); - } - self.next_token = Some(Token::ParenthesisClose.into()); - break; - } - b'<' => { - self.next_token = Some(Token::AngleOpen.into()); - break; - } - b'>' => { - self.next_token = Some(Token::AngleClose.into()); - break; - } - b'[' => { - if !self.in_quote { - self.bracket_depth = self.comment_depth.saturating_add(1); - } - self.next_token = Some(Token::BracketOpen.into()); - break; - } - b']' => { - if !self.in_quote { - self.bracket_depth = self.comment_depth.saturating_sub(1); - } - self.next_token = Some(Token::BracketClose.into()); - break; - } - b':' => { - // The current token might an IPv6 address - if self.in_date - || n_at > 0 - || n_dot > 0 - || n_alpha > 0 - || n_other > 0 - || n_plus > 0 - || n_minus > 0 - || n_utf > 0 - || n_colon == 7 - { - self.next_token = Some(Token::Colon.into()); - break; - } else { - n_colon += 1; - } - } - b'=' => { - self.next_token = Some(Token::Equal.into()); - break; - } - b';' => { - if self.comment_depth == 0 { - self.in_date = true; - } - self.next_token = Some(Token::Semicolon.into()); - break; - } - b'/' => { - self.next_token = Some(Token::Slash.into()); - break; - } - b'"' => { - self.in_quote = !self.in_quote; - self.next_token = Some(Token::Quote.into()); - break; - } - b',' => { - self.next_token = Some(Token::Comma.into()); - break; - } - b' ' | b'\t' | b'\r' => { - if n_total > 0 { - break; - } else { - start_pos += 1; - end_pos = start_pos; - continue; - } - } - 0x7f..=u8::MAX => { - n_utf += 1; - } - b'_' => { - n_underscore += 1; - n_other += 1; - } - _ => { - n_other += 1; - } - } - - n_total += 1; - end_pos = self.stream.offset(); - } - - if n_total == 0 { - return self.next_token.take(); - } - - let text = std::str::from_utf8(self.stream.bytes(start_pos..end_pos)).unwrap_or_default(); - - let token = match ( - n_alpha, n_digit, n_hex, n_dot, n_at, n_other, n_colon, n_plus, n_minus, n_utf, hash, - ) { - (0, 4..=12, 0, 3, 0, 0, 0, 0, 0, 0, _) => { - // IPv4 address - text.parse::<Ipv4Addr>() - .map(|ip| Token::IpAddr(IpAddr::V4(ip))) - .unwrap_or(Token::Text) - } - (0, _, 1..=32, 0, 0, 0, 2.., 0, 0, 0, _) - | (0, 1..=32, _, 0, 0, 0, 2.., 0, 0, 0, _) - | (0, 4..=12, 4, 3, 0, 0, 3, 0, 0, 0, _) => { - // IPv6 address - text.parse::<Ipv6Addr>() - .map(|ip| Token::IpAddr(IpAddr::V6(ip))) - .unwrap_or(Token::Text) - } - (0, 1.., 0, 0, 0, 0, 0, 0, 0, 0, _) - | (0, 1.., 0, 0, 0, 0, 0, 0, 1, 0, _) - | (0, 1.., 0, 0, 0, 0, 0, 1, 0, 0, _) => { - // Integer - text.parse::<i64>() - .map(Token::Integer) - .unwrap_or(Token::Text) - } - (1.., _, _, _, 1, _, _, _, _, _, _) | (_, _, 1.., _, 1, _, _, _, _, _, _) => { - // E-mail address - Token::Email - } - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x727061) => Token::Month(Month::Apr), - (4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x70746d7362) => Token::Protocol(Protocol::SMTP), - (1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x7962) => Token::By, - (0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0x636564) => Token::Month(Month::Dec), - (3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6f6c6865) => Token::Greeting(Greeting::Ehlo), - (4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x70746d7365) => Token::Protocol(Protocol::ESMTP), - (4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0x6170746d7365) => Token::Protocol(Protocol::ESMTPA), - (5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x7370746d7365) => Token::Protocol(Protocol::ESMTPS), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x726f66) => Token::For, - (3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6d6f7266) => Token::From, - (3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6f6c6568) => Token::Greeting(Greeting::Helo), - (4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x70747468) => Token::Protocol(Protocol::HTTP), - (7, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x7473657270747468) => Token::Protocol(Protocol::HTTP), - (1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6469) => Token::Id, - (3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x70616d69) => Token::Protocol(Protocol::IMAP), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6e616a) => Token::Month(Month::Jan), - (3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x6c756a) => Token::Month(Month::Jul), - (3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x6e756a) => Token::Month(Month::Jun), - (4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x6f6c686c) => Token::Greeting(Greeting::Lhlo), - (4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x70746d6c) => Token::Protocol(Protocol::LMTP), - (4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6170746d6c) => Token::Protocol(Protocol::LMTPA), - (3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0x6c61636f6c) => Token::Protocol(Protocol::Local), - (5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x70746d736c) => Token::Protocol(Protocol::LMTP), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x72616d) => Token::Month(Month::Mar), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x79616d) => Token::Month(Month::May), - (3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x766f6e) => Token::Month(Month::Nov), - (3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0x33706f70) => Token::Protocol(Protocol::POP3), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x706573) => Token::Month(Month::Sep), - (4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x70746d73) => Token::Protocol(Protocol::SMTP), - (4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6470746d73) => Token::Protocol(Protocol::SMTP), - (6, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x63767370746d73) => Token::Protocol(Protocol::SMTP), - (4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0x74656b636f73) => Token::Protocol(Protocol::Local), - (4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x6e69647473) => Token::Protocol(Protocol::Local), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x616976) => Token::Via, - (0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0x626566) => Token::Month(Month::Feb), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x677561) => Token::Month(Month::Aug), - (2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x74636f) => Token::Month(Month::Oct), - (4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x68746977) => Token::With, - (4, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x70746d7361) => Token::Protocol(Protocol::ESMTPA), - (5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7570747468) => Token::Protocol(Protocol::HTTP), - (5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7370747468) => Token::Protocol(Protocol::HTTPS), - (3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0x746e656469) => Token::Ident, - (5, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0x617370746d7365) => Token::Protocol(Protocol::ESMTPSA), - (5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7370746d6c) => Token::Protocol(Protocol::LMTPS), - (5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0x617370746d6c) => Token::Protocol(Protocol::LMTPSA), - (3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x736d6d) => Token::Protocol(Protocol::MMS), - (6, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0x70746d7338667475) => { - Token::Protocol(Protocol::UTF8SMTP) - } - (6, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x6170746d7338667475) => { - Token::Protocol(Protocol::UTF8SMTPA) - } - (7, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0x7370746d7338667475) => { - Token::Protocol(Protocol::UTF8SMTPS) - } - (7, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x617370746d7338667475) => { - Token::Protocol(Protocol::UTF8SMTPSA) - } - (6, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0x70746d6c38667475) => { - Token::Protocol(Protocol::UTF8LMTP) - } - (6, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x6170746d6c38667475) => { - Token::Protocol(Protocol::UTF8LMTPA) - } - (7, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0x7370746d6c38667475) => { - Token::Protocol(Protocol::UTF8LMTPS) - } - (7, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x617370746d6c38667475) => { - Token::Protocol(Protocol::UTF8LMTPSA) - } - (7, 0, 3, 0, 0, 0, 0, 0, _, 0, 0x70746d73656c61636f6c) => { - Token::Protocol(Protocol::ESMTP) - } - (8, 0, 3, 0, 0, 0, 0, 0, _, 0, 0x7370746d73656c61636f6c) => { - Token::Protocol(Protocol::ESMTPS) - } - (7, 0, 3, 0, 0, 0, 0, 0, _, 0, 0x70746d73626c61636f6c) => { - Token::Protocol(Protocol::SMTP) - } - (7, 0, 1, 0, 0, 0, 0, 0, _, 0, 0x736c7470746d7365) => Token::Protocol(Protocol::ESMTPS), - (3, 2, 0, _, 0, _, 0, 0, _, 0, 0x3031736c74) => Token::TlsVersion(TlsVersion::TLSv1_0), - (3, 2, 0, _, 0, _, 0, 0, _, 0, 0x3131736c74) => Token::TlsVersion(TlsVersion::TLSv1_1), - (3, 2, 0, _, 0, _, 0, 0, _, 0, 0x3231736c74) => Token::TlsVersion(TlsVersion::TLSv1_2), - (3, 2, 0, _, 0, _, 0, 0, _, 0, 0x3331736c74) => Token::TlsVersion(TlsVersion::TLSv1_3), - (4, 2, 0, _, 0, _, 0, 0, 0, 0, 0x303176736c74) => { - Token::TlsVersion(TlsVersion::TLSv1_0) - } - (4, 2, 0, _, 0, _, 0, 0, 0, 0, 0x313176736c74) => { - Token::TlsVersion(TlsVersion::TLSv1_1) - } - (4, 2, 0, _, 0, _, 0, 0, 0, 0, 0x323176736c74) => { - Token::TlsVersion(TlsVersion::TLSv1_2) - } - (4, 2, 0, _, 0, _, 0, 0, 0, 0, 0x333176736c74) => { - Token::TlsVersion(TlsVersion::TLSv1_3) - } - (3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0x326c7373) => Token::TlsVersion(TlsVersion::SSLv2), - (3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0x336c7373) => Token::TlsVersion(TlsVersion::SSLv3), - (4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0x32766c7373) => Token::TlsVersion(TlsVersion::SSLv2), - (4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0x33766c7373) => Token::TlsVersion(TlsVersion::SSLv3), - (3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0x31736c74) => Token::TlsVersion(TlsVersion::TLSv1_0), - (4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0x3176736c74) => Token::TlsVersion(TlsVersion::TLSv1_0), - (4, 2, 1, _, 0, _, 0, 0, 0, 0, 0x303176736c7464) => { - Token::TlsVersion(TlsVersion::DTLSv1_0) - } - (4, 2, 1, _, 0, _, 0, 0, 0, 0, 0x323176736c7464) => { - Token::TlsVersion(TlsVersion::DTLSv1_2) - } - (4, 2, 1, _, 0, _, 0, 0, 0, 0, 0x333176736c7464) => { - Token::TlsVersion(TlsVersion::DTLSv1_3) - } - (3, 2, 1, _, 0, _, 0, 0, 0, 0, 0x3031736c7464) => { - Token::TlsVersion(TlsVersion::DTLSv1_0) - } - (3, 2, 1, _, 0, _, 0, 0, 0, 0, 0x3231736c7464) => { - Token::TlsVersion(TlsVersion::DTLSv1_2) - } - (3, 2, 1, _, 0, _, 0, 0, 0, 0, 0x3331736c7464) => { - Token::TlsVersion(TlsVersion::DTLSv1_3) - } - (1.., _, _, 1.., 0, 0, 0, 0, _, _, _) | (_, _, 1.., 1.., 0, 0, 0, 0, _, _, _) => { - // Domain name - Token::Domain - } - _ => { - // Try ciphersuite - if n_alpha + n_hex == n_uppercase - && n_total > 6 - && (n_underscore > 0 || n_minus > 0) - && n_digit > 0 - && n_dot == 0 - && n_at == 0 - && n_plus == 0 - && (n_other == 0 || n_other == n_underscore) - && n_colon == 0 - && n_utf == 0 - && [ - 0x617372, 0x646365, 0x646365, 0x656864, 0x6b7370, 0x707273, 0x736561, - 0x736564, 0x736c74, - ] - .contains(&(hash & 0xffffff)) - { - Token::Cipher - } else { - Token::Text - } - } - }; - - TokenData { - text, - token, - comment_depth, - bracket_depth, - } - .into() - } -} - -impl<'x, 'y> Tokenizer<'x, 'y> { - fn new(stream: &'y mut MessageStream<'x>) -> Self { - Self { - stream, - next_token: None, - eof: false, - in_quote: false, - bracket_depth: 0, - comment_depth: 0, - in_date: false, - } - } -} - -impl From<Token> for TokenData<'_> { - fn from(token: Token) -> Self { - Self { - token, - text: "", - comment_depth: 0, - bracket_depth: 0, - } - } -} - -impl Month { - fn to_number(self) -> i64 { - match self { - Month::Jan => 1, - Month::Feb => 2, - Month::Mar => 3, - Month::Apr => 4, - Month::May => 5, - Month::Jun => 6, - Month::Jul => 7, - Month::Aug => 8, - Month::Sep => 9, - Month::Oct => 10, - Month::Nov => 11, - Month::Dec => 12, - } - } -} - -impl Token { - fn is_separator(&self) -> bool { - matches!( - self, - Token::BracketOpen - | Token::BracketClose - | Token::AngleOpen - | Token::AngleClose - | Token::ParenthesisOpen - | Token::ParenthesisClose - | Token::Semicolon - | Token::Colon - | Token::Equal - | Token::Slash - | Token::Quote - | Token::Comma - ) - } -} - -#[cfg(test)] -mod tests { - - use crate::{ - MessageParser, - parsers::{MessageStream, fields::load_tests}, - }; - - #[test] - fn parse_received() { - for test in load_tests("received.json") { - assert_eq!( - MessageStream::new(test.header.as_bytes()) - .parse_received() - .unwrap_received(), - test.expected, - "failed for {:?}", - test.header - ); - } - } - - #[test] - fn parse_received_truncated_fold() { - for message in [ - &b"Received:\n\t"[..], - b"Received:\r\n ", - b"Received: x\r\n ", - b"Received: x\r\n\t", - b"Received: x\n ", - b"Received: x\n\t", - b"Received: x\r\n ", - b"Received: x\r\n \t", - b"Received: x\r\n \t ", - b"Received: x\r\n \r", - b"Received: x\r\n \r\n", - b"Received: x\r\n \r\nbody", - b"Received: x\r\n y\r\n ", - b"Received: x;\r\n ", - b"To: a@b\r\nReceived: x\r\n ", - b"Received: from x (y)\r\n\t", - b"Received: from x by y;\r\n\t", - b"Received: ", - b"Received:", - b"Received: x", - ] { - MessageParser::default().parse(message); - MessageParser::default().parse_headers(message); - } - } -} diff --git a/src/parsers/fields/unstructured.rs b/src/parsers/fields/unstructured.rs deleted file mode 100644 index 96e7a49..0000000 --- a/src/parsers/fields/unstructured.rs +++ /dev/null @@ -1,108 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::borrow::Cow; - -use crate::{HeaderValue, parsers::MessageStream}; -struct UnstructuredParser<'x> { - token_start: usize, - token_end: usize, - tokens: Vec<Cow<'x, str>>, - last_is_encoded: bool, -} - -impl<'x> UnstructuredParser<'x> { - fn add_token(&mut self, stream: &MessageStream<'x>) { - if self.token_start > 0 { - if !self.tokens.is_empty() { - self.tokens.push(" ".into()); - } - self.tokens.push(String::from_utf8_lossy( - stream.bytes(self.token_start - 1..self.token_end), - )); - - self.token_start = 0; - self.last_is_encoded = false; - } - } - - fn add_rfc2047(&mut self, token: String) { - if !self.last_is_encoded { - self.tokens.push(" ".into()); - } - self.tokens.push(token.into()); - self.last_is_encoded = true; - } -} - -impl<'x> MessageStream<'x> { - pub fn parse_unstructured(&mut self) -> HeaderValue<'x> { - let mut parser = UnstructuredParser { - token_start: 0, - token_end: 0, - tokens: Vec::new(), - last_is_encoded: true, - }; - - while let Some(ch) = self.next() { - match ch { - b'\n' => { - parser.add_token(self); - - if !self.try_next_is_space() { - return match parser.tokens.len() { - 1 => HeaderValue::Text(parser.tokens.pop().unwrap()), - 0 => HeaderValue::Empty, - _ => HeaderValue::Text(parser.tokens.concat().into()), - }; - } else { - continue; - } - } - b' ' | b'\t' | b'\r' => { - continue; - } - b'=' if self.peek_char(b'?') => { - self.checkpoint(); - if let Some(token) = self.decode_rfc2047() { - parser.add_token(self); - parser.add_rfc2047(token); - continue; - } - self.restore(); - } - _ => (), - } - - if parser.token_start == 0 { - parser.token_start = self.offset(); - } - - parser.token_end = self.offset(); - } - - HeaderValue::Empty - } -} - -#[cfg(test)] -mod tests { - use crate::parsers::{MessageStream, fields::load_tests}; - - #[test] - fn parse_unstructured() { - for test in load_tests::<String>("unstructured.json") { - assert_eq!( - MessageStream::new(test.header.as_bytes()) - .parse_unstructured() - .unwrap_text(), - test.expected, - "failed for {:?}", - test.header - ); - } - } -} diff --git a/src/parsers/header.rs b/src/parsers/header.rs deleted file mode 100644 index ff31c76..0000000 --- a/src/parsers/header.rs +++ /dev/null @@ -1,215 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use super::MessageStream; -use crate::{Header, HeaderName, MessageParser, header_map}; -use std::borrow::Cow; -const MAX_HEADER_NAME_LEN: usize = 34; - -impl<'x> MessageStream<'x> { - pub fn parse_headers(&mut self, conf: &MessageParser, headers: &mut Vec<Header<'x>>) -> bool { - loop { - loop { - match self.peek() { - Some(b'\n') => { - self.next(); - return true; - } - None => return false, - Some(ch) if !ch.is_ascii_whitespace() => { - break; - } - _ => { - self.next(); - } - } - } - - let offset_field = self.offset(); - - if let Some(header_name) = self.parse_header_name() { - let from_offset = self.offset(); - let value = if conf.header_map.is_empty() { - match &header_name { - HeaderName::Subject - | HeaderName::Comments - | HeaderName::ContentDescription - | HeaderName::ContentLocation - | HeaderName::ContentTransferEncoding => self.parse_unstructured(), - HeaderName::From - | HeaderName::To - | HeaderName::Cc - | HeaderName::Bcc - | HeaderName::ReplyTo - | HeaderName::Sender - | HeaderName::ResentTo - | HeaderName::ResentFrom - | HeaderName::ResentBcc - | HeaderName::ResentCc - | HeaderName::ResentSender - | HeaderName::ListArchive - | HeaderName::ListHelp - | HeaderName::ListId - | HeaderName::ListOwner - | HeaderName::ListPost - | HeaderName::ListSubscribe - | HeaderName::ListUnsubscribe => self.parse_address(), - HeaderName::Date | HeaderName::ResentDate => self.parse_date(), - HeaderName::MessageId - | HeaderName::References - | HeaderName::InReplyTo - | HeaderName::ReturnPath - | HeaderName::ContentId - | HeaderName::ResentMessageId => self.parse_id(), - HeaderName::Keywords | HeaderName::ContentLanguage => { - self.parse_comma_separared() - } - HeaderName::Received => self.parse_received(), - HeaderName::MimeVersion => self.parse_raw(), - HeaderName::ContentType | HeaderName::ContentDisposition => { - self.parse_content_type() - } - _ => self.parse_raw(), - } - } else { - (conf - .header_map - .get(&header_name) - .unwrap_or(&conf.def_hdr_parse_fnc))(self) - }; - - headers.push(Header { - name: header_name, - value, - offset_field: offset_field as u32, - offset_start: from_offset as u32, - offset_end: self.offset() as u32, - }); - } else if self.is_eof() { - return false; - } - } - } - - pub fn parse_header_name(&mut self) -> Option<HeaderName<'x>> { - let mut token_start: usize = 0; - let mut token_end: usize = 0; - let mut token_len: usize = 0; - - let mut header = [0u8; MAX_HEADER_NAME_LEN]; - - while let Some(&ch) = self.next() { - match ch { - b':' => { - if token_start != 0 { - break; - } - } - b'\n' => { - return None; - } - _ => { - if !ch.is_ascii_whitespace() { - if token_start == 0 { - token_start = self.offset(); - token_end = token_start; - } else { - token_end = self.offset(); - } - - if let Some(header) = header.get_mut(token_len) { - *header = ch.to_ascii_lowercase(); - } - token_len += 1; - } - } - } - } - - if token_start != 0 { - header - .get(..token_len) - .and_then(header_map) - .unwrap_or_else(|| { - HeaderName::Other(String::from_utf8_lossy( - self.bytes(token_start - 1..token_end), - )) - }) - .into() - } else { - None - } - } -} - -impl<'x> HeaderName<'x> { - /// Parse a header name - pub fn parse(data: impl Into<Cow<'x, str>>) -> Option<HeaderName<'x>> { - let data = data.into(); - - if !data.is_empty() { - let mut data_lc = String::with_capacity(data.len()); - for ch in data.chars() { - match ch { - 'A'..='Z' => data_lc.push(ch.to_ascii_lowercase()), - 'a'..='z' | '0'..='9' | '-' | '_' => data_lc.push(ch), - _ => return None, - } - } - header_map(data_lc.as_bytes()) - .unwrap_or(HeaderName::Other(data)) - .into() - } else { - None - } - } -} - -#[cfg(test)] -mod tests { - use crate::{HeaderName, parsers::MessageStream}; - - #[test] - fn header_name_parse() { - let inputs = [ - ("From: ", HeaderName::From), - ("receiVED: ", HeaderName::Received), - (" subject : ", HeaderName::Subject), - ( - "X-Custom-Field : ", - HeaderName::Other("X-Custom-Field".into()), - ), - (" T : ", HeaderName::Other("T".into())), - ("mal formed: ", HeaderName::Other("mal formed".into())), - ("MIME-version : ", HeaderName::MimeVersion), - ("Delivered-To: ", HeaderName::DeliveredTo), - ("archived-AT: ", HeaderName::ArchivedAt), - ("X-Face: ", HeaderName::Other("X-Face".into())), - ( - "Disposition-Notification-Options: ", - HeaderName::DispositionNotificationOptions, - ), - ( - "MMHS-Other-Recipients-Indicator-To: ", - HeaderName::MmhsOtherRecipientsIndicatorTo, - ), - ( - "Original-Encoded-Information-Types-Extra: ", - HeaderName::Other("Original-Encoded-Information-Types-Extra".into()), - ), - ]; - - for (input, expected_result) in inputs { - assert_eq!( - expected_result, - MessageStream::new(input.as_bytes()) - .parse_header_name() - .unwrap(), - "Failed to parse '{input:?}'", - ); - } - } -} diff --git a/src/parsers/message.rs b/src/parsers/message.rs deleted file mode 100644 index c4b3c46..0000000 --- a/src/parsers/message.rs +++ /dev/null @@ -1,678 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::borrow::Cow; - -use crate::{ - ContentType, Encoding, GetHeader, HeaderName, HeaderValue, Message, MessageParser, MessagePart, - MessagePartId, PartType, - decoders::{DecodeFnc, charsets::map::charset_decoder}, -}; - -use super::MessageStream; - -const MAX_NESTED_ENCODED: usize = 3; - -#[derive(Debug, PartialEq, Default)] -enum MimeType { - MultipartMixed, - MultipartAlternative, - MultipartRelated, - MultipartDigest, - TextPlain, - TextHtml, - TextOther, - Inline, - #[default] - Message, - Other, -} - -#[inline(always)] -fn mime_type( - content_type: Option<&ContentType<'_>>, - parent_content_type: &MimeType, -) -> (bool, bool, bool, MimeType) { - if let Some(content_type) = content_type { - match content_type.ctype() { - "multipart" => ( - true, - false, - false, - match content_type.subtype() { - Some("mixed") => MimeType::MultipartMixed, - Some("alternative") => MimeType::MultipartAlternative, - Some("related") => MimeType::MultipartRelated, - Some("digest") => MimeType::MultipartDigest, - _ => MimeType::Other, - }, - ), - "text" => match content_type.subtype() { - Some("plain") => (false, true, true, MimeType::TextPlain), - Some("html") => (false, true, true, MimeType::TextHtml), - _ => (false, false, true, MimeType::TextOther), - }, - "image" | "audio" | "video" => (false, true, false, MimeType::Inline), - "message" if [Some("rfc822"), Some("global")].contains(&content_type.subtype()) => { - (false, false, false, MimeType::Message) - } - _ => (false, false, false, MimeType::Other), - } - } else if let MimeType::MultipartDigest = parent_content_type { - (false, false, false, MimeType::Message) - } else { - (false, true, true, MimeType::TextPlain) - } -} - -#[derive(Default, Debug)] -struct MessageParserState { - mime_type: MimeType, - mime_boundary: Option<Vec<u8>>, - in_alternative: bool, - parts: usize, - html_parts: usize, - text_parts: usize, - need_html_body: bool, - need_text_body: bool, - part_id: MessagePartId, - sub_part_ids: Vec<MessagePartId>, - offset_header: usize, - offset_body: usize, - offset_end: usize, -} - -impl MessageParserState { - fn new() -> MessageParserState { - MessageParserState { - mime_type: MimeType::Message, - mime_boundary: None, - in_alternative: false, - parts: 0, - html_parts: 0, - text_parts: 0, - need_text_body: true, - need_html_body: true, - ..Default::default() - } - } -} - -impl MessageParser { - /// Parses a byte slice containing the RFC5322 raw message and returns a - /// `Message` struct. - /// - /// This function never panics, a best-effort is made to parse the message and - /// if no headers are found None is returned. - /// - pub fn parse<'x>(&self, raw_message: &'x (impl AsRef<[u8]> + ?Sized)) -> Option<Message<'x>> { - self.parse_(raw_message.as_ref(), MAX_NESTED_ENCODED, false) - } - - /// Parses a byte slice containing the RFC5322 raw message and returns a - /// `Message` struct containing only the headers. - pub fn parse_headers<'x>( - &self, - raw_message: &'x (impl AsRef<[u8]> + ?Sized), - ) -> Option<Message<'x>> { - self.parse_(raw_message.as_ref(), MAX_NESTED_ENCODED, true) - } - - fn parse_<'x>( - &self, - raw_message: &'x [u8], - depth: usize, - skip_body: bool, - ) -> Option<Message<'x>> { - let mut stream = MessageStream::new(raw_message); - - let mut message = Message::new(); - - let mut state = MessageParserState::new(); - let mut state_stack = Vec::with_capacity(4); - - let mut part_headers = Vec::new(); - - 'outer: loop { - // Parse headers - state.offset_header = stream.offset(); - if !stream.parse_headers(self, &mut part_headers) { - break; - } - state.offset_body = stream.offset(); - if skip_body { - break; - } - - state.parts += 1; - state.sub_part_ids.push(message.parts.len() as u32); - - let content_type = part_headers - .header_value(&HeaderName::ContentType) - .and_then(|c| c.as_content_type()); - - let (is_multipart, mut is_inline, mut is_text, mut mime_type) = - mime_type(content_type, &state.mime_type); - - if is_multipart - && let Some(mime_boundary) = content_type.and_then(|f| f.attribute("boundary")) - { - if stream.seek_next_part(mime_boundary.as_bytes()) { - let part_id = message.parts.len(); - let new_state = MessageParserState { - in_alternative: state.in_alternative - || mime_type == MimeType::MultipartAlternative, - mime_type, - mime_boundary: mime_boundary.as_bytes().to_vec().into(), - html_parts: message.html_body.len(), - text_parts: message.text_body.len(), - need_html_body: state.need_html_body, - need_text_body: state.need_text_body, - part_id: part_id as u32, - ..Default::default() - }; - //add_missing_type(&mut part_header, "text".into(), "plain".into()); - message.parts.push(MessagePart { - headers: std::mem::take(&mut part_headers), - offset_header: state.offset_header as u32, - offset_body: state.offset_body as u32, - offset_end: 0, - is_encoding_problem: false, - encoding: Encoding::None, - body: PartType::default(), - }); - state_stack.push((state, None)); - state = new_state; - stream.skip_crlf(); - continue; - } else { - mime_type = MimeType::TextOther; - is_text = true; - } - } - - let (mut encoding, decode_fnc): (Encoding, DecodeFnc<'_>) = match part_headers - .header_value(&HeaderName::ContentTransferEncoding) - { - Some(HeaderValue::Text(encoding)) if encoding.eq_ignore_ascii_case("base64") => { - (Encoding::Base64, MessageStream::decode_base64_mime) - } - Some(HeaderValue::Text(encoding)) - if encoding.eq_ignore_ascii_case("quoted-printable") => - { - ( - Encoding::QuotedPrintable, - MessageStream::decode_quoted_printable_mime, - ) - } - _ => (Encoding::None, MessageStream::mime_part), - }; - - if mime_type == MimeType::Message && encoding == Encoding::None { - let new_state = MessageParserState { - mime_type: MimeType::Message, - mime_boundary: state.mime_boundary.take(), - need_html_body: true, - need_text_body: true, - part_id: message.parts.len() as u32, - ..Default::default() - }; - message.attachments.push(message.parts.len() as u32); - message.parts.push(MessagePart { - headers: std::mem::take(&mut part_headers), - encoding, - is_encoding_problem: false, - offset_header: state.offset_header as u32, - offset_body: state.offset_body as u32, - offset_end: 0, - body: PartType::default(), // Temp value, will be replaced later. - }); - state_stack.push((state, message.into())); - message = Message::new(); - state = new_state; - continue; - } - - let (offset_end, mut bytes) = decode_fnc( - &mut stream, - state.mime_boundary.as_deref().unwrap_or(&b""[..]), - ); - - // Attempt to recover contents of an invalid message - let mut is_encoding_problem = offset_end == usize::MAX; - if is_encoding_problem { - encoding = Encoding::None; - if mime_type != MimeType::TextPlain { - mime_type = MimeType::TextOther; - } - is_inline = false; - is_text = true; - - let (offset_end, boundary_found) = - stream.seek_part_end(state.mime_boundary.as_deref()); - state.offset_end = offset_end; - bytes = stream.data[state.offset_body..state.offset_end].into(); - - if !boundary_found { - state.mime_boundary = None; - } - } else { - state.offset_end = offset_end; - } - - let body_part = if mime_type != MimeType::Message { - let is_inline = is_inline - && part_headers - .header_value(&HeaderName::ContentDisposition) - .is_none_or(|d| !d.as_content_type().is_some_and(|ct| ct.is_attachment())) - && (state.parts == 1 - || state.mime_type != MimeType::MultipartRelated - && (mime_type == MimeType::Inline - || content_type.is_none_or(|c| !c.has_attribute("name")))); - - // if message consists of single text/plain part, classify as text regardless - // of encoding issues: see malformed/018.eml - let is_inline = is_inline - || state.parts == 1 - && state.mime_type == MimeType::Message - && mime_type == MimeType::TextPlain - && is_encoding_problem; - - let (add_to_html, add_to_text) = - if let MimeType::MultipartAlternative = state.mime_type { - match mime_type { - MimeType::TextHtml => (true, false), - MimeType::TextPlain => (false, true), - _ => (false, false), - } - } else if is_inline { - if state.in_alternative && (state.need_text_body || state.need_html_body) { - match mime_type { - MimeType::TextHtml => { - state.need_text_body = false; - } - MimeType::TextPlain => { - state.need_html_body = false; - } - _ => (), - } - } - (state.need_html_body, state.need_text_body) - } else { - (false, false) - }; - - if add_to_html { - message.html_body.push(message.parts.len() as u32); - } - if add_to_text { - message.text_body.push(message.parts.len() as u32); - } - - if is_text { - let text = match ( - bytes, - content_type.and_then(|ct| { - ct.attribute("charset") - .and_then(|c| charset_decoder(c.as_bytes())) - }), - ) { - (Cow::Owned(vec), Some(charset_decoder)) => charset_decoder(&vec).into(), - (Cow::Owned(vec), None) => String::from_utf8(vec) - .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()) - .into(), - (Cow::Borrowed(bytes), Some(charset_decoder)) => { - charset_decoder(bytes).into() - } - (Cow::Borrowed(bytes), None) => String::from_utf8_lossy(bytes), - }; - - let is_html = mime_type == MimeType::TextHtml; - - if !add_to_html && is_html || !add_to_text && !is_html { - message.attachments.push(message.parts.len() as u32); - } - - if is_html { - PartType::Html(text) - } else { - PartType::Text(text) - } - } else { - message.attachments.push(message.parts.len() as u32); - - if !is_inline { - PartType::Binary(bytes) - } else { - PartType::InlineBinary(bytes) - } - } - } else { - message.attachments.push(message.parts.len() as u32); - - if depth != 0 { - if let Some(nested_message) = self.parse_(bytes.as_ref(), depth - 1, false) { - PartType::Message(Message { - html_body: nested_message.html_body, - text_body: nested_message.text_body, - attachments: nested_message.attachments, - parts: nested_message - .parts - .into_iter() - .map(|p| p.into_owned()) - .collect(), - raw_message: bytes.into_owned().into(), - }) - } else { - is_encoding_problem = true; - PartType::Binary(bytes) - } - } else { - is_encoding_problem = true; - PartType::Binary(bytes) - } - }; - - // Add part - message.parts.push(MessagePart { - headers: std::mem::take(&mut part_headers), - encoding, - is_encoding_problem, - body: body_part, - offset_header: state.offset_header as u32, - offset_body: state.offset_body as u32, - offset_end: state.offset_end as u32, - }); - - if state.mime_boundary.is_some() { - // Currently processing a MIME part - 'inner: loop { - if let MimeType::Message = state.mime_type { - // Finished processing a nested message, restore parent message from stack - if let Some((mut prev_state, Some(mut prev_message))) = state_stack.pop() { - let offset_end = state - .mime_boundary - .as_ref() - .map(|b| { - let pos = stream.offset().saturating_sub(b.len() + 2); - stream.data.get(pos - 2).map_or(pos - 1, |&ch| { - if ch == b'\r' { pos - 2 } else { pos - 1 } - }) - }) - .unwrap_or_else(|| stream.offset()); - message.raw_message = raw_message.into(); - //raw_message[state.offset_header..offset_end].as_ref().into(); - - if let Some(part) = prev_message.parts.get_mut(state.part_id as usize) { - part.offset_end = offset_end as u32; - if message.is_empty() { - part.is_encoding_problem = true; - part.body = PartType::Text(String::from_utf8_lossy( - raw_message - .get(part.offset_body as usize..offset_end) - .unwrap_or_default(), - )); - } else { - part.body = PartType::Message(message); - } - } else { - debug_assert!(false, "Invalid part ID, could not find message."); - } - - message = prev_message; - prev_state.mime_boundary = state.mime_boundary; - state = prev_state; - } else { - debug_assert!(false, "Failed to restore parent message. Aborting."); - break 'outer; - } - } - - if stream.is_multipart_end() { - // End of MIME part reached - - if MimeType::MultipartAlternative == state.mime_type - && state.need_html_body - && state.need_text_body - { - // Found HTML part only - if state.text_parts == message.text_body.len() - && state.html_parts != message.html_body.len() - { - for &part_id in &message.html_body[state.html_parts..] { - message.text_body.push(part_id); - } - } - - // Found text part only - if state.html_parts == message.html_body.len() - && state.text_parts != message.text_body.len() - { - for &part_id in &message.text_body[state.text_parts..] { - message.html_body.push(part_id); - } - } - } - - if let Some(part) = message.parts.get_mut(state.part_id as usize) { - // Add headers and substructure to parent part - if state.sub_part_ids.len() != 1 || state.sub_part_ids[0] != 0 { - part.body = - PartType::Multipart(std::mem::take(&mut state.sub_part_ids)); - } - - // Restore ancestor's state - if let Some((prev_state, _)) = state_stack.pop() { - state = prev_state; - - if let Some(ref mime_boundary) = state.mime_boundary { - // Ancestor has a MIME boundary, seek it. - if let Some(offset) = - stream.seek_next_part_offset(mime_boundary) - { - part.offset_end = offset as u32; - continue 'inner; - } - } - } - - // This part has no boundary, update end offset - part.offset_end = stream.offset() as u32; - } else { - debug_assert!(false, "Invalid part ID, could not find multipart."); - } - - break 'outer; - } else { - // Headers of next part expected next, break inner look. - break 'inner; - } - } - } else if stream.offset() >= stream.data.len() { - break 'outer; - } - } - - // Corrupted MIME message, try to recover whatever is possible. - while let Some((prev_state, prev_message)) = state_stack.pop() { - if let Some(mut prev_message) = prev_message { - message.raw_message = raw_message.into(); //raw_message[state.offset_header..stream.offset()].as_ref().into(); - - if let Some(part) = prev_message.parts.get_mut(state.part_id as usize) { - part.offset_end = stream.offset() as u32; - if message.is_empty() { - part.is_encoding_problem = true; - let raw_text = raw_message.get(part.offset_body as usize..stream.offset()); - let text = match raw_text - .and_then(|bytes| std::str::from_utf8(bytes).ok()) - .and_then(|text| { - state - .mime_boundary - .as_deref() - .and_then(|b| std::str::from_utf8(b).ok()) - .and_then(|boundary| { - text.rsplit_once(boundary) - .and_then(|(text, _)| text.strip_suffix("--")) - }) - .map(|text| { - let text = text.strip_suffix('\n').unwrap_or(text); - text.strip_suffix('\r').unwrap_or(text) - }) - }) { - Some(text) => Cow::Borrowed(text), - _ => String::from_utf8_lossy(raw_text.unwrap_or_default()), - }; - - part.body = PartType::Text(text); - } else { - part.body = PartType::Message(message); - } - } else { - debug_assert!(false, "Invalid part ID, could not find message."); - } - - message = prev_message; - } else if let Some(part) = message.parts.get_mut(state.part_id as usize) { - part.offset_end = stream.offset() as u32; - if state.sub_part_ids.len() != 1 || state.sub_part_ids[0] != 0 { - part.body = PartType::Multipart(state.sub_part_ids); - } - } else { - debug_assert!(false, "This should not have happened."); - } - state = prev_state; - } - - message.raw_message = raw_message.into(); - - if !message.is_empty() { - message.parts[0].offset_end = message.raw_message.len() as u32; - Some(message) - } else if !part_headers.is_empty() { - // Message without a body - message.parts.push(MessagePart { - headers: part_headers, - encoding: Encoding::None, - is_encoding_problem: true, - body: PartType::Text("".into()), - offset_header: 0, - offset_body: message.raw_message.len() as u32, - offset_end: message.raw_message.len() as u32, - }); - Some(message) - } else { - None - } - } -} - -impl<'x> Message<'x> { - fn new() -> Message<'x> { - Message { - ..Default::default() - } - } - - /// Returns `false` if at least one header field was successfully parsed. - pub fn is_empty(&self) -> bool { - self.parts.is_empty() - } -} - -#[cfg(test)] -mod tests { - use std::{fs, path::PathBuf}; - - use crate::MessageParser; - - #[test] - fn parse_full_messages() { - for test_suite in ["rfc", "legacy", "thirdparty", "malformed"] { - let test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("resources") - .join("eml") - .join(test_suite); - - let mut tests_run = 0; - - for file_name in fs::read_dir(&test_dir).unwrap() { - let mut file_name = file_name.unwrap().path(); - if file_name.extension().is_some_and(|e| e == "eml") { - let raw_original = fs::read(&file_name).unwrap(); - tests_run += 1; - - // Test without CRs - let raw_message = strip_crlf(&raw_original); - file_name.set_extension("json"); - let expected_result = fs::read(&file_name).unwrap(); - - let message = MessageParser::default().parse(&raw_message).unwrap(); - let json_message = serde_json::to_string_pretty(&message).unwrap(); - - // Test that deserialization also works - let _: super::Message<'_> = serde_json::from_str(&json_message).unwrap(); - - if json_message.as_bytes() != expected_result { - file_name.set_extension("failed"); - fs::write(&file_name, json_message.as_bytes()).unwrap(); - panic!( - "Test failed, parsed message saved to {}", - file_name.display() - ); - } - - // Test with CRs - let raw_message = add_crlf(&raw_original); - file_name.set_extension("crlf.json"); - let expected_result = fs::read(&file_name).unwrap(); - - let message = MessageParser::default().parse(&raw_message).unwrap(); - let json_message = serde_json::to_string_pretty(&message).unwrap(); - - if json_message.as_bytes() != expected_result { - file_name.set_extension("failed"); - fs::write(&file_name, json_message.as_bytes()).unwrap(); - panic!( - "Test failed, parsed message saved to {}", - file_name.display() - ); - } - } - } - - assert!( - tests_run > 0, - "Did not find any tests to run in folder {}.", - test_dir.display() - ); - } - } - - fn add_crlf(bytes: &[u8]) -> Vec<u8> { - let mut result = Vec::with_capacity(bytes.len()); - let mut last_ch = 0; - for &ch in bytes { - if ch == b'\n' && last_ch != b'\r' { - result.push(b'\r'); - } - result.push(ch); - last_ch = ch; - } - - result - } - - fn strip_crlf(bytes: &[u8]) -> Vec<u8> { - let mut result = Vec::with_capacity(bytes.len()); - for &ch in bytes { - if ch != b'\r' { - result.push(ch); - } - } - - result - } -} diff --git a/src/parsers/mime.rs b/src/parsers/mime.rs deleted file mode 100644 index e9631a5..0000000 --- a/src/parsers/mime.rs +++ /dev/null @@ -1,167 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::borrow::Cow; - -use super::MessageStream; - -impl<'x> MessageStream<'x> { - pub fn seek_next_part(&mut self, boundary: &[u8]) -> bool { - if !boundary.is_empty() { - let mut last_ch = 0; - - self.checkpoint(); - - while let Some(&ch) = self.next() { - if ch == b'-' && last_ch == b'-' && self.try_skip(boundary) { - return true; - } - - last_ch = ch; - } - - self.restore(); - } - - false - } - - pub fn seek_next_part_offset(&mut self, boundary: &[u8]) -> Option<usize> { - let mut last_ch = b'\n'; - let mut offset_pos = self.offset(); - self.checkpoint(); - - while let Some(&ch) = self.next() { - if ch == b'\n' { - offset_pos = if last_ch == b'\r' { - self.offset() - 2 - } else { - self.offset() - 1 - }; - } else if ch == b'-' && last_ch == b'-' && self.try_skip(boundary) { - return offset_pos.into(); - } - - last_ch = ch; - } - - self.restore(); - - None - } - - pub fn mime_part(&mut self, boundary: &[u8]) -> (usize, Cow<'x, [u8]>) { - let mut last_ch = b'\n'; - let mut before_last_ch = 0; - let start_pos = self.offset(); - let mut end_pos = self.offset(); - - self.checkpoint(); - - while let Some(&ch) = self.next() { - if ch == b'\n' { - end_pos = if last_ch == b'\r' { - self.offset() - 2 - } else { - self.offset() - 1 - }; - } else if ch == b'-' - && !boundary.is_empty() - && last_ch == b'-' - && self.try_skip(boundary) - { - if before_last_ch != b'\n' { - end_pos = self.offset() - boundary.len() - 2; - } - return (end_pos, self.bytes(start_pos..end_pos).into()); - } - - before_last_ch = last_ch; - last_ch = ch; - } - - ( - if boundary.is_empty() { - self.offset() - } else { - self.restore(); - usize::MAX - }, - self.bytes(start_pos..self.len()).into(), - ) - } - - pub fn seek_part_end(&mut self, boundary: Option<&[u8]>) -> (usize, bool) { - let mut last_ch = b'\n'; - let mut before_last_ch = 0; - let mut end_pos = self.offset(); - - if let Some(boundary) = boundary { - while let Some(&ch) = self.next() { - if ch == b'\n' { - end_pos = if last_ch == b'\r' { - self.offset() - 2 - } else { - self.offset() - 1 - }; - } else if ch == b'-' && last_ch == b'-' && self.try_skip(boundary) { - if before_last_ch != b'\n' { - end_pos = self.offset() - boundary.len() - 2; - } - return (end_pos, true); - } - - before_last_ch = last_ch; - last_ch = ch; - } - - (self.offset(), false) - } else { - self.seek_end(); - (self.offset(), true) - } - } - - pub fn is_multipart_end(&mut self) -> bool { - self.checkpoint(); - - match (self.next(), self.peek()) { - (Some(b'\r'), Some(b'\n')) => { - self.next(); - false - } - (Some(b'-'), Some(b'-')) => { - self.next(); - true - } - (Some(b'\n'), _) => false, - (Some(&a), _) if a.is_ascii_whitespace() => { - self.skip_crlf(); - false - } - _ => { - self.restore(); - false - } - } - } - - #[inline(always)] - pub fn skip_crlf(&mut self) { - while let Some(ch) = self.peek() { - match ch { - b'\r' | b' ' | b'\t' => { - self.next(); - } - b'\n' => { - self.next(); - break; - } - _ => break, - } - } - } -} diff --git a/src/parsers/mod.rs b/src/parsers/mod.rs deleted file mode 100644 index 2c5879f..0000000 --- a/src/parsers/mod.rs +++ /dev/null @@ -1,152 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::{iter::Peekable, ops::Range, slice::Iter}; - -pub mod fields; -pub mod header; -pub mod message; -pub mod mime; -pub mod preview; - -pub struct MessageStream<'x> { - data: &'x [u8], - iter: Peekable<Iter<'x, u8>>, - pos: usize, - restore_pos: usize, -} - -impl<'x> MessageStream<'x> { - pub fn new(data: &'x [u8]) -> MessageStream<'x> { - MessageStream { - data, - iter: data.iter().peekable(), - pos: 0, - restore_pos: 0, - } - } - - #[inline(always)] - pub fn peek(&mut self) -> Option<&&u8> { - self.iter.peek() - } - - #[inline(always)] - pub fn offset(&self) -> usize { - std::cmp::min(self.pos, self.data.len()) - } - - #[inline(always)] - pub fn remaining(&self) -> usize { - self.data.len() - self.offset() - } - - #[inline(always)] - pub fn checkpoint(&mut self) { - self.restore_pos = self.offset(); - } - - #[inline(always)] - pub fn restore(&mut self) { - self.iter = self.data[self.restore_pos..].iter().peekable(); - self.pos = self.restore_pos; - self.restore_pos = 0; - } - - #[inline(always)] - pub fn reset(&mut self) { - self.restore_pos = 0; - } - - #[inline(always)] - pub fn peek_bytes(&self, len: usize) -> Option<&[u8]> { - let pos = self.offset(); - self.data.get(pos..pos + len) - } - - #[inline(always)] - pub fn peek_char(&mut self, ch: u8) -> bool { - matches!(self.peek(), Some(&&ch_) if ch_ == ch) - } - - #[inline(always)] - pub fn skip_bytes(&mut self, len: usize) { - self.pos += len; - self.iter = self.data[self.pos..].iter().peekable(); - } - - #[inline(always)] - pub fn try_skip(&mut self, bytes: &[u8]) -> bool { - if self.peek_bytes(bytes.len()) == Some(bytes) { - self.skip_bytes(bytes.len()); - true - } else { - false - } - } - - #[inline(always)] - pub fn try_skip_char(&mut self, ch: u8) -> bool { - if self.peek_char(ch) { - self.next(); - true - } else { - false - } - } - - #[inline(always)] - pub fn bytes(&self, range: Range<usize>) -> &'x [u8] { - self.data.get(range).unwrap_or_default() - } - - #[inline(always)] - pub fn seek_end(&mut self) { - self.pos = self.data.len(); - self.iter = [][..].iter().peekable(); - } - - #[inline(always)] - pub fn next_is_space(&mut self) -> bool { - matches!(self.next(), Some(b' ' | b'\t')) - } - - #[inline(always)] - pub fn peek_next_is_space(&mut self) -> bool { - matches!(self.peek(), Some(b' ' | b'\t')) - } - - #[inline(always)] - pub fn try_next_is_space(&mut self) -> bool { - if self.peek_next_is_space() { - self.next(); - true - } else { - false - } - } - - #[allow(clippy::len_without_is_empty)] - #[inline(always)] - pub fn len(&self) -> usize { - self.data.len() - } - - #[inline(always)] - pub fn is_eof(&mut self) -> bool { - self.iter.peek().is_none() - } -} - -impl<'x> Iterator for MessageStream<'x> { - type Item = &'x u8; - - #[inline(always)] - fn next(&mut self) -> Option<Self::Item> { - self.pos += 1; - self.iter.next() - } -} diff --git a/src/parsers/preview.rs b/src/parsers/preview.rs deleted file mode 100644 index 7941618..0000000 --- a/src/parsers/preview.rs +++ /dev/null @@ -1,181 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - */ - -use std::borrow::Cow; - -use crate::decoders::html::html_to_text; - -pub fn preview_html<'x>(html: Cow<'_, str>, max_len: usize) -> Cow<'x, str> { - preview_text(html_to_text(html.as_ref()).into(), max_len) -} - -pub fn preview_text<'x>(text: Cow<'_, str>, mut max_len: usize) -> Cow<'x, str> { - if text.len() > max_len { - let add_dots = max_len > 6; - if add_dots { - max_len -= 3; - } - let mut result = String::with_capacity(max_len); - for ch in text.chars() { - if ch.len_utf8() + result.len() > max_len { - break; - } - result.push(ch); - } - if add_dots { - result.push_str("..."); - } - result.into() - } else { - text.into_owned().into() - } -} - -pub fn truncate_text<'x>(text: Cow<'_, str>, max_len: usize) -> Cow<'x, str> { - preview_text(text, max_len) -} - -pub fn truncate_html<'x>(html: Cow<'_, str>, mut max_len: usize) -> Cow<'x, str> { - if html.len() > max_len { - let add_dots = max_len > 6; - if add_dots { - max_len -= 3; - } - - let mut result = String::with_capacity(max_len); - let mut in_tag = false; - let mut in_comment = false; - let mut last_tag_end_pos = 0; - for (pos, ch) in html.char_indices() { - let mut set_last_tag = 0; - match ch { - '<' if !in_tag => { - in_tag = true; - if let Some("!--") = html.get(pos + 1..pos + 4) { - in_comment = true; - } - set_last_tag = pos; - } - '>' if in_tag => { - if in_comment { - if let Some("--") = html.get(pos - 2..pos) { - in_comment = false; - in_tag = false; - set_last_tag = pos + 1; - } - } else { - in_tag = false; - set_last_tag = pos + 1; - } - } - _ => (), - } - if ch.len_utf8() + pos > max_len { - result.push_str( - &html[0..if (in_tag || set_last_tag > 0) && last_tag_end_pos > 0 { - last_tag_end_pos - } else { - pos - }], - ); - if add_dots { - result.push_str("..."); - } - break; - } else if set_last_tag > 0 { - last_tag_end_pos = set_last_tag; - } - } - result.into() - } else { - html.into_owned().into() - } -} - -#[cfg(test)] -mod tests { - #[test] - fn text_preview() { - let text_1 = concat!( - "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", - "— Antoine de Saint-Exupéry, Citadelle (1948)" - ); - let text_2 = concat!( - "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」", - "子路曰:「為孔丘。」曰:「是魯孔丘與?」曰:「是也。」曰:「是知津矣。」問於桀溺,", - "桀溺曰:「子為誰?」曰:「為仲由。」曰:「是魯孔丘之徒與?」對曰:「然。", - "」曰:「滔滔者天下皆是也,而誰以易之?且而與其從辟人之士也,豈若從", - "辟世之士哉?」耰而不輟。子路行以告。夫子憮然曰:「鳥獸不可與同群,吾非斯人之徒", - "與而誰與?天下有道,丘不與易也。」", - "子路從而後,遇丈人,以杖荷蓧。子路問曰:「子見夫子乎?」丈人曰:「四體不勤,", - "五穀不分。孰為夫子?」植其杖而芸。子路拱而立。止子路宿,殺雞為黍而食之,見其二", - "子焉。明日,子路行以告。子曰:「隱者也。」使子路反見之。至則行矣。子路曰:「", - "不仕無義。長幼之節,不可廢也;君臣之義,如之何其廢之?欲潔其身,而亂大倫。君", - "子之仕也,行其義也。道之不行,已知之矣。」" - ); - - assert_eq!( - super::truncate_text(text_1.into(), 110), - "J'interdis aux marchands de vanter trop leurs marchandises. Car ils se fontvite pédagogues et t'enseignent..." - ); - - assert_eq!( - super::truncate_text(text_2.into(), 110), - "長沮、桀溺耦而耕,孔子過之,使子路問津焉。長沮曰:「夫執輿者為誰?」子..." - ); - } - - #[test] - fn html_truncate() { - for (html, expected_result) in [ - ( - "<html>hello<br/>world<br/></html>", - "<html>hello<br/>world...", - ), - ("<html>using <><br/></html>", "<html>using <><br/>..."), - ( - "test <not br/>tag<br />test <not br/>tag<br />", - "test <not br/>tag...", - ), - ( - "<>< ><tag\n/>>hello world< br \n />", - "<>< ><tag\n/>>hello ...", - ), - ( - concat!( - "<head><title>ignore headxyz", - "

<body>

" - ), - "ignore he...", - ), - ( - concat!( - "<p>what is ♥?</p><p>ßĂΒγ ", - "don't hurt me.</p>" - ), - "<p>what is ♥...", - ), - ( - "<!-- <> < < < -->the actual<!--> text", - "<!-- <> < < < -->the a...", - ), - ( - " < p > hello < / p > < p > world < / p > !!! < br > ", - " < p > hello ...", - ), - ( - " <p>please unsubscribe <a href=#>here</a>.</p> ", - " <p>please unsubscribe...", - ), - ] { - assert_eq!(super::truncate_html(html.into(), 25), expected_result); - } - } -} diff --git a/src/scan/lib_memchr.rs b/src/scan/lib_memchr.rs new file mode 100644 index 0000000..ff1ae95 --- /dev/null +++ b/src/scan/lib_memchr.rs @@ -0,0 +1,21 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{after, is_field_end}; +use memchr::{memchr_iter, memmem::Finder}; +use std::sync::LazyLock; + +static DASH_LINE: LazyLock<Finder<'static>> = LazyLock::new(|| Finder::new(b"\n--")); + +pub(crate) fn dash_line(hay: &[u8], from: usize) -> Option<usize> { + DASH_LINE.find(hay.get(from..)?).map(|pos| pos + from) +} + +pub(crate) fn field_end(hay: &[u8], from: usize) -> Option<usize> { + memchr_iter(b'\n', hay.get(from..)?) + .map(|pos| pos + from) + .find(|&pos| is_field_end(after(hay, pos))) +} diff --git a/src/scan/mod.rs b/src/scan/mod.rs new file mode 100644 index 0000000..d2b01b8 --- /dev/null +++ b/src/scan/mod.rs @@ -0,0 +1,204 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +//! Byte-scanning kernels used by the structural pass. +//! +//! Two searches do all the scanning: [`Kernel::dash_line`] finds candidate +//! delimiter lines (`\n--`) inside bodies, and [`Kernel::field_end`] finds the +//! end of each unfolded header field (a `\n` not followed by SP or HT). Every +//! back end returns exactly what the scalar reference returns. + +mod lib_memchr; +mod scalar; +mod set; +pub(crate) mod swar; + +pub(crate) use set::{ByteSet, Stop}; + +#[cfg(any( + all(target_arch = "aarch64", target_feature = "neon"), + all(target_arch = "x86_64", target_feature = "sse2") +))] +mod simd; + +#[cfg(all(target_arch = "aarch64", target_feature = "neon"))] +mod neon; +#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] +mod x86; + +/// A back end for the structural kernels. +/// +/// A value names a back end the running CPU supports: the only ways to get +/// one are [`Kernel::best`], [`Kernel::available`] and the portable +/// [`Kernel::SCALAR`] and [`Kernel::MEMCHR`]. A SIMD back end cannot be +/// named from outside the crate: +/// +/// ```compile_fail +/// #[cfg(target_arch = "x86_64")] +/// let forced = mail_parser::scan::Kernel::Avx2; +/// #[cfg(target_arch = "aarch64")] +/// let forced = mail_parser::scan::Kernel::Neon; +/// assert_eq!(forced.dash_line(b"x\n--", 0), Some(1)); +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Kernel(Backend); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum Backend { + Scalar, + Memchr, + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + Neon, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Sse2, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Avx2, +} + +impl Kernel { + /// Byte-at-a-time reference implementation, on every CPU. + pub const SCALAR: Kernel = Kernel(Backend::Scalar); + + /// Portable implementation over the `memchr` crate, on every CPU. + pub const MEMCHR: Kernel = Kernel(Backend::Memchr); + + /// The fastest back end supported by the running CPU: NEON on aarch64, + /// AVX2 when detected or else SSE2 on x86_64, `memchr` elsewhere. + pub fn best() -> Self { + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + { + Kernel(Backend::Neon) + } + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + { + if std::is_x86_feature_detected!("avx2") { + Kernel(Backend::Avx2) + } else { + Kernel(Backend::Sse2) + } + } + #[cfg(not(any( + all(target_arch = "aarch64", target_feature = "neon"), + all(target_arch = "x86_64", target_feature = "sse2") + )))] + { + Kernel::MEMCHR + } + } + + /// Every back end the running CPU supports, scalar reference first. + pub fn available() -> impl Iterator<Item = Kernel> { + [ + Some(Kernel::SCALAR), + Some(Kernel::MEMCHR), + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + Some(Kernel(Backend::Neon)), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Some(Kernel(Backend::Sse2)), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + std::is_x86_feature_detected!("avx2").then_some(Kernel(Backend::Avx2)), + ] + .into_iter() + .flatten() + } + + /// Short name of the back end. + pub fn name(self) -> &'static str { + match self.0 { + Backend::Scalar => "scalar", + Backend::Memchr => "memchr", + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + Backend::Neon => "neon", + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Sse2 => "sse2", + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Avx2 => "avx2", + } + } + + /// First position `i >= from` where `hay[i] == b'\n'` and + /// `hay[i + 1..i + 3] == b"--"`. + #[inline] + pub fn dash_line(self, hay: &[u8], from: usize) -> Option<usize> { + match self.0 { + Backend::Scalar => scalar::dash_line(hay, from), + Backend::Memchr => lib_memchr::dash_line(hay, from), + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + Backend::Neon => neon::dash_line(hay, from), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Sse2 => x86::sse2_dash_line(hay, from), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Avx2 => x86::avx2_dash_line(hay, from), + } + } + + /// First position `i >= from` where `hay[i] == b'\n'` and the next byte + /// is not SP or HT (or `i` is the last byte). + #[inline] + pub fn field_end(self, hay: &[u8], from: usize) -> Option<usize> { + match self.0 { + Backend::Scalar => scalar::field_end(hay, from), + Backend::Memchr => lib_memchr::field_end(hay, from), + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + Backend::Neon => neon::field_end(hay, from), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Sse2 => x86::sse2_field_end(hay, from), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Avx2 => x86::avx2_field_end(hay, from), + } + } + + #[inline] + pub(crate) fn first_in_set( + self, + set: &ByteSet, + hay: &[u8], + from: usize, + end: usize, + ) -> Option<usize> { + match self.0 { + Backend::Scalar | Backend::Memchr => set::first_in_set(set, hay, from, end), + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + Backend::Neon => neon::first_in_set(set, hay, from, end), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Sse2 => x86::sse2_first_in_set(set, hay, from, end), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Avx2 => x86::avx2_first_in_set(set, hay, from, end), + } + } + + #[inline] + pub(crate) fn stop_in_set(self, set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Stop { + match self.0 { + Backend::Scalar | Backend::Memchr => set::stop_in_set(set, hay, from, end), + #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] + Backend::Neon => neon::stop_in_set(set, hay, from, end), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Sse2 => x86::sse2_stop_in_set(set, hay, from, end), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + Backend::Avx2 => x86::avx2_stop_in_set(set, hay, from, end), + } + } +} + +impl Default for Kernel { + fn default() -> Self { + Kernel::best() + } +} + +#[inline(always)] +pub(crate) fn is_field_end(after: &[u8]) -> bool { + !matches!(after, [b' ' | b'\t', ..]) +} + +#[inline(always)] +pub(crate) fn after(hay: &[u8], pos: usize) -> &[u8] { + hay.get(pos + 1..).unwrap_or_default() +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/src/scan/neon.rs b/src/scan/neon.rs new file mode 100644 index 0000000..a74f768 --- /dev/null +++ b/src/scan/neon.rs @@ -0,0 +1,144 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +#![allow(unsafe_code)] + +use super::{ + set::{ByteSet, Stop}, + simd::{self, Vector}, +}; +use core::arch::aarch64::*; + +impl Vector for uint8x16_t { + const BYTES: usize = 16; + const BITS_PER_BYTE: u32 = 4; + + #[inline(always)] + unsafe fn load(ptr: *const u8) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // Our caller guarantees `ptr` is readable for 16 bytes. + unsafe { vld1q_u8(ptr) } + } + + #[inline(always)] + unsafe fn splat(byte: u8) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { vdupq_n_u8(byte) } + } + + #[inline(always)] + unsafe fn eq(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { vceqq_u8(self, other) } + } + + #[inline(always)] + unsafe fn and(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { vandq_u8(self, other) } + } + + #[inline(always)] + unsafe fn or(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { vorrq_u8(self, other) } + } + + #[inline(always)] + unsafe fn and_not(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { vbicq_u8(self, other) } + } + + #[inline(always)] + unsafe fn mask(self) -> u64 { + // SAFETY: the module is built only with `target_feature = "neon"`, so + // NEON is part of the compilation target and present at run time. + // The intrinsics work on registers only. + unsafe { + vget_lane_u64::<0>(vreinterpret_u64_u8(vshrn_n_u16::<4>(vreinterpretq_u16_u8( + self, + )))) + } + } +} + +#[inline] +pub(crate) fn dash_line(hay: &[u8], from: usize) -> Option<usize> { + // SAFETY: NEON is enabled at compile time (the module is built only + // with `target_feature = "neon"`), the only requirement of + // `simd::dash_line::<uint8x16_t>`. + unsafe { simd::dash_line::<uint8x16_t>(hay.get(from..)?) }.map(|pos| pos + from) +} + +#[inline] +pub(crate) fn field_end(hay: &[u8], from: usize) -> Option<usize> { + // SAFETY: NEON is enabled at compile time (the module is built only + // with `target_feature = "neon"`), the only requirement of + // `simd::field_end::<uint8x16_t>`. + unsafe { simd::field_end::<uint8x16_t>(hay.get(from..)?) }.map(|pos| pos + from) +} + +#[inline] +pub(crate) fn first_in_set(set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Option<usize> { + // SAFETY: NEON is enabled at compile time (the module is built only with + // `target_feature = "neon"`). `set.low` and `set.high` are `[u8; 16]`, so + // their loads read exactly their 16 bytes. `simd::first_in_set` passes the + // closure only pointers with `SET_WIDTH` (16) bytes of `hay` behind them, + // and the closure reads those 16 bytes with one `vld1q_u8`. + unsafe { + let low = vld1q_u8(set.low.as_ptr()); + let high = vld1q_u8(set.high.as_ptr()); + let nibble = vdupq_n_u8(0x0f); + let stops = vdupq_n_u8(set.stops); + simd::first_in_set(set, hay, from, end, uint8x16_t::BITS_PER_BYTE, |at| { + let bytes = vld1q_u8(at); + let buckets = vandq_u8( + vqtbl1q_u8(low, vandq_u8(bytes, nibble)), + vqtbl1q_u8(high, vshrq_n_u8::<4>(bytes)), + ); + vtstq_u8(buckets, stops).mask() + }) + } +} + +#[inline] +pub(crate) fn stop_in_set(set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Stop { + // SAFETY: NEON is enabled at compile time (the module is built only with + // `target_feature = "neon"`). `set.low` and `set.high` are `[u8; 16]`, so + // their loads read exactly their 16 bytes. `simd::stop_in_set` passes the + // closure only pointers with `SET_WIDTH` (16) bytes of `hay` behind them, + // and the closure reads those 16 bytes with one `vld1q_u8`. + unsafe { + let low = vld1q_u8(set.low.as_ptr()); + let high = vld1q_u8(set.high.as_ptr()); + let nibble = vdupq_n_u8(0x0f); + let stops = vdupq_n_u8(set.stops); + let marks = vdupq_n_u8(set.marks); + simd::stop_in_set(set, hay, from, end, uint8x16_t::BITS_PER_BYTE, |at| { + let bytes = vld1q_u8(at); + let buckets = vandq_u8( + vqtbl1q_u8(low, vandq_u8(bytes, nibble)), + vqtbl1q_u8(high, vshrq_n_u8::<4>(bytes)), + ); + ( + vtstq_u8(buckets, stops).mask(), + vtstq_u8(buckets, marks).mask(), + ) + }) + } +} diff --git a/src/scan/scalar.rs b/src/scan/scalar.rs new file mode 100644 index 0000000..5968e10 --- /dev/null +++ b/src/scan/scalar.rs @@ -0,0 +1,23 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{after, is_field_end}; + +pub(crate) fn dash_line(hay: &[u8], from: usize) -> Option<usize> { + hay.get(from..)? + .windows(3) + .position(|window| window == b"\n--") + .map(|pos| pos + from) +} + +pub(crate) fn field_end(hay: &[u8], from: usize) -> Option<usize> { + hay.get(from..)? + .iter() + .enumerate() + .filter(|(_, byte)| **byte == b'\n') + .map(|(pos, _)| pos + from) + .find(|&pos| is_field_end(after(hay, pos))) +} diff --git a/src/scan/set.rs b/src/scan/set.rs new file mode 100644 index 0000000..80ed2c8 --- /dev/null +++ b/src/scan/set.rs @@ -0,0 +1,177 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +const NIBBLE: u8 = 0x0f; +const MAX_MEMBERS: usize = 16; + +#[derive(Debug, Clone, Copy)] +pub(crate) struct ByteSet { + pub(super) low: [u8; 16], + pub(super) high: [u8; 16], + pub(super) stops: u8, + pub(super) marks: u8, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + members: [u8; MAX_MEMBERS], + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + len: usize, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + marked: [u8; MAX_MEMBERS], + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + marked_len: usize, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Stop { + pub(crate) at: Option<usize>, + pub(crate) marked: bool, +} + +impl ByteSet { + pub(crate) const fn new(bytes: &[u8]) -> ByteSet { + ByteSet::with_marks(bytes, &[]) + } + + pub(crate) const fn with_marks(bytes: &[u8], marks: &[u8]) -> ByteSet { + assert!(!bytes.is_empty() && bytes.len() <= MAX_MEMBERS && marks.len() <= MAX_MEMBERS); + let mut set = ByteSet { + low: [0; 16], + high: [0; 16], + stops: 0, + marks: 0, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + members: [0; MAX_MEMBERS], + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + len: bytes.len(), + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + marked: [0; MAX_MEMBERS], + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + marked_len: marks.len(), + }; + let mut index = 0; + while index < bytes.len() { + let byte = bytes[index]; + assert!(byte < 0x80); + let bucket = 1 << (byte >> 4); + set.low[(byte & NIBBLE) as usize] |= bucket; + set.high[(byte >> 4) as usize] = bucket; + set.stops |= bucket; + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + { + set.members[index] = byte; + } + index += 1; + } + index = 0; + while index < marks.len() { + let byte = marks[index]; + assert!(byte < 0x80); + let bucket = 1 << (byte >> 4); + assert!(set.stops & bucket == 0); + set.low[(byte & NIBBLE) as usize] |= bucket; + set.high[(byte >> 4) as usize] = bucket; + set.marks |= bucket; + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + { + set.marked[index] = byte; + } + index += 1; + } + set + } + + pub(crate) const fn excluding(classes: &[u8; 256], class: u8) -> ByteSet { + let mut set = ByteSet { + low: [0; 16], + high: [0; 16], + stops: 0, + marks: 0, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + members: [0; MAX_MEMBERS], + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + len: 0, + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + marked: [0; MAX_MEMBERS], + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + marked_len: 0, + }; + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + let mut count = 0; + let mut byte = 0; + while byte < classes.len() { + let member = classes[byte] & class == 0; + if byte >= 0x80 { + assert!(!member); + } else if member { + let value = byte as u8; + let bucket = 1 << (value >> 4); + set.low[(value & NIBBLE) as usize] |= bucket; + set.high[(value >> 4) as usize] = bucket; + set.stops |= bucket; + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + { + if count < MAX_MEMBERS { + set.members[count] = value; + } + count += 1; + } + } + byte += 1; + } + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + { + set.len = if count <= MAX_MEMBERS { count } else { 0 }; + } + set + } + + #[inline(always)] + fn buckets(&self, byte: u8) -> u8 { + let low = self.low.get(usize::from(byte & NIBBLE)).copied(); + let high = self.high.get(usize::from(byte >> 4)).copied(); + low.unwrap_or(0) & high.unwrap_or(0) + } + + #[inline(always)] + pub(crate) fn contains(&self, byte: u8) -> bool { + self.buckets(byte) & self.stops != 0 + } + + #[inline(always)] + pub(crate) fn marks(&self, byte: u8) -> bool { + self.buckets(byte) & self.marks != 0 + } + + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + pub(super) fn members(&self) -> &[u8] { + self.members.get(..self.len).unwrap_or_default() + } + + #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))] + pub(super) fn marked(&self) -> &[u8] { + self.marked.get(..self.marked_len).unwrap_or_default() + } +} + +pub(crate) fn first_in_set(set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Option<usize> { + hay.get(from..end.min(hay.len()))? + .iter() + .position(|&byte| set.contains(byte)) + .map(|pos| pos + from) +} + +pub(crate) fn stop_in_set(set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Stop { + let mut marked = false; + let at = hay + .get(from..end.min(hay.len())) + .unwrap_or_default() + .iter() + .position(|&byte| { + marked |= set.marks(byte); + set.contains(byte) + }) + .map(|pos| pos + from); + Stop { at, marked } +} diff --git a/src/scan/simd.rs b/src/scan/simd.rs new file mode 100644 index 0000000..98c9801 --- /dev/null +++ b/src/scan/simd.rs @@ -0,0 +1,335 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +#![allow(unsafe_code)] + +use super::{ + scalar, + set::{self, ByteSet, Stop}, +}; + +pub(crate) trait Vector: Copy { + const BYTES: usize; + const BITS_PER_BYTE: u32; + + /// Loads `BYTES` bytes from `ptr`, which needs no alignment. + /// + /// # Safety + /// + /// `ptr` must be valid for reads of `BYTES` bytes, and the running CPU + /// must support the instruction set of the implementing type. + unsafe fn load(ptr: *const u8) -> Self; + + /// Copies `byte` into every lane. + /// + /// # Safety + /// + /// The running CPU must support the instruction set of the implementing + /// type. + unsafe fn splat(byte: u8) -> Self; + + /// Sets every bit of the lanes where `self` and `other` are equal. + /// + /// # Safety + /// + /// The running CPU must support the instruction set of the implementing + /// type. + unsafe fn eq(self, other: Self) -> Self; + + /// Bitwise AND. + /// + /// # Safety + /// + /// The running CPU must support the instruction set of the implementing + /// type. + unsafe fn and(self, other: Self) -> Self; + + /// Bitwise OR. + /// + /// # Safety + /// + /// The running CPU must support the instruction set of the implementing + /// type. + unsafe fn or(self, other: Self) -> Self; + + /// The bits of `self` that are clear in `other`. + /// + /// # Safety + /// + /// The running CPU must support the instruction set of the implementing + /// type. + unsafe fn and_not(self, other: Self) -> Self; + + /// Packs each lane of a comparison result into `BITS_PER_BYTE` bits, + /// lane 0 in the lowest bits. + /// + /// # Safety + /// + /// The running CPU must support the instruction set of the implementing + /// type. + unsafe fn mask(self) -> u64; +} + +const UNROLL: usize = 4; +const DASH_LOOKAHEAD: usize = 2; +const FOLD_LOOKAHEAD: usize = 1; +const SET_WIDTH: usize = 16; + +#[inline(always)] +fn first<V: Vector>(mask: u64) -> usize { + (mask.trailing_zeros() / V::BITS_PER_BYTE) as usize +} + +/// Vector version of `scalar::dash_line` over the whole of `tail`. +/// +/// # Safety +/// +/// The running CPU must support the instruction set of `V`. +#[inline(always)] +pub(crate) unsafe fn dash_line<V: Vector>(tail: &[u8]) -> Option<usize> { + let ptr = tail.as_ptr(); + let mut offset = 0; + // SAFETY: our caller guarantees the CPU supports `V`. Every load reads + // `V::BYTES` bytes that lie inside `tail`. The unrolled loop runs while + // `offset + UNROLL * V::BYTES + DASH_LOOKAHEAD <= tail.len()`; its last + // loads start at `offset + 1 + 3 * V::BYTES` and at + // `offset + 3 * V::BYTES + 2`, so they end at most at + // `offset + 4 * V::BYTES + 2`, within that bound. The single-vector loop + // runs while `offset + V::BYTES + DASH_LOOKAHEAD <= tail.len()` and loads + // from `offset`, `offset + 1` and `offset + 2`, ending at most at + // `offset + V::BYTES + 2`. `offset` never exceeds `tail.len()`, so the + // additions cannot overflow, and the bytes left over go to the safe + // `scalar::dash_line`. + unsafe { + let newline = V::splat(b'\n'); + let dash = V::splat(b'-'); + while offset + UNROLL * V::BYTES + DASH_LOOKAHEAD <= tail.len() { + let at = ptr.add(offset + 1); + let dashes = [ + V::load(at).eq(dash), + V::load(at.add(V::BYTES)).eq(dash), + V::load(at.add(2 * V::BYTES)).eq(dash), + V::load(at.add(3 * V::BYTES)).eq(dash), + ]; + let [d0, d1, d2, d3] = dashes; + if d0.or(d1).or(d2.or(d3)).mask() != 0 { + for (index, first_dash) in dashes.into_iter().enumerate() { + let block = offset + index * V::BYTES; + let hits = V::load(ptr.add(block)) + .eq(newline) + .and(first_dash) + .and(V::load(ptr.add(block + 2)).eq(dash)); + let mask = hits.mask(); + if mask != 0 { + return Some(block + first::<V>(mask)); + } + } + } + offset += UNROLL * V::BYTES; + } + while offset + V::BYTES + DASH_LOOKAHEAD <= tail.len() { + let at = ptr.add(offset); + let hits = V::load(at) + .eq(newline) + .and(V::load(at.add(1)).eq(dash)) + .and(V::load(at.add(2)).eq(dash)); + let mask = hits.mask(); + if mask != 0 { + return Some(offset + first::<V>(mask)); + } + offset += V::BYTES; + } + } + scalar::dash_line(tail, offset) +} + +/// Vector version of `scalar::field_end` over the whole of `tail`. +/// +/// # Safety +/// +/// The running CPU must support the instruction set of `V`. +#[inline(always)] +pub(crate) unsafe fn field_end<V: Vector>(tail: &[u8]) -> Option<usize> { + let ptr = tail.as_ptr(); + let mut offset = 0; + // SAFETY: our caller guarantees the CPU supports `V`. Every load reads + // `V::BYTES` bytes that lie inside `tail`. The unrolled loop runs while + // `offset + UNROLL * V::BYTES + FOLD_LOOKAHEAD <= tail.len()`; its loads + // start at `offset + k * V::BYTES` for `k < UNROLL` and at `block + 1` + // with `block <= offset + 3 * V::BYTES`, so they end at most at + // `offset + 4 * V::BYTES + 1`, within that bound. The single-vector loop + // runs while `offset + V::BYTES + FOLD_LOOKAHEAD <= tail.len()` and loads + // from `offset` and `offset + 1`, ending at most at + // `offset + V::BYTES + 1`. `offset` never exceeds `tail.len()`, so the + // additions cannot overflow, and the bytes left over go to the safe + // `scalar::field_end`. + unsafe { + let newline = V::splat(b'\n'); + let space = V::splat(b' '); + let tab = V::splat(b'\t'); + while offset + UNROLL * V::BYTES + FOLD_LOOKAHEAD <= tail.len() { + let at = ptr.add(offset); + let lines = [ + V::load(at).eq(newline), + V::load(at.add(V::BYTES)).eq(newline), + V::load(at.add(2 * V::BYTES)).eq(newline), + V::load(at.add(3 * V::BYTES)).eq(newline), + ]; + let [l0, l1, l2, l3] = lines; + if l0.or(l1).or(l2.or(l3)).mask() != 0 { + for (index, lines) in lines.into_iter().enumerate() { + let block = offset + index * V::BYTES; + if lines.mask() == 0 { + continue; + } + let next = V::load(ptr.add(block + 1)); + let mask = lines.and_not(next.eq(space).or(next.eq(tab))).mask(); + if mask != 0 { + return Some(block + first::<V>(mask)); + } + } + } + offset += UNROLL * V::BYTES; + } + while offset + V::BYTES + FOLD_LOOKAHEAD <= tail.len() { + let at = ptr.add(offset); + let lines = V::load(at).eq(newline); + if lines.mask() != 0 { + let next = V::load(at.add(1)); + let mask = lines.and_not(next.eq(space).or(next.eq(tab))).mask(); + if mask != 0 { + return Some(offset + first::<V>(mask)); + } + } + offset += V::BYTES; + } + } + scalar::field_end(tail, offset) +} + +/// First byte of `set` in `hay[from..end]`, testing `SET_WIDTH` bytes per +/// call of `mask_at`. +/// +/// # Safety +/// +/// `mask_at` must read at most `SET_WIDTH` bytes from the pointer it gets +/// and must otherwise be sound to call on the running CPU: this function +/// passes it only pointers with `SET_WIDTH` bytes of `hay` behind them. +#[inline(always)] +pub(crate) unsafe fn first_in_set( + set: &ByteSet, + hay: &[u8], + from: usize, + end: usize, + bits_per_byte: u32, + mask_at: impl Fn(*const u8) -> u64, +) -> Option<usize> { + let end = end.min(hay.len()); + if from >= end { + return None; + } + let ptr = hay.as_ptr(); + let first = |offset: usize, mask: u64| { + let hit = offset + (mask.trailing_zeros() / bits_per_byte) as usize; + (hit < end).then_some(hit) + }; + let mut offset = from; + while offset + SET_WIDTH <= hay.len() { + // SAFETY: the loop condition keeps `offset + SET_WIDTH` within + // `hay.len()`, so `ptr + offset` and the `SET_WIDTH` bytes that + // `mask_at` reads from it lie inside `hay`. `offset` starts below + // `end <= hay.len()` and the loop returns once it reaches `end`, so + // the addition cannot overflow. + let mask = mask_at(unsafe { ptr.add(offset) }); + if mask != 0 { + return first(offset, mask); + } + offset += SET_WIDTH; + if offset >= end { + return None; + } + } + match hay.len().checked_sub(SET_WIDTH) { + Some(base) => { + let skipped = (offset - base) as u32 * bits_per_byte; + // SAFETY: `base` is `hay.len() - SET_WIDTH` and the subtraction + // did not underflow, so the `SET_WIDTH` bytes at `ptr + base` are + // the last ones of `hay`. The loop exited with + // `offset + SET_WIDTH > hay.len()`, so `offset > base` and the + // shift drops the bytes before `offset`. + let mask = mask_at(unsafe { ptr.add(base) }) >> skipped; + if mask != 0 { first(offset, mask) } else { None } + } + None => set::first_in_set(set, hay, offset, end), + } +} + +#[inline(always)] +fn low_bits(bytes: usize, bits_per_byte: u32) -> u64 { + match u32::try_from(bytes).map(|bytes| bytes.saturating_mul(bits_per_byte)) { + Ok(bits) if bits < u64::BITS => (1 << bits) - 1, + _ => u64::MAX, + } +} + +/// First byte of the stop set in `hay[from..end]`, and whether a marked byte +/// comes before it, testing `SET_WIDTH` bytes per call of `masks_at`. +/// +/// # Safety +/// +/// `masks_at` must read at most `SET_WIDTH` bytes from the pointer it gets +/// and must otherwise be sound to call on the running CPU: this function +/// passes it only pointers with `SET_WIDTH` bytes of `hay` behind them. +#[inline(always)] +pub(crate) unsafe fn stop_in_set( + set: &ByteSet, + hay: &[u8], + from: usize, + end: usize, + bits_per_byte: u32, + masks_at: impl Fn(*const u8) -> (u64, u64), +) -> Stop { + let end = end.min(hay.len()); + let mut marked = false; + let mut offset = from; + while offset < end { + let base = if offset + SET_WIDTH <= hay.len() { + offset + } else { + match hay.len().checked_sub(SET_WIDTH) { + Some(base) => base, + None => { + let rest = set::stop_in_set(set, hay, offset, end); + return Stop { + at: rest.at, + marked: marked || rest.marked, + }; + } + } + }; + let skipped = (offset - base) as u32 * bits_per_byte; + // SAFETY: `base` is `offset` when `offset + SET_WIDTH <= hay.len()`, + // else `hay.len() - SET_WIDTH` when that does not underflow (a + // shorter `hay` returned through the safe `set::stop_in_set` above), + // so the `SET_WIDTH` bytes that `masks_at` reads from + // `hay.as_ptr() + base` lie inside `hay`. `offset < end <= hay.len()` + // keeps `offset + SET_WIDTH` from overflowing. + let (stops, marks) = masks_at(unsafe { hay.as_ptr().add(base) }); + let valid = low_bits(end - offset, bits_per_byte); + let stops = (stops >> skipped) & valid; + let marks = (marks >> skipped) & valid; + if stops != 0 { + let first = stops.trailing_zeros() / bits_per_byte; + return Stop { + at: Some(offset + first as usize), + marked: marked || marks & low_bits(first as usize, bits_per_byte) != 0, + }; + } + marked |= marks != 0; + offset = base + SET_WIDTH; + } + Stop { at: None, marked } +} diff --git a/src/scan/swar.rs b/src/scan/swar.rs new file mode 100644 index 0000000..72ca036 --- /dev/null +++ b/src/scan/swar.rs @@ -0,0 +1,96 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +pub(crate) const WORD: usize = 8; +pub(crate) const LANES: u64 = 0x0101_0101_0101_0101; +pub(crate) const HIGH_BITS: u64 = 0x8080_8080_8080_8080; + +#[inline(always)] +pub(crate) fn load(bytes: &[u8]) -> u64 { + match bytes.first_chunk::<WORD>() { + Some(word) => u64::from_le_bytes(*word), + None => { + let mut word = [0u8; WORD]; + if let Some(prefix) = word.get_mut(..bytes.len()) { + prefix.copy_from_slice(bytes); + } + u64::from_le_bytes(word) + } + } +} + +#[inline(always)] +pub(crate) fn splat(byte: u8) -> u64 { + LANES * u64::from(byte) +} + +#[inline(always)] +pub(crate) fn zero_bytes(word: u64) -> u64 { + word.wrapping_sub(LANES) & !word & HIGH_BITS +} + +#[inline(always)] +pub(crate) fn equal_bytes(word: u64, byte: u8) -> u64 { + zero_bytes(word ^ splat(byte)) +} + +#[inline(always)] +pub(crate) fn bytes_below(word: u64, limit: u8) -> u64 { + word.wrapping_sub(splat(limit)) & !word & HIGH_BITS +} + +#[inline(always)] +pub(crate) fn ascii_in_range(word: u64, low: u8, high: u8) -> u64 { + let low_bits = word & !HIGH_BITS; + let from_low = low_bits + splat(0x80 - low); + let after_high = low_bits + splat(0x7f - high); + from_low & !after_high & !word & HIGH_BITS +} + +#[inline(always)] +pub(crate) fn ascii_lowercase(word: u64) -> u64 { + word | (ascii_in_range(word, b'A', b'Z') >> 2) +} + +#[inline(always)] +pub(crate) fn first_byte(mask: u64) -> usize { + (mask.trailing_zeros() / 8) as usize +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn masks_match_byte_tests() { + let mut rng = crate::scan::tests::Rng(0x0123_4567_89ab_cdef); + for _ in 0..100_000 { + let bytes: [u8; WORD] = std::array::from_fn(|_| rng.below(256) as u8); + let word = u64::from_le_bytes(bytes); + let first = |mask: u64| (mask != 0).then(|| first_byte(mask)); + assert_eq!( + first(equal_bytes(word, b':')), + bytes.iter().position(|&b| b == b':') + ); + assert_eq!( + first(bytes_below(word, 0x21)), + bytes.iter().position(|&b| b < 0x21) + ); + let range = ascii_in_range(word, 0x3a, 0x3d); + for (index, byte) in bytes.iter().enumerate() { + assert_eq!( + range >> (index * 8 + 7) & 1 == 1, + (0x3a..=0x3d).contains(byte), + "{bytes:?}" + ); + } + assert_eq!( + ascii_lowercase(word).to_le_bytes(), + bytes.map(|byte| byte.to_ascii_lowercase()) + ); + } + } +} diff --git a/src/scan/tests.rs b/src/scan/tests.rs new file mode 100644 index 0000000..315471a --- /dev/null +++ b/src/scan/tests.rs @@ -0,0 +1,317 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{ByteSet, Kernel, set}; +use std::path::PathBuf; + +const ALPHABET: &[u8] = b"\n\n\n\r\r---- \ta"; +const ITERATIONS: usize = 3_000; +const MAX_LEN: usize = 300; + +pub(crate) struct Rng(pub(crate) u64); + +impl Rng { + pub(crate) fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + pub(crate) fn below(&mut self, limit: usize) -> usize { + (self.next() % limit.max(1) as u64) as usize + } +} + +fn agree(kernel: Kernel, hay: &[u8]) { + for from in 0..=hay.len() + 1 { + assert_eq!( + kernel.dash_line(hay, from), + Kernel::SCALAR.dash_line(hay, from), + "{} dash_line from {from} in {hay:?}", + kernel.name() + ); + assert_eq!( + kernel.field_end(hay, from), + Kernel::SCALAR.field_end(hay, from), + "{} field_end from {from} in {hay:?}", + kernel.name() + ); + } +} + +fn all_hits(hay: &[u8], find: impl Fn(&[u8], usize) -> Option<usize>) -> Vec<usize> { + let mut hits = Vec::new(); + let mut from = 0; + while let Some(hit) = find(hay, from) { + hits.push(hit); + from = hit + 1; + } + hits +} + +fn agree_on_sample(kernel: Kernel, hay: &[u8]) { + assert_eq!( + all_hits(hay, |h, f| kernel.dash_line(h, f)), + all_hits(hay, |h, f| Kernel::SCALAR.dash_line(h, f)), + "{} dash_line", + kernel.name() + ); + assert_eq!( + all_hits(hay, |h, f| kernel.field_end(h, f)), + all_hits(hay, |h, f| Kernel::SCALAR.field_end(h, f)), + "{} field_end", + kernel.name() + ); +} + +pub(crate) fn fixture_files() -> Vec<Vec<u8>> { + let mut files = Vec::new(); + let mut dirs = vec![PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/eml")]; + while let Some(dir) = dirs.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for path in entries.flatten().map(|entry| entry.path()) { + if path.is_dir() { + dirs.push(path); + } else if path.extension().is_some_and(|ext| ext == "eml") + && let Ok(bytes) = std::fs::read(&path) + { + files.push(bytes); + } + } + } + files +} + +pub(crate) fn with_crlf(bytes: &[u8]) -> Vec<u8> { + let mut out = Vec::with_capacity(bytes.len() + bytes.len() / 16); + let mut last = 0u8; + for &byte in bytes { + if byte == b'\n' && last != b'\r' { + out.push(b'\r'); + } + out.push(byte); + last = byte; + } + out +} + +pub(crate) fn with_lf(bytes: &[u8]) -> Vec<u8> { + bytes + .iter() + .copied() + .filter(|&byte| byte != b'\r') + .collect() +} + +#[test] +fn kernels_match_scalar_on_random_input() { + let mut rng = Rng(0x2545_f491_4f6c_dd1d); + for _ in 0..ITERATIONS { + let len = rng.below(MAX_LEN); + let hay: Vec<u8> = (0..len) + .map(|_| ALPHABET[rng.below(ALPHABET.len())]) + .collect(); + for kernel in Kernel::available() { + agree(kernel, &hay); + } + } +} + +#[test] +fn kernels_match_scalar_on_adversarial_input() { + let patterns: [&[u8]; 8] = [ + b"\n", + b"\n-", + b"\n--", + b"\n \n\t\n", + b"--\n--\n", + b"\r\n\r\n--", + b"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + b"-----------------------------------", + ]; + for pattern in patterns { + for pad in 0..70 { + for tail in 0..3 { + let mut hay = vec![b'x'; pad]; + hay.extend_from_slice(pattern); + hay.extend(std::iter::repeat_n(b'y', tail)); + for kernel in Kernel::available() { + agree(kernel, &hay); + } + } + } + } + let mut dense = Vec::new(); + for index in 0..512usize { + dense.push(match index % 7 { + 0 | 3 => b'\n', + 1 | 4 => b'-', + 2 => b' ', + 5 => b'\t', + _ => b'-', + }); + } + for kernel in Kernel::available() { + agree(kernel, &dense); + } +} + +#[test] +fn kernels_match_scalar_on_fixtures() { + for file in fixture_files() { + for hay in [with_lf(&file), with_crlf(&file)] { + for kernel in Kernel::available() { + agree_on_sample(kernel, &hay); + } + } + } +} + +#[test] +fn best_kernel_is_available() { + assert!(Kernel::available().any(|kernel| kernel == Kernel::best())); +} + +const SETS: [ByteSet; 7] = [ + ByteSet::with_marks(b"\n\r,;<\"(:=", b"@"), + ByteSet::new(b"\n\r,;<\"(:="), + ByteSet::new(b"\n\r\"\\="), + ByteSet::new(b"\n\r>\\(="), + ByteSet::new(b"@"), + ByteSet::new(b"\x00\x7f"), + ByteSet::new(b" !\"#$%&'()*+,-.0"), +]; + +fn agree_on_sets(hay: &[u8]) { + for set in &SETS { + for from in 0..=hay.len() + 1 { + for end in [ + from, + from + 1, + from + 7, + from + 16, + from + 17, + from + 40, + usize::MAX, + ] { + let expected = set::first_in_set(set, hay, from, end); + let window = hay.get(from..end.min(hay.len())).unwrap_or_default(); + let naive = hay + .get(from..end.min(hay.len())) + .and_then(|bytes| bytes.iter().position(|byte| set.contains(*byte))); + assert_eq!(expected, naive.map(|pos| pos + from)); + let marked = window + .get(..naive.unwrap_or(window.len())) + .unwrap_or_default() + .iter() + .any(|byte| set.marks(*byte)); + let stop = set::stop_in_set(set, hay, from, end); + assert_eq!((stop.at, stop.marked), (expected, marked)); + for kernel in Kernel::available() { + assert_eq!( + kernel.first_in_set(set, hay, from, end), + expected, + "{} first_in_set from {from} end {end} in {hay:?}", + kernel.name() + ); + assert_eq!( + kernel.stop_in_set(set, hay, from, end), + stop, + "{} stop_in_set from {from} end {end} in {hay:?}", + kernel.name() + ); + } + } + } + } +} + +#[test] +fn byte_sets_are_exact() { + for (set, members) in SETS.iter().zip([ + &b"\n\r,;<\"(:="[..], + b"\n\r,;<\"(:=", + b"\n\r\"\\=", + b"\n\r>\\(=", + b"@", + b"\x00\x7f", + b" !\"#$%&'()*+,-.0", + ]) { + for byte in 0..=u8::MAX { + assert_eq!(set.contains(byte), members.contains(&byte), "{byte:#x}"); + } + } + let marked = SETS.first().copied().unwrap_or(ByteSet::new(b"@")); + for byte in 0..=u8::MAX { + assert_eq!(marked.marks(byte), byte == b'@', "{byte:#x}"); + } +} + +const ALNUM_CLASSES: [u8; 256] = { + let mut table = [0; 256]; + let mut byte = 0; + while byte < 256 { + if (byte as u8).is_ascii_alphanumeric() || byte >= 0x80 { + table[byte] = 1; + } + byte += 1; + } + table +}; + +static NOT_ALNUM: ByteSet = ByteSet::excluding(&ALNUM_CLASSES, 1); + +#[test] +fn excluding_sets_are_exact() { + for byte in 0..=u8::MAX { + assert_eq!( + NOT_ALNUM.contains(byte), + byte < 0x80 && !byte.is_ascii_alphanumeric(), + "{byte:#x}" + ); + } + let hay: Vec<u8> = (0..=u8::MAX).rev().chain(0..=u8::MAX).collect(); + for from in 0..hay.len() { + for kernel in Kernel::available() { + assert_eq!( + kernel.first_in_set(&NOT_ALNUM, &hay, from, hay.len()), + set::first_in_set(&NOT_ALNUM, &hay, from, hay.len()), + "{} from {from}", + kernel.name() + ); + } + } +} + +#[test] +fn set_kernels_match_scalar() { + let alphabet: &[u8] = b"aaaaaaaaaa@<>\"\\,;:=()\n\r \t\x00\x7f\x80\xc3\xff0/"; + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for _ in 0..400 { + let len = rng.below(90); + let hay: Vec<u8> = (0..len) + .map(|_| { + alphabet + .get(rng.below(alphabet.len())) + .copied() + .unwrap_or(b'a') + }) + .collect(); + agree_on_sets(&hay); + } + for len in 0..40 { + for hit in 0..len { + let mut hay = vec![b'a'; len]; + if let Some(byte) = hay.get_mut(hit) { + *byte = b'@'; + } + agree_on_sets(&hay); + } + } +} diff --git a/src/scan/x86.rs b/src/scan/x86.rs new file mode 100644 index 0000000..e22c170 --- /dev/null +++ b/src/scan/x86.rs @@ -0,0 +1,343 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +#![allow(unsafe_code)] + +use super::{ + set::{ByteSet, Stop}, + simd::{self, Vector}, +}; +use core::arch::x86_64::*; + +impl Vector for __m128i { + const BYTES: usize = 16; + const BITS_PER_BYTE: u32 = 1; + + #[inline(always)] + unsafe fn load(ptr: *const u8) -> Self { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // Our caller guarantees `ptr` is readable for 16 bytes; the load is + // unaligned. + unsafe { _mm_loadu_si128(ptr.cast()) } + } + + #[inline(always)] + unsafe fn splat(byte: u8) -> Self { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { _mm_set1_epi8(byte as i8) } + } + + #[inline(always)] + unsafe fn eq(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { _mm_cmpeq_epi8(self, other) } + } + + #[inline(always)] + unsafe fn and(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { _mm_and_si128(self, other) } + } + + #[inline(always)] + unsafe fn or(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { _mm_or_si128(self, other) } + } + + #[inline(always)] + unsafe fn and_not(self, other: Self) -> Self { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { _mm_andnot_si128(other, self) } + } + + #[inline(always)] + unsafe fn mask(self) -> u64 { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is part of the compilation target and present at run time. + // The intrinsic works on registers only. + unsafe { _mm_movemask_epi8(self) as u32 as u64 } + } +} + +impl Vector for __m256i { + const BYTES: usize = 32; + const BITS_PER_BYTE: u32 = 1; + + #[inline(always)] + unsafe fn load(ptr: *const u8) -> Self { + // SAFETY: our caller guarantees the CPU supports AVX2, as the + // `Vector` contract requires for `__m256i`. + // It also guarantees `ptr` is readable for 32 bytes; the load is + // unaligned. + unsafe { _mm256_loadu_si256(ptr.cast()) } + } + + #[inline(always)] + unsafe fn splat(byte: u8) -> Self { + // SAFETY: our caller guarantees the CPU supports AVX2, as the + // `Vector` contract requires for `__m256i`. + // The intrinsic works on registers only. + unsafe { _mm256_set1_epi8(byte as i8) } + } + + #[inline(always)] + unsafe fn eq(self, other: Self) -> Self { + // SAFETY: our caller guarantees the CPU supports AVX2, as the + // `Vector` contract requires for `__m256i`. + // The intrinsic works on registers only. + unsafe { _mm256_cmpeq_epi8(self, other) } + } + + #[inline(always)] + unsafe fn and(self, other: Self) -> Self { + // SAFETY: our caller guarantees the CPU supports AVX2, as the + // `Vector` contract requires for `__m256i`. + // The intrinsic works on registers only. + unsafe { _mm256_and_si256(self, other) } + } + + #[inline(always)] + unsafe fn or(self, other: Self) -> Self { + // SAFETY: our caller guarantees the CPU supports AVX2, as the + // `Vector` contract requires for `__m256i`. + // The intrinsic works on registers only. + unsafe { _mm256_or_si256(self, other) } + } + + #[inline(always)] + unsafe fn and_not(self, other: Self) -> Self { + // SAFETY: our caller guarantees the CPU supports AVX2, as the + // `Vector` contract requires for `__m256i`. + // The intrinsic works on registers only. + unsafe { _mm256_andnot_si256(other, self) } + } + + #[inline(always)] + unsafe fn mask(self) -> u64 { + // SAFETY: our caller guarantees the CPU supports AVX2, as the + // `Vector` contract requires for `__m256i`. + // The intrinsic works on registers only. + unsafe { _mm256_movemask_epi8(self) as u32 as u64 } + } +} + +#[inline] +pub(crate) fn sse2_dash_line(hay: &[u8], from: usize) -> Option<usize> { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is present, the only requirement of `simd::dash_line::<__m128i>`. + unsafe { simd::dash_line::<__m128i>(hay.get(from..)?) }.map(|pos| pos + from) +} + +#[inline] +pub(crate) fn sse2_field_end(hay: &[u8], from: usize) -> Option<usize> { + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is present, the only requirement of `simd::field_end::<__m128i>`. + unsafe { simd::field_end::<__m128i>(hay.get(from..)?) }.map(|pos| pos + from) +} + +/// # Safety +/// +/// The running CPU must support AVX2. +#[target_feature(enable = "avx2")] +unsafe fn avx2_dash_line_impl(tail: &[u8]) -> Option<usize> { + // SAFETY: our caller guarantees the CPU supports AVX2, the only + // requirement of `simd::dash_line::<__m256i>`. + unsafe { simd::dash_line::<__m256i>(tail) } +} + +/// # Safety +/// +/// The running CPU must support AVX2. +#[target_feature(enable = "avx2")] +unsafe fn avx2_field_end_impl(tail: &[u8]) -> Option<usize> { + // SAFETY: our caller guarantees the CPU supports AVX2, the only + // requirement of `simd::field_end::<__m256i>`. + unsafe { simd::field_end::<__m256i>(tail) } +} + +#[inline] +pub(crate) fn avx2_dash_line(hay: &[u8], from: usize) -> Option<usize> { + // SAFETY: the CPU supports AVX2. This function is reached only from the + // `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: `x86` is a + // private module of `scan`, `Backend` and the field of `Kernel` are + // private to `scan`, and `Kernel::best` and `Kernel::available` build + // `Backend::Avx2` only after `is_x86_feature_detected!("avx2")` returned + // true. + unsafe { avx2_dash_line_impl(hay.get(from..)?) }.map(|pos| pos + from) +} + +#[inline] +pub(crate) fn avx2_field_end(hay: &[u8], from: usize) -> Option<usize> { + // SAFETY: the CPU supports AVX2. This function is reached only from the + // `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: `x86` is a + // private module of `scan`, `Backend` and the field of `Kernel` are + // private to `scan`, and `Kernel::best` and `Kernel::available` build + // `Backend::Avx2` only after `is_x86_feature_detected!("avx2")` returned + // true. + unsafe { avx2_field_end_impl(hay.get(from..)?) }.map(|pos| pos + from) +} + +#[inline] +pub(crate) fn sse2_first_in_set( + set: &ByteSet, + hay: &[u8], + from: usize, + end: usize, +) -> Option<usize> { + if set.members().is_empty() { + return super::set::first_in_set(set, hay, from, end); + } + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is present, and the closure uses only SSE2 intrinsics and the + // `__m128i` methods. `simd::first_in_set` passes the closure only + // pointers with `SET_WIDTH` (16) bytes of `hay` behind them, and + // `__m128i::load` reads those 16 bytes. + unsafe { + simd::first_in_set(set, hay, from, end, __m128i::BITS_PER_BYTE, |at| { + let bytes = __m128i::load(at); + set.members() + .iter() + .fold(_mm_setzero_si128(), |hits, &member| { + hits.or(bytes.eq(__m128i::splat(member))) + }) + .mask() + }) + } +} + +/// # Safety +/// +/// The running CPU must support AVX2. +#[target_feature(enable = "avx2")] +unsafe fn avx2_first_in_set_impl( + set: &ByteSet, + hay: &[u8], + from: usize, + end: usize, +) -> Option<usize> { + // SAFETY: our caller guarantees the CPU supports AVX2, and this function + // enables it; AVX2 implies SSSE3 (`_mm_shuffle_epi8`) and SSE2, the only + // instruction sets used here. `set.low` and `set.high` are `[u8; 16]`, so + // their unaligned 16-byte loads stay inside them. `simd::first_in_set` + // passes the closure only pointers with `SET_WIDTH` (16) bytes of `hay` + // behind them, and the closure reads those 16 bytes with one unaligned + // load. + unsafe { + let low = _mm_loadu_si128(set.low.as_ptr().cast()); + let high = _mm_loadu_si128(set.high.as_ptr().cast()); + let nibble = _mm_set1_epi8(0x0f); + let stops = _mm_set1_epi8(set.stops as i8); + let zero = _mm_setzero_si128(); + simd::first_in_set(set, hay, from, end, __m128i::BITS_PER_BYTE, |at| { + let bytes = _mm_loadu_si128(at.cast()); + let buckets = _mm_and_si128( + _mm_shuffle_epi8(low, _mm_and_si128(bytes, nibble)), + _mm_shuffle_epi8(high, _mm_and_si128(_mm_srli_epi16::<4>(bytes), nibble)), + ); + let hits = _mm_and_si128(buckets, stops); + u64::from(!(_mm_movemask_epi8(_mm_cmpeq_epi8(hits, zero)) as u32) & 0xffff) + }) + } +} + +#[inline] +pub(crate) fn avx2_first_in_set( + set: &ByteSet, + hay: &[u8], + from: usize, + end: usize, +) -> Option<usize> { + // SAFETY: the CPU supports AVX2. This function is reached only from the + // `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: `x86` is a + // private module of `scan`, `Backend` and the field of `Kernel` are + // private to `scan`, and `Kernel::best` and `Kernel::available` build + // `Backend::Avx2` only after `is_x86_feature_detected!("avx2")` returned + // true. + unsafe { avx2_first_in_set_impl(set, hay, from, end) } +} + +#[inline] +pub(crate) fn sse2_stop_in_set(set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Stop { + if set.members().is_empty() { + return super::set::stop_in_set(set, hay, from, end); + } + // SAFETY: the module is built only with `target_feature = "sse2"`, so + // SSE2 is present, and the closure uses only SSE2 intrinsics and the + // `__m128i` methods. `simd::stop_in_set` passes the closure only + // pointers with `SET_WIDTH` (16) bytes of `hay` behind them, and + // `__m128i::load` reads those 16 bytes. + unsafe { + simd::stop_in_set(set, hay, from, end, __m128i::BITS_PER_BYTE, |at| { + let bytes = __m128i::load(at); + let any = |members: &[u8]| { + members + .iter() + .fold(_mm_setzero_si128(), |hits, &member| { + hits.or(bytes.eq(__m128i::splat(member))) + }) + .mask() + }; + (any(set.members()), any(set.marked())) + }) + } +} + +/// # Safety +/// +/// The running CPU must support AVX2. +#[target_feature(enable = "avx2")] +unsafe fn avx2_stop_in_set_impl(set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Stop { + // SAFETY: our caller guarantees the CPU supports AVX2, and this function + // enables it; AVX2 implies SSSE3 (`_mm_shuffle_epi8`) and SSE2, the only + // instruction sets used here. `set.low` and `set.high` are `[u8; 16]`, so + // their unaligned 16-byte loads stay inside them. `simd::stop_in_set` + // passes the closure only pointers with `SET_WIDTH` (16) bytes of `hay` + // behind them, and the closure reads those 16 bytes with one unaligned + // load. + unsafe { + let low = _mm_loadu_si128(set.low.as_ptr().cast()); + let high = _mm_loadu_si128(set.high.as_ptr().cast()); + let nibble = _mm_set1_epi8(0x0f); + let stops = _mm_set1_epi8(set.stops as i8); + let marks = _mm_set1_epi8(set.marks as i8); + let zero = _mm_setzero_si128(); + simd::stop_in_set(set, hay, from, end, __m128i::BITS_PER_BYTE, |at| { + let bytes = _mm_loadu_si128(at.cast()); + let buckets = _mm_and_si128( + _mm_shuffle_epi8(low, _mm_and_si128(bytes, nibble)), + _mm_shuffle_epi8(high, _mm_and_si128(_mm_srli_epi16::<4>(bytes), nibble)), + ); + let bits = |mask| { + let hits = _mm_and_si128(buckets, mask); + u64::from(!(_mm_movemask_epi8(_mm_cmpeq_epi8(hits, zero)) as u32) & 0xffff) + }; + (bits(stops), bits(marks)) + }) + } +} + +#[inline] +pub(crate) fn avx2_stop_in_set(set: &ByteSet, hay: &[u8], from: usize, end: usize) -> Stop { + // SAFETY: the CPU supports AVX2. This function is reached only from the + // `Kernel` dispatch in `scan/mod.rs` on `Backend::Avx2`: `x86` is a + // private module of `scan`, `Backend` and the field of `Kernel` are + // private to `scan`, and `Kernel::best` and `Kernel::available` build + // `Backend::Avx2` only after `is_x86_feature_detected!("avx2")` returned + // true. + unsafe { avx2_stop_in_set_impl(set, hay, from, end) } +} diff --git a/src/store/mod.rs b/src/store/mod.rs new file mode 100644 index 0000000..e7ff1bf --- /dev/null +++ b/src/store/mod.rs @@ -0,0 +1,660 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod str; +mod table; + +pub(crate) use str::{Str, validated_string}; +pub(crate) use table::{Blank, Table}; + +use crate::{DateTime, Encoding, Greeting, Protocol, TlsVersion}; +use std::{fmt, net::IpAddr}; + +pub(crate) const NONE: u32 = u32::MAX; +const FIRST_TEXT_ITEMS: usize = 16; +const INLINE_IDS: usize = 4; +const INLINE_PARAMS: usize = 2; +const INLINE_CONTENT_TYPES: usize = 2; +const INLINE_TEXT_ITEMS: usize = 8; +const INLINE_ADDRESS_ITEMS: usize = 4; + +/// Index of a part in [`crate::Message::parts`], in document order across +/// nested messages. +pub type PartId = u32; + +/// Index of a message in [`crate::Message::messages`]; 0 is the root message. +pub type MessageId = u32; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) struct Span { + pub(crate) start: u32, + pub(crate) len: u32, +} + +impl Span { + pub(crate) fn range(self) -> std::ops::Range<usize> { + let start = self.start as usize; + start..start + self.len as usize + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct MessageEntry { + pub(crate) root: PartId, + pub(crate) parts_end: PartId, + pub(crate) source: u32, + pub(crate) container: PartId, + pub(crate) lists: u32, + pub(crate) text_len: u32, + pub(crate) html_len: u32, + pub(crate) attachments_len: u32, +} + +impl Blank for MessageEntry { + const BLANK: MessageEntry = MessageEntry { + root: NONE, + parts_end: NONE, + source: 0, + container: NONE, + lists: 0, + text_len: 0, + html_len: 0, + attachments_len: 0, + }; +} + +#[derive(Debug, Clone)] +pub(crate) struct Messages { + root: MessageEntry, + has_root: bool, + nested: Vec<MessageEntry>, +} + +impl Default for Messages { + fn default() -> Self { + Messages::EMPTY + } +} + +impl Messages { + pub(crate) const EMPTY: Messages = Messages { + root: MessageEntry::BLANK, + has_root: false, + nested: Vec::new(), + }; + + #[inline] + pub(crate) fn len(&self) -> usize { + usize::from(self.has_root) + self.nested.len() + } + + #[inline] + pub(crate) fn get(&self, index: usize) -> Option<&MessageEntry> { + match index.checked_sub(1) { + None => Some(&self.root), + Some(index) => self.nested.get(index), + } + } + + #[inline] + pub(crate) fn get_mut(&mut self, index: usize) -> Option<&mut MessageEntry> { + match index.checked_sub(1) { + None => Some(&mut self.root), + Some(index) => self.nested.get_mut(index), + } + } + + pub(crate) fn first(&self) -> Option<&MessageEntry> { + Some(&self.root) + } + + pub(crate) fn push(&mut self, entry: MessageEntry, first: usize) -> MessageId { + if !self.has_root { + self.root = entry; + self.has_root = true; + return 0; + } + if self.nested.capacity() == 0 { + self.nested.reserve_exact(first); + } + self.nested.push(entry); + self.nested.len() as MessageId + } + + pub(crate) fn pop(&mut self) -> Option<MessageEntry> { + self.nested.pop() + } + + pub(crate) fn clear(&mut self) { + self.root = MessageEntry::BLANK; + self.has_root = false; + self.nested.clear(); + } + + #[cfg(test)] + pub(crate) fn iter(&self) -> impl Iterator<Item = &MessageEntry> { + std::iter::once(&self.root) + .take(usize::from(self.has_root)) + .chain(&self.nested) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub(crate) enum KindTag { + Text, + Html, + Binary, + InlineBinary, + Multipart, + Message, +} + +pub(crate) mod flag { + pub(crate) const MISSING_DELIMITER: u16 = 1; + pub(crate) const FALLBACK_DELIMITER: u16 = 1 << 1; + pub(crate) const NO_BLANK_LINE: u16 = 1 << 2; + pub(crate) const UNTERMINATED: u16 = 1 << 3; + pub(crate) const NESTING_LIMIT: u16 = 1 << 4; + pub(crate) const LIMIT_REACHED: u16 = 1 << 5; + pub(crate) const MASK: u16 = 0xff; +} + +pub(crate) mod role { + pub(crate) const IN_TEXT_BODY: u16 = 1 << 8; + pub(crate) const IN_HTML_BODY: u16 = 1 << 9; + pub(crate) const ATTACHMENT: u16 = 1 << 10; + pub(crate) const INLINE: u16 = 1 << 11; + pub(crate) const COPIED: u16 = 1 << 12; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct PartEntry { + pub(crate) offset_header: u32, + pub(crate) offset_body: u32, + pub(crate) offset_end: u32, + pub(crate) headers: Span, + pub(crate) parent: PartId, + pub(crate) message: MessageId, + pub(crate) content_type: u32, + pub(crate) content_disposition: u32, + pub(crate) children: Span, + pub(crate) kind: KindTag, + pub(crate) encoding: Encoding, + pub(crate) flags: u16, +} + +impl PartEntry { + pub(crate) const EMPTY: PartEntry = PartEntry { + offset_header: 0, + offset_body: 0, + offset_end: 0, + headers: Span { start: 0, len: 0 }, + parent: NONE, + message: 0, + content_type: NONE, + content_disposition: NONE, + children: Span { start: 0, len: 0 }, + kind: KindTag::Text, + encoding: Encoding::None, + flags: 0, + }; + + pub(crate) fn has_role(&self, role: u16) -> bool { + self.flags & role != 0 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) enum Value { + #[default] + Empty, + Text(Str), + TextList(Span), + Address(Span), + DateTime(DateTime), + ContentType(u32), + Received(u32), +} + +pub(crate) const OTHER_NAME: u16 = u16::MAX; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct HeaderEntry { + pub(crate) offset_field: u32, + pub(crate) offset_start: u32, + pub(crate) offset_end: u32, + pub(crate) value: Value, + pub(crate) name: u16, + pub(crate) other_name: u32, +} + +pub(crate) const GROUP_BIT: u32 = 1 << 31; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct AddressEntry { + pub(crate) name: Str, + pub(crate) address: Str, + pub(crate) group: u32, +} + +impl Blank for AddressEntry { + const BLANK: AddressEntry = AddressEntry { + name: Str::NONE, + address: Str::NONE, + group: 0, + }; +} + +impl AddressEntry { + pub(crate) fn is_group(&self) -> bool { + self.group & GROUP_BIT != 0 + } + + pub(crate) fn members(&self) -> usize { + (self.group & !GROUP_BIT) as usize + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ParamEntry { + pub(crate) name: Str, + pub(crate) value: Str, +} + +impl Blank for ParamEntry { + const BLANK: ParamEntry = ParamEntry { + name: Str::NONE, + value: Str::NONE, + }; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ContentTypeEntry { + pub(crate) ctype: Str, + pub(crate) subtype: Str, + pub(crate) params: Span, +} + +impl Blank for ContentTypeEntry { + const BLANK: ContentTypeEntry = ContentTypeEntry { + ctype: Str::NONE, + subtype: Str::NONE, + params: Span { start: 0, len: 0 }, + }; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) enum HostEntry { + #[default] + None, + Name(Str), + Ip(IpAddr), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ReceivedEntry { + pub(crate) from: HostEntry, + pub(crate) from_ip: Option<IpAddr>, + pub(crate) from_iprev: Str, + pub(crate) by: HostEntry, + pub(crate) for_: Str, + pub(crate) with: Option<Protocol>, + pub(crate) tls_version: Option<TlsVersion>, + pub(crate) tls_cipher: Str, + pub(crate) id: Str, + pub(crate) ident: Str, + pub(crate) helo: HostEntry, + pub(crate) helo_cmd: Option<Greeting>, + pub(crate) via: Str, + pub(crate) date: Option<DateTime>, +} + +impl ReceivedEntry { + pub(crate) const EMPTY: ReceivedEntry = ReceivedEntry { + from: HostEntry::None, + from_ip: None, + from_iprev: Str::NONE, + by: HostEntry::None, + for_: Str::NONE, + with: None, + tls_version: None, + tls_cipher: Str::NONE, + id: Str::NONE, + ident: Str::NONE, + helo: HostEntry::None, + helo_cmd: None, + via: Str::NONE, + date: None, + }; +} + +impl Default for ReceivedEntry { + fn default() -> Self { + ReceivedEntry::EMPTY + } +} + +#[derive(Debug, Clone, Default)] +pub(crate) struct Scratch { + pub(crate) frames: Vec<crate::parser::Frame>, + pub(crate) pending: Vec<PartId>, + pub(crate) bytes: Vec<u8>, + pub(crate) text: String, + pub(crate) continuations: Vec<(Str, u32, Str)>, +} + +impl Scratch { + const EMPTY: Scratch = Scratch { + frames: Vec::new(), + pending: Vec::new(), + bytes: Vec::new(), + text: String::new(), + continuations: Vec::new(), + }; + + fn clear(&mut self) { + self.frames.clear(); + self.pending.clear(); + self.bytes.clear(); + self.text.clear(); + self.continuations.clear(); + } +} + +#[derive(Debug, Clone)] +pub(crate) struct SourceBuffer { + pub(crate) bytes: Box<[u8]>, + pub(crate) container: PartId, +} + +#[derive(Debug, Clone, Default)] +pub(crate) struct MessageData { + pub(crate) messages: Messages, + pub(crate) parts: Vec<PartEntry>, + pub(crate) headers: Vec<HeaderEntry>, + pub(crate) ids: Table<PartId, INLINE_IDS>, + pub(crate) address_items: Table<AddressEntry, INLINE_ADDRESS_ITEMS>, + pub(crate) params: Table<ParamEntry, INLINE_PARAMS>, + pub(crate) content_types: Table<ContentTypeEntry, INLINE_CONTENT_TYPES>, + pub(crate) text_items: Table<Str, INLINE_TEXT_ITEMS>, + pub(crate) received: Vec<ReceivedEntry>, + pub(crate) strings: String, + pub(crate) sources: Vec<SourceBuffer>, + pub(crate) scratch: Scratch, +} + +impl MessageData { + pub(crate) const EMPTY: MessageData = MessageData { + messages: Messages::EMPTY, + parts: Vec::new(), + headers: Vec::new(), + ids: Table::EMPTY, + address_items: Table::EMPTY, + params: Table::EMPTY, + content_types: Table::EMPTY, + text_items: Table::EMPTY, + received: Vec::new(), + strings: String::new(), + sources: Vec::new(), + scratch: Scratch::EMPTY, + }; + + pub(crate) fn empty_message() -> Self { + let mut messages = Messages::EMPTY; + messages.push( + MessageEntry { + root: 0, + parts_end: 1, + ..MessageEntry::BLANK + }, + 0, + ); + MessageData { + messages, + parts: vec![PartEntry::EMPTY], + ..MessageData::EMPTY + } + } + + fn capacity_bytes(&self) -> usize { + [ + vec_bytes(&self.messages.nested), + vec_bytes(&self.parts), + vec_bytes(&self.headers), + self.ids.capacity_bytes(), + self.address_items.capacity_bytes(), + self.params.capacity_bytes(), + self.content_types.capacity_bytes(), + self.text_items.capacity_bytes(), + vec_bytes(&self.received), + self.strings.capacity(), + vec_bytes(&self.sources), + self.sources.iter().map(|source| source.bytes.len()).sum(), + vec_bytes(&self.scratch.frames), + vec_bytes(&self.scratch.pending), + self.scratch.bytes.capacity(), + self.scratch.text.capacity(), + vec_bytes(&self.scratch.continuations), + ] + .into_iter() + .sum() + } + + pub(crate) fn push_text_item(&mut self, item: Str) -> u32 { + let index = self.text_items.len() as u32; + self.text_items.push(item, FIRST_TEXT_ITEMS); + index + } + + pub(crate) fn clear(&mut self) { + self.messages.clear(); + self.parts.clear(); + self.headers.clear(); + self.ids.clear(); + self.address_items.clear(); + self.params.clear(); + self.content_types.clear(); + self.text_items.clear(); + self.received.clear(); + self.strings.clear(); + self.sources.clear(); + self.scratch.clear(); + } + + pub(crate) fn source<'a>(&'a self, raw: &'a [u8], source: u32) -> &'a [u8] { + match source.checked_sub(1) { + None => raw, + Some(index) => self + .sources + .get(index as usize) + .map_or(&[], |source| source.bytes.as_ref()), + } + } + + pub(crate) fn source_container(&self, source: u32) -> Option<PartId> { + self.sources + .get(source.checked_sub(1)? as usize) + .map(|source| source.container) + } + + pub(crate) fn message_source<'a>(&'a self, raw: &'a [u8], message: MessageId) -> &'a [u8] { + if message == 0 { + return raw; + } + self.messages + .get(message as usize) + .map_or(raw, |entry| self.source(raw, entry.source)) + } +} + +/// Reusable storage for [`crate::MessageParser::parse_with`]. +/// +/// A parsed message keeps its parts, headers and values in a handful of +/// vectors. Parsing many messages one after the other (an mbox or Maildir +/// import, classifier training, a batch of messages from a queue) can reuse +/// those vectors instead of allocating new ones for every message: pass the +/// buffers to `parse_with`, and when done with the message, get them back +/// with [`crate::Message::into_buffers`]. Once the vectors have grown to +/// fit the messages, parsing allocates nothing. +/// +/// There is no hidden state: dropping a message instead of calling +/// `into_buffers` only means the next parse allocates, and dropping the +/// buffers frees the memory they hold. +/// +/// The vectors never shrink on their own: they keep the capacity of the +/// largest message parsed with them, so one very large message in a batch +/// holds its memory for the rest of the loop. [`MessageBuffers::shrink_to`] +/// bounds that memory between two parses. +/// +/// ``` +/// use mail_parser::{MessageBuffers, MessageParser, mailbox::mbox::MessageIterator}; +/// +/// let mbox = b"From a@example.com Sat Jan 3 01:05:34 1996\n\ +/// Subject: first\n\nbody\n\ +/// From b@example.com Sat Jan 3 01:05:35 1996\n\ +/// Subject: second\n\nbody\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("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"]); +/// ``` +#[derive(Clone, Default)] +pub struct MessageBuffers { + pub(crate) data: MessageData, +} + +impl fmt::Debug for MessageBuffers { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MessageBuffers").finish_non_exhaustive() + } +} + +impl MessageBuffers { + /// Empty buffers; they grow to fit the messages parsed with them. + pub fn new() -> Self { + MessageBuffers::default() + } + + /// Frees the memory held by the buffers when it exceeds `max_bytes`, + /// so that they hold at most `max_bytes` afterwards; the next parse then + /// allocates again. Call it between two parses, for example after + /// [`crate::Message::into_buffers`] in a batch loop, to keep one large + /// message from pinning its memory. It costs nothing when the buffers + /// are within the bound. + /// + /// ``` + /// use mail_parser::{MessageBuffers, MessageParser}; + /// + /// let parser = MessageParser::new(); + /// let mut buffers = MessageBuffers::new(); + /// for raw in [&b"Subject: small\n\nbody\n"[..], b"Subject: next\n\nbody\n"] { + /// if let Some(message) = parser.parse_with(raw, &mut buffers) { + /// assert!(message.subject().is_some()); + /// buffers = message.into_buffers(); + /// buffers.shrink_to(1 << 20); + /// } + /// } + /// ``` + pub fn shrink_to(&mut self, max_bytes: usize) { + if self.data.capacity_bytes() > max_bytes { + self.data = MessageData::default(); + } + } +} + +fn vec_bytes<T>(items: &Vec<T>) -> usize { + items.capacity() * size_of::<T>() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::size_of; + + #[test] + fn root_message_stays_inline() { + let entry = |root| MessageEntry { + root, + ..MessageEntry::BLANK + }; + let mut messages = Messages::default(); + assert_eq!(messages.len(), 0); + assert_eq!(messages.iter().count(), 0); + assert_eq!(messages.get(0), Some(&MessageEntry::BLANK)); + assert_eq!(messages.push(entry(1), 8), 0); + assert_eq!(messages.push(entry(2), 8), 1); + assert_eq!(messages.push(entry(3), 8), 2); + assert_eq!(messages.len(), 3); + assert_eq!( + messages.iter().map(|entry| entry.root).collect::<Vec<_>>(), + [1, 2, 3] + ); + if let Some(nested) = messages.get_mut(1) { + nested.root = 7; + } + assert_eq!(messages.get(1).map(|entry| entry.root), Some(7)); + assert_eq!(messages.get(3), None); + assert_eq!(messages.pop().map(|entry| entry.root), Some(3)); + assert_eq!(messages.first().map(|entry| entry.root), Some(1)); + messages.clear(); + assert_eq!(messages.len(), 0); + assert_eq!(messages.push(entry(4), 8), 0); + assert_eq!(messages.len(), 1); + } + + #[test] + fn buffers_shrink_above_the_bound() { + let mut raw = b"Content-Type: multipart/mixed; boundary=b\n\n".to_vec(); + for index in 0..500 { + raw.extend_from_slice(format!("--b\nX-Index: {index}\n\npart {index}\n").as_bytes()); + } + raw.extend_from_slice(b"--b--\n"); + let parser = crate::MessageParser::new(); + let mut buffers = MessageBuffers::new(); + assert_eq!(buffers.data.capacity_bytes(), 0); + let message = parser.parse_with(&raw, &mut buffers).expect("parses"); + buffers = message.into_buffers(); + let held = buffers.data.capacity_bytes(); + assert!(held >= 501 * size_of::<PartEntry>()); + buffers.shrink_to(held); + assert_eq!(buffers.data.capacity_bytes(), held); + buffers.shrink_to(held - 1); + assert_eq!(buffers.data.capacity_bytes(), 0); + } + + #[test] + fn empty_message_has_one_root_part() { + let data = MessageData::empty_message(); + assert_eq!(data.messages.len(), 1); + assert_eq!(data.messages.first().map(|entry| entry.root), Some(0)); + assert_eq!(data.parts, [PartEntry::EMPTY]); + assert_eq!(data.source_container(0), None); + assert_eq!(data.source_container(1), None); + } + + #[test] + fn entry_sizes() { + assert_eq!(size_of::<Str>(), 8); + assert_eq!(size_of::<Value>(), 12); + assert_eq!(size_of::<MessageEntry>(), 32); + assert_eq!(size_of::<PartEntry>(), 48); + assert_eq!(size_of::<HeaderEntry>(), 32); + assert_eq!(size_of::<AddressEntry>(), 20); + assert_eq!(size_of::<ParamEntry>(), 16); + assert_eq!(size_of::<ContentTypeEntry>(), 24); + assert!(size_of::<ReceivedEntry>() <= 160); + assert!(size_of::<crate::parser::Frame>() <= 96); + } +} diff --git a/src/store/str.rs b/src/store/str.rs new file mode 100644 index 0000000..1bce9ab --- /dev/null +++ b/src/store/str.rs @@ -0,0 +1,200 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use std::ops::Range; + +const POOL_BIT: u32 = 1 << 31; +const MAX_LEN: usize = (POOL_BIT - 1) as usize; +const NONE_LEN: u32 = u32::MAX; +const FIRST_POOL: usize = 256; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Str { + start: u32, + len: u32, +} + +impl super::Blank for Str { + const BLANK: Str = Str::NONE; +} + +impl Default for Str { + fn default() -> Self { + Str::EMPTY + } +} + +impl Str { + pub(crate) const EMPTY: Str = Str { + start: 0, + len: POOL_BIT, + }; + pub(crate) const NONE: Str = Str { + start: u32::MAX, + len: NONE_LEN, + }; + + pub(crate) fn is_none(self) -> bool { + self.len == NONE_LEN + } + + pub(crate) fn is_some(self) -> bool { + !self.is_none() + } + + pub(crate) fn from_option(value: Option<Str>) -> Str { + value.unwrap_or(Str::NONE) + } + + pub(crate) fn len(self) -> usize { + if self.is_none() { + 0 + } else { + (self.len & !POOL_BIT) as usize + } + } + + pub(crate) fn is_empty(self) -> bool { + self.len() == 0 + } + + fn is_pool(self) -> bool { + self.len & POOL_BIT != 0 + } + + fn range(self) -> Range<usize> { + let start = self.start as usize; + start..start + self.len() + } + + #[inline] + pub(crate) fn borrow(source: &[u8], range: Range<usize>) -> Option<Str> { + let bytes = source.get(range.clone())?; + let len = bytes.len(); + if len > MAX_LEN || range.start > u32::MAX as usize || !bytes.is_ascii() && !is_utf8(bytes) + { + return None; + } + Some(Str { + start: range.start as u32, + len: len as u32, + }) + } + + pub(crate) fn push(pool: &mut String, text: &str) -> Str { + Str::push_with(pool, |pool| pool.push_str(text)) + } + + pub(crate) fn push_with(pool: &mut String, write: impl FnOnce(&mut String)) -> Str { + if pool.capacity() == 0 { + pool.reserve(FIRST_POOL); + } + let start = pool.len(); + write(pool); + let end = pool.len(); + if end > MAX_LEN || start > u32::MAX as usize { + pool.truncate(start); + return Str::EMPTY; + } + Str { + start: start as u32, + len: (end - start) as u32 | POOL_BIT, + } + } + + #[inline] + pub(crate) fn resolve<'a>(self, source: &'a [u8], pool: &'a str) -> &'a str { + if self.is_none() { + return ""; + } + if self.is_pool() { + return pool.get(self.range()).unwrap_or_default(); + } + source.get(self.range()).map_or("", source_str) + } + + pub(crate) fn resolve_option<'a>(self, source: &'a [u8], pool: &'a str) -> Option<&'a str> { + self.is_some().then(|| self.resolve(source, pool)) + } +} + +#[inline(never)] +fn is_utf8(bytes: &[u8]) -> bool { + simdutf8::basic::from_utf8(bytes).is_ok() +} + +pub(crate) fn validated_string(bytes: Vec<u8>) -> Result<String, Vec<u8>> { + if is_utf8(&bytes) { + Ok(owned_str(bytes)) + } else { + Err(bytes) + } +} + +#[cfg(not(mail_parser_checked_str))] +#[allow(unsafe_code)] +fn source_str(bytes: &[u8]) -> &str { + debug_assert!(simdutf8::basic::from_utf8(bytes).is_ok()); + // SAFETY: the only caller, `Str::resolve`, passes `source[range]` for a + // span that is neither `NONE` nor in the pool. Only `Str::borrow` builds + // such a span (the fields of `Str` are private to this module), after + // checking that `source[range]` is ASCII or valid UTF-8 (simdutf8). The + // crate resolves every span against the same immutable buffer it was + // borrowed from: the raw input for message 0, the decoded + // `SourceBuffer` of a nested message (`MessageData::message_source`, + // with the message id of the part that owns the span), or the buffer + // held by the `FieldCtx`, `Resolver` or `ParsedValue` that borrowed it. + // `MessageData::clear` drops every span before the store is reused, and + // a nested source is popped only when its message has no part, so no + // span borrowed from it survives. + unsafe { std::str::from_utf8_unchecked(bytes) } +} + +#[cfg(mail_parser_checked_str)] +fn source_str(bytes: &[u8]) -> &str { + simdutf8::basic::from_utf8(bytes).unwrap_or_default() +} + +#[cfg(not(mail_parser_checked_str))] +#[allow(unsafe_code)] +fn owned_str(bytes: Vec<u8>) -> String { + // SAFETY: the only caller, `validated_string`, passes `bytes` after + // `is_utf8` (simdutf8) accepted the whole vector, which is moved here + // unchanged. + unsafe { String::from_utf8_unchecked(bytes) } +} + +#[cfg(mail_parser_checked_str)] +fn owned_str(bytes: Vec<u8>) -> String { + String::from_utf8(bytes).unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::Str; + + #[test] + fn borrow_validates_utf8() { + let source = "héllo wörld".as_bytes(); + let span = Str::borrow(source, 0..source.len()).expect("valid"); + assert_eq!(span.resolve(source, ""), "héllo wörld"); + assert!(Str::borrow(source, 0..2).is_none()); + assert!(Str::borrow(source, 0..100).is_none()); + assert!(Str::borrow(b"\xff\xfe", 0..2).is_none()); + } + + #[test] + fn pool_strings() { + let mut pool = String::new(); + let first = Str::push(&mut pool, "abc"); + let second = Str::push_with(&mut pool, |pool| pool.push_str("défg")); + assert_eq!(first.resolve(b"", &pool), "abc"); + assert_eq!(second.resolve(b"", &pool), "défg"); + assert_eq!(Str::EMPTY.resolve(b"xyz", &pool), ""); + assert_eq!(Str::NONE.resolve_option(b"xyz", &pool), None); + assert!(Str::EMPTY.is_empty() && Str::EMPTY.is_some()); + } +} diff --git a/src/store/table.rs b/src/store/table.rs new file mode 100644 index 0000000..95d3902 --- /dev/null +++ b/src/store/table.rs @@ -0,0 +1,177 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use std::ops::{Deref, DerefMut}; + +pub(crate) trait Blank: Copy { + const BLANK: Self; +} + +impl Blank for u32 { + const BLANK: u32 = 0; +} + +#[derive(Debug, Clone)] +pub(crate) enum Table<T: Blank, const N: usize> { + Inline([T; N], u32), + Spill(Vec<T>), +} + +impl<T: Blank, const N: usize> Default for Table<T, N> { + fn default() -> Self { + Table::EMPTY + } +} + +impl<T: Blank, const N: usize> Table<T, N> { + pub(crate) const EMPTY: Self = Table::Inline([T::BLANK; N], 0); + + #[inline] + pub(crate) fn push(&mut self, item: T, first: usize) { + match self { + Table::Inline(items, len) => match items.get_mut(*len as usize) { + Some(slot) => { + *slot = item; + *len += 1; + } + None => self.spill(item, first), + }, + Table::Spill(spill) => spill.push(item), + } + } + + #[inline(never)] + fn spill(&mut self, item: T, first: usize) { + let mut spill = Vec::with_capacity(first.max(N + 1)); + spill.extend_from_slice(self); + spill.push(item); + *self = Table::Spill(spill); + } + + pub(crate) fn extend_from_slice(&mut self, items: &[T], first: usize) { + match self { + Table::Spill(spill) => spill.extend_from_slice(items), + Table::Inline(..) => items.iter().for_each(|item| self.push(*item, first)), + } + } + + pub(crate) fn resize(&mut self, new_len: usize, value: T, first: usize) { + if new_len <= self.len() { + self.truncate(new_len); + return; + } + match self { + Table::Spill(spill) => spill.resize(new_len, value), + Table::Inline(..) => (self.len()..new_len).for_each(|_| self.push(value, first)), + } + } + + pub(crate) fn truncate(&mut self, new_len: usize) { + match self { + Table::Inline(_, len) => *len = (*len).min(u32::try_from(new_len).unwrap_or(u32::MAX)), + Table::Spill(spill) => spill.truncate(new_len), + } + } + + pub(crate) fn clear(&mut self) { + match self { + Table::Inline(_, len) => *len = 0, + Table::Spill(spill) => spill.clear(), + } + } + + #[inline] + pub(crate) fn len(&self) -> usize { + match self { + Table::Inline(_, len) => *len as usize, + Table::Spill(spill) => spill.len(), + } + } + + pub(crate) fn capacity_bytes(&self) -> usize { + match self { + Table::Inline(..) => 0, + Table::Spill(spill) => spill.capacity() * size_of::<T>(), + } + } + + #[cfg(test)] + pub(crate) fn is_spilled(&self) -> bool { + matches!(self, Table::Spill(_)) + } +} + +impl<T: Blank, const N: usize> Deref for Table<T, N> { + type Target = [T]; + + #[inline] + fn deref(&self) -> &[T] { + match self { + Table::Inline(items, len) => items.get(..*len as usize).unwrap_or_default(), + Table::Spill(spill) => spill, + } + } +} + +impl<T: Blank, const N: usize> DerefMut for Table<T, N> { + #[inline] + fn deref_mut(&mut self) -> &mut [T] { + match self { + Table::Inline(items, len) => items.get_mut(..*len as usize).unwrap_or_default(), + Table::Spill(spill) => spill, + } + } +} + +#[cfg(test)] +mod tests { + use super::Table; + + #[test] + fn inline_then_spill() { + let mut table: Table<u32, 2> = Table::default(); + let mut reference = Vec::new(); + for value in 0..40u32 { + table.push(value, 4); + reference.push(value); + assert_eq!(&*table, reference.as_slice()); + assert_eq!(table.is_spilled(), reference.len() > 2); + } + table.truncate(5); + reference.truncate(5); + assert_eq!(&*table, reference.as_slice()); + table.resize(9, 7, 4); + reference.resize(9, 7); + assert_eq!(&*table, reference.as_slice()); + table.clear(); + assert!(table.is_empty() && table.is_spilled()); + table.push(3, 4); + assert_eq!(&*table, &[3]); + } + + #[test] + fn inline_operations() { + let mut table: Table<u32, 4> = Table::default(); + table.extend_from_slice(&[1, 2, 3], 8); + assert_eq!(&*table, &[1, 2, 3]); + assert!(!table.is_spilled()); + table.resize(4, 9, 8); + assert_eq!(&*table, &[1, 2, 3, 9]); + assert!(!table.is_spilled()); + if let Some(first) = table.first_mut() { + *first = 5; + } + table.truncate(1); + assert_eq!(&*table, &[5]); + table.resize(6, 0, 8); + assert_eq!(&*table, &[5, 0, 0, 0, 0, 0]); + assert!(table.is_spilled()); + let mut empty: Table<u32, 1> = Table::default(); + empty.truncate(3); + empty.clear(); + assert!(empty.is_empty()); + } +} diff --git a/src/view/address.rs b/src/view/address.rs new file mode 100644 index 0000000..cd3db99 --- /dev/null +++ b/src/view/address.rs @@ -0,0 +1,248 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::Resolver; +use crate::store::AddressEntry; +use std::fmt; + +/// An address list: mailboxes and groups in document order (issue #98). +/// Lists compare by content. +/// +/// ``` +/// use mail_parser::{Address, MessageParser}; +/// +/// let raw = b"To: Ann <ann@example.com>, team: bob@example.com, cy@example.com;\r\n\r\n"; +/// let message = MessageParser::new().parse(raw).expect("message"); +/// let to = message.to().expect("addresses"); +/// let addresses: Vec<_> = to.mailboxes().filter_map(|mailbox| mailbox.address()).collect(); +/// assert_eq!(addresses, ["ann@example.com", "bob@example.com", "cy@example.com"]); +/// assert!(matches!(to.iter().nth(1), Some(Address::Group(group)) if group.name() == Some("team"))); +/// assert!(to.contains("BOB@example.com")); +/// ``` +#[derive(Clone, Copy)] +pub struct AddressList<'m> { + resolver: Resolver<'m>, + items: &'m [AddressEntry], +} + +/// One item of an address list. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Address<'m> { + /// A mailbox outside any group. + Mailbox(Mailbox<'m>), + /// A group and its mailboxes. + Group(Group<'m>), +} + +/// A mailbox: a display name and an address (or a URL in RFC 2369 list +/// headers). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Mailbox<'m> { + name: Option<&'m str>, + address: Option<&'m str>, +} + +/// A named group of mailboxes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Group<'m> { + name: Option<&'m str>, + members: AddressRun<'m>, +} + +/// A run of consecutive mailboxes: the members of a [`Group`], or a run +/// yielded by [`AddressList::groups`]. It is an iterator of [`Mailbox`], and +/// runs compare by content. +#[derive(Clone, Copy)] +pub struct AddressRun<'m> { + resolver: Resolver<'m>, + items: &'m [AddressEntry], +} + +impl fmt::Debug for AddressList<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl fmt::Debug for AddressRun<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(*self).finish() + } +} + +impl PartialEq for AddressList<'_> { + fn eq(&self, other: &Self) -> bool { + self.items.len() == other.items.len() && self.iter().eq(other.iter()) + } +} + +impl Eq for AddressList<'_> {} + +impl PartialEq for AddressRun<'_> { + fn eq(&self, other: &Self) -> bool { + self.items.len() == other.items.len() && Iterator::eq(*self, *other) + } +} + +impl Eq for AddressRun<'_> {} + +fn mailbox<'m>(resolver: Resolver<'m>, entry: &AddressEntry) -> Mailbox<'m> { + Mailbox { + name: resolver.opt(entry.name), + address: resolver.opt(entry.address), + } +} + +impl<'m> AddressList<'m> { + pub(crate) fn new(resolver: Resolver<'m>, items: &'m [AddressEntry]) -> Self { + AddressList { resolver, items } + } + + /// Whether the list has neither mailboxes nor groups. + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + /// Mailboxes and groups in document order. + pub fn iter(&self) -> impl Iterator<Item = Address<'m>> + use<'m> { + let resolver = self.resolver; + let mut rest = self.items; + std::iter::from_fn(move || { + let (first, tail) = rest.split_first()?; + if first.is_group() { + let (members, tail) = tail.split_at(first.members().min(tail.len())); + rest = tail; + Some(Address::Group(Group { + name: resolver.opt(first.name), + members: AddressRun { + resolver, + items: members, + }, + })) + } else { + rest = tail; + Some(Address::Mailbox(mailbox(resolver, first))) + } + }) + } + + /// Every mailbox, groups flattened. + pub fn mailboxes(&self) -> impl DoubleEndedIterator<Item = Mailbox<'m>> + use<'m> { + let resolver = self.resolver; + self.items + .iter() + .filter(|entry| !entry.is_group()) + .map(move |entry| mailbox(resolver, entry)) + } + + /// The first mailbox, groups flattened. + pub fn first(&self) -> Option<Mailbox<'m>> { + self.mailboxes().next() + } + + /// The last mailbox, groups flattened. + pub fn last(&self) -> Option<Mailbox<'m>> { + self.mailboxes().next_back() + } + + /// The JMAP `asGroupedAddresses` shape (RFC 8621): each group with its + /// name, and each run of mailboxes outside groups as an unnamed group. + pub fn groups(&self) -> impl Iterator<Item = (Option<&'m str>, AddressRun<'m>)> + use<'m> { + let resolver = self.resolver; + let mut rest = self.items; + std::iter::from_fn(move || { + let (first, tail) = rest.split_first()?; + let (name, run, tail) = if first.is_group() { + let (members, tail) = tail.split_at(first.members().min(tail.len())); + (resolver.opt(first.name), members, tail) + } else { + let len = rest.iter().take_while(|entry| !entry.is_group()).count(); + let (run, tail) = rest.split_at(len); + (None, run, tail) + }; + rest = tail; + Some(( + name, + AddressRun { + resolver, + items: run, + }, + )) + }) + } + + /// Whether any mailbox has this address (ASCII case-insensitive). + pub fn contains(&self, address: &str) -> bool { + self.mailboxes().any(|mailbox| { + mailbox + .address + .is_some_and(|a| a.eq_ignore_ascii_case(address)) + }) + } + + /// Whether the list contains at least one group. + pub fn has_groups(&self) -> bool { + self.items.iter().any(AddressEntry::is_group) + } +} + +impl<'m> Mailbox<'m> { + /// The display name, decoded and unquoted. + pub fn name(&self) -> Option<&'m str> { + self.name + } + + /// The address (`local@domain`), or the URL of an RFC 2369 list header. + pub fn address(&self) -> Option<&'m str> { + self.address + } +} + +impl<'m> Group<'m> { + /// The group name, decoded and unquoted. + pub fn name(&self) -> Option<&'m str> { + self.name + } + + /// The members of the group. + pub fn mailboxes(&self) -> AddressRun<'m> { + self.members + } + + /// Number of members. + pub fn len(&self) -> usize { + self.members.len() + } + + /// Whether the group has no member. + pub fn is_empty(&self) -> bool { + self.members.len() == 0 + } +} + +impl<'m> Iterator for AddressRun<'m> { + type Item = Mailbox<'m>; + + fn next(&mut self) -> Option<Mailbox<'m>> { + let (first, rest) = self.items.split_first()?; + self.items = rest; + Some(mailbox(self.resolver, first)) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + (self.items.len(), Some(self.items.len())) + } +} + +impl DoubleEndedIterator for AddressRun<'_> { + fn next_back(&mut self) -> Option<Self::Item> { + let (last, rest) = self.items.split_last()?; + self.items = rest; + Some(mailbox(self.resolver, last)) + } +} + +impl ExactSizeIterator for AddressRun<'_> {} diff --git a/src/view/content_type.rs b/src/view/content_type.rs new file mode 100644 index 0000000..2bf9853 --- /dev/null +++ b/src/view/content_type.rs @@ -0,0 +1,120 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::Resolver; +use crate::store::{ContentTypeEntry, MessageData, ParamEntry}; +use std::fmt; + +struct Attributes<'m>(ContentType<'m>); + +/// A Content-Type or Content-Disposition value. Type, subtype and +/// parameter names are lowercase; RFC 2231 and RFC 2047 encoded parameter +/// values are decoded. Values compare by content. +/// +/// ``` +/// use mail_parser::MessageParser; +/// +/// let raw = b"Content-Type: Text/Plain; Charset=\"utf-8\"; format=flowed\r\n\r\nbody"; +/// let message = MessageParser::new().parse(raw).expect("message"); +/// let content_type = message.content_type().expect("content type"); +/// assert_eq!((content_type.ctype(), content_type.subtype()), ("text", Some("plain"))); +/// assert_eq!(content_type.attribute("charset"), Some("utf-8")); +/// assert!(message.is_content_type("text", "plain")); +/// ``` +#[derive(Clone, Copy)] +pub struct ContentType<'m> { + resolver: Resolver<'m>, + entry: &'m ContentTypeEntry, + params: &'m [ParamEntry], +} + +impl<'m> ContentType<'m> { + #[inline] + pub(crate) fn new( + resolver: Resolver<'m>, + data: &'m MessageData, + entry: &'m ContentTypeEntry, + ) -> Self { + ContentType { + resolver, + entry, + params: data.params.get(entry.params.range()).unwrap_or_default(), + } + } + + /// The type (`text`, `multipart`, `attachment`, ...). + #[inline] + pub fn ctype(&self) -> &'m str { + self.resolver.str(self.entry.ctype) + } + + /// The subtype (`plain`, `mixed`, ...); `None` for a disposition or a + /// type without `/`. + #[inline] + pub fn subtype(&self) -> Option<&'m str> { + self.resolver.opt(self.entry.subtype) + } + + /// The first parameter with this (lowercase) name. + pub fn attribute(&self, name: &str) -> Option<&'m str> { + self.attributes() + .find(|(param, _)| *param == name) + .map(|(_, value)| value) + } + + /// Every parameter in document order. + #[inline] + pub fn attributes( + &self, + ) -> impl ExactSizeIterator<Item = (&'m str, &'m str)> + DoubleEndedIterator + use<'m> { + let resolver = self.resolver; + self.params + .iter() + .map(move |param| (resolver.str(param.name), resolver.str(param.value))) + } + + /// Whether a parameter with this (lowercase) name is present. + pub fn has_attribute(&self, name: &str) -> bool { + self.attribute(name).is_some() + } + + /// Whether this is `Content-Disposition: attachment`. + pub fn is_attachment(&self) -> bool { + self.ctype().eq_ignore_ascii_case("attachment") + } + + /// Whether this is `Content-Disposition: inline`. + pub fn is_inline(&self) -> bool { + self.ctype().eq_ignore_ascii_case("inline") + } +} + +impl fmt::Debug for Attributes<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_map().entries(self.0.attributes()).finish() + } +} + +impl fmt::Debug for ContentType<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ContentType") + .field("type", &self.ctype()) + .field("subtype", &self.subtype()) + .field("attributes", &Attributes(*self)) + .finish() + } +} + +impl PartialEq for ContentType<'_> { + fn eq(&self, other: &Self) -> bool { + self.ctype() == other.ctype() + && self.subtype() == other.subtype() + && self.params.len() == other.params.len() + && self.attributes().eq(other.attributes()) + } +} + +impl Eq for ContentType<'_> {} diff --git a/src/view/headers.rs b/src/view/headers.rs new file mode 100644 index 0000000..2319312 --- /dev/null +++ b/src/view/headers.rs @@ -0,0 +1,766 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{AddressList, ContentType, Received, Resolver}; +use crate::{ + DateTime, HeaderForm, HeaderName, ParsedValue, + header_name::{self, HeaderId, HeaderKey}, + store::{HeaderEntry, MessageData, NONE, OTHER_NAME, Str, Value}, + thread_name, +}; +use std::{borrow::Cow, fmt, iter::FusedIterator, slice}; + +/// The header fields of one part, in the order they were written. +/// +/// Accessors that return one field ([`Headers::get`], [`Headers::value`], +/// [`Headers::subject`], ...) return the last occurrence of the name, as +/// 0.11 did. Names compare ASCII case-insensitively. +/// +/// ``` +/// use mail_parser::{HeaderName, MessageParser}; +/// +/// let raw = b"Subject: first\r\nX-Tag: a\r\nSubject: second\r\n\r\nbody"; +/// let message = MessageParser::new().parse(raw).expect("message"); +/// let headers = message.headers(); +/// assert_eq!(headers.len(), 3); +/// assert_eq!(headers.subject(), Some("second")); +/// assert_eq!(headers.all(HeaderName::Subject).count(), 2); +/// assert_eq!(headers.get("x-tag").map(|header| header.raw_value()), Some(&b" a\r\n"[..])); +/// ``` +#[derive(Clone, Copy)] +pub struct Headers<'m> { + resolver: Resolver<'m>, + data: &'m MessageData, + entries: &'m [HeaderEntry], +} + +/// One header field: its name, its parsed value, and where it is in the +/// source buffer of its message (see [`crate::MessageRef::source`]). +#[derive(Clone, Copy)] +pub struct Header<'m> { + resolver: Resolver<'m>, + data: &'m MessageData, + entry: &'m HeaderEntry, +} + +/// A parsed header value. The variant follows the [`HeaderForm`] the parser +/// used for the name (see [`crate::MessageParser::header`]). Values compare +/// by content. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum HeaderValue<'m> { + /// No parsable value: a value that does not parse in its form (an empty + /// address list, date or Content-Type included), or a field parsed with + /// [`HeaderForm::Ignore`]. + #[default] + Empty, + /// The trimmed field ([`HeaderForm::Raw`]) or its decoded text + /// ([`HeaderForm::Text`]); an empty string for a field that is present + /// but blank. + Text(&'m str), + /// Message identifiers ([`HeaderForm::MessageIds`]) or phrases + /// ([`HeaderForm::CommaList`]); always a list, even with one item. + TextList(TextList<'m>), + /// Mailboxes and groups ([`HeaderForm::Addresses`]). + Address(AddressList<'m>), + /// A date ([`HeaderForm::Date`]). + DateTime(DateTime), + /// A Content-Type or Content-Disposition value + /// ([`HeaderForm::ContentType`]). + ContentType(ContentType<'m>), + /// A Received trace field ([`HeaderForm::Received`]). + Received(Received<'m>), +} + +/// The headers with one name, returned by [`Headers::all`]. +#[derive(Clone)] +pub struct NamedHeaders<'m, 'n> { + headers: Headers<'m>, + rest: &'m [HeaderEntry], + name: HeaderName<'n>, + id: u16, +} + +impl<'m> Iterator for NamedHeaders<'m, '_> { + type Item = Header<'m>; + + #[inline] + fn next(&mut self) -> Option<Header<'m>> { + while let Some((entry, rest)) = self.rest.split_first() { + self.rest = rest; + if self.headers.matches(entry, self.name.as_str(), self.id) { + return Some(self.headers.header(entry)); + } + } + None + } +} + +/// Every header of a part in document order, returned by [`Headers::iter`] +/// and by iterating a [`Headers`] value. +#[derive(Clone)] +pub struct HeaderIter<'m> { + headers: Headers<'m>, + entries: slice::Iter<'m, HeaderEntry>, +} + +impl<'m> Iterator for HeaderIter<'m> { + type Item = Header<'m>; + + fn next(&mut self) -> Option<Header<'m>> { + self.entries.next().map(|entry| self.headers.header(entry)) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.entries.size_hint() + } +} + +impl<'m> DoubleEndedIterator for HeaderIter<'m> { + fn next_back(&mut self) -> Option<Header<'m>> { + self.entries + .next_back() + .map(|entry| self.headers.header(entry)) + } +} + +impl ExactSizeIterator for HeaderIter<'_> {} + +impl FusedIterator for HeaderIter<'_> {} + +impl<'m> IntoIterator for Headers<'m> { + type Item = Header<'m>; + type IntoIter = HeaderIter<'m>; + + fn into_iter(self) -> HeaderIter<'m> { + self.iter() + } +} + +impl<'m> IntoIterator for &Headers<'m> { + type Item = Header<'m>; + type IntoIter = HeaderIter<'m>; + + fn into_iter(self) -> HeaderIter<'m> { + self.iter() + } +} + +/// A list of text items: message identifiers (without angle brackets), +/// keywords, languages. Lists compare by content. +#[derive(Clone, Copy)] +pub struct TextList<'m> { + resolver: Resolver<'m>, + items: &'m [Str], +} + +impl<'m> Headers<'m> { + pub(crate) fn new( + resolver: Resolver<'m>, + data: &'m MessageData, + entries: &'m [HeaderEntry], + ) -> Self { + Headers { + resolver, + data, + entries, + } + } + + #[inline] + fn header(&self, entry: &'m HeaderEntry) -> Header<'m> { + Header { + resolver: self.resolver, + data: self.data, + entry, + } + } + + /// Number of header fields. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Whether the part has no header field. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Every header in document order. `for header in headers` does the + /// same. + pub fn iter(&self) -> HeaderIter<'m> { + HeaderIter { + headers: *self, + entries: self.entries.iter(), + } + } + + #[inline] + fn matches(&self, entry: &HeaderEntry, name: &str, id: u16) -> bool { + if id != OTHER_NAME { + entry.name == id + } else { + entry.name == OTHER_NAME + && raw_name(self.resolver, self.data, entry).eq_ignore_ascii_case(name) + } + } + + /// The last header with this name. A [`HeaderName::Other`] spelled + /// like a known name finds that name. + pub fn get<'n>(&self, name: impl Into<HeaderName<'n>>) -> Option<Header<'m>> { + let name = name.into(); + self.find_last(name.as_str(), name.resolved_id()) + } + + /// The last header with the name of this key; see [`HeaderName::key`]. + #[inline] + pub fn get_key(&self, key: HeaderKey<'_>) -> Option<Header<'m>> { + self.find_last(key.as_str(), key.id()) + } + + #[inline] + fn find_last(&self, name: &str, id: u16) -> Option<Header<'m>> { + match id { + OTHER_NAME => self + .entries + .iter() + .rev() + .find(|entry| self.matches(entry, name, OTHER_NAME)) + .map(|entry| self.header(entry)), + id => self.last_known(id), + } + } + + #[inline] + fn last_known(&self, id: u16) -> Option<Header<'m>> { + self.entries + .iter() + .rev() + .find(|entry| entry.name == id) + .map(|entry| self.header(entry)) + } + + #[inline] + fn known_value(&self, id: HeaderId) -> Option<HeaderValue<'m>> { + self.last_known(id as u16).map(|header| header.value()) + } + + /// Every header with this name, in document order. A + /// [`HeaderName::Other`] spelled like a known name finds that name. + #[inline] + pub fn all<'n>(&self, name: impl Into<HeaderName<'n>>) -> NamedHeaders<'m, 'n> { + let name = name.into(); + NamedHeaders { + headers: *self, + rest: self.entries, + id: name.resolved_id(), + name, + } + } + + /// Every header with the name of this key, in document order; see + /// [`HeaderName::key`]. + #[inline] + pub fn all_key<'k>(&self, key: HeaderKey<'k>) -> NamedHeaders<'m, 'k> { + NamedHeaders { + headers: *self, + rest: self.entries, + id: key.id(), + name: HeaderName::Other(Cow::Borrowed(key.as_str())), + } + } + + /// Whether a header with this name is present. + pub fn contains<'n>(&self, name: impl Into<HeaderName<'n>>) -> bool { + self.get(name).is_some() + } + + /// Whether at least one header has a known name: a cheap test that the + /// input looks like a message rather than arbitrary text. + pub fn has_known(&self) -> bool { + self.entries.iter().any(|entry| entry.name != OTHER_NAME) + } + + /// The value of the last header with this name. + pub fn value<'n>(&self, name: impl Into<HeaderName<'n>>) -> Option<HeaderValue<'m>> { + self.get(name).map(|header| header.value()) + } + + fn text(&self, id: HeaderId) -> Option<&'m str> { + self.known_value(id)?.as_text() + } + + fn address(&self, id: HeaderId) -> Option<AddressList<'m>> { + self.known_value(id)?.as_address() + } + + fn text_list(&self, id: HeaderId) -> Option<TextList<'m>> { + self.known_value(id)?.as_text_list() + } + + fn all_addresses( + &self, + name: HeaderName<'static>, + ) -> impl Iterator<Item = AddressList<'m>> + use<'m> { + self.all(name) + .filter_map(|header| header.value().as_address()) + } + + /// The Subject field, RFC 2047 encoded words decoded. + pub fn subject(&self) -> Option<&'m str> { + self.text(HeaderId::Subject) + } + + /// The Comments field, decoded. + pub fn comments(&self) -> Option<&'m str> { + self.text(HeaderId::Comments) + } + + /// The MIME-Version field, as written. + pub fn mime_version(&self) -> Option<&'m str> { + self.text(HeaderId::MimeVersion) + } + + /// The subject with reply and forward markers removed; see + /// [`crate::thread_name`]. + pub fn thread_name(&self) -> Option<&'m str> { + self.subject().map(thread_name) + } + + /// The From field. + pub fn from(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::From) + } + + /// The To field. + pub fn to(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::To) + } + + /// The Cc field. + pub fn cc(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::Cc) + } + + /// The Bcc field. + pub fn bcc(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::Bcc) + } + + /// The Reply-To field. + pub fn reply_to(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ReplyTo) + } + + /// The Sender field. + pub fn sender(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::Sender) + } + + /// Every To field, in document order. + pub fn all_to(&self) -> impl Iterator<Item = AddressList<'m>> + use<'m> { + self.all_addresses(HeaderName::To) + } + + /// Every Cc field, in document order. + pub fn all_cc(&self) -> impl Iterator<Item = AddressList<'m>> + use<'m> { + self.all_addresses(HeaderName::Cc) + } + + /// Every Bcc field, in document order. + pub fn all_bcc(&self) -> impl Iterator<Item = AddressList<'m>> + use<'m> { + self.all_addresses(HeaderName::Bcc) + } + + /// The Resent-To field. + pub fn resent_to(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ResentTo) + } + + /// The Resent-From field. + pub fn resent_from(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ResentFrom) + } + + /// The Resent-Cc field. + pub fn resent_cc(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ResentCc) + } + + /// The Resent-Bcc field. + pub fn resent_bcc(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ResentBcc) + } + + /// The Resent-Sender field. + pub fn resent_sender(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ResentSender) + } + + /// The List-Archive field (RFC 2369); the URLs are in + /// [`crate::Mailbox::address`]. + pub fn list_archive(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ListArchive) + } + + /// The List-Help field (RFC 2369); the URLs are in + /// [`crate::Mailbox::address`]. + pub fn list_help(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ListHelp) + } + + /// The List-ID field (RFC 2919): the description in + /// [`crate::Mailbox::name`], the identifier in [`crate::Mailbox::address`]. + pub fn list_id(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ListId) + } + + /// The List-Owner field (RFC 2369); the URLs are in + /// [`crate::Mailbox::address`]. + pub fn list_owner(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ListOwner) + } + + /// The List-Post field (RFC 2369); the URLs are in + /// [`crate::Mailbox::address`]. + pub fn list_post(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ListPost) + } + + /// The List-Subscribe field (RFC 2369); the URLs are in + /// [`crate::Mailbox::address`]. + pub fn list_subscribe(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ListSubscribe) + } + + /// The List-Unsubscribe field (RFC 2369); the URLs are in + /// [`crate::Mailbox::address`]. + pub fn list_unsubscribe(&self) -> Option<AddressList<'m>> { + self.address(HeaderId::ListUnsubscribe) + } + + /// The Date field. + pub fn date(&self) -> Option<DateTime> { + self.known_value(HeaderId::Date)?.as_datetime() + } + + /// The Resent-Date field. + pub fn resent_date(&self) -> Option<DateTime> { + self.known_value(HeaderId::ResentDate)?.as_datetime() + } + + /// The last identifier of the Message-ID field, without angle brackets. + pub fn message_id(&self) -> Option<&'m str> { + self.known_value(HeaderId::MessageId)?.as_text() + } + + /// The identifiers of the In-Reply-To field. + pub fn in_reply_to(&self) -> Option<TextList<'m>> { + self.text_list(HeaderId::InReplyTo) + } + + /// The identifiers of the References field. + pub fn references(&self) -> Option<TextList<'m>> { + self.text_list(HeaderId::References) + } + + /// The identifiers of the Resent-Message-ID field. + pub fn resent_message_id(&self) -> Option<TextList<'m>> { + self.text_list(HeaderId::ResentMessageId) + } + + /// The Return-Path field, parsed as message identifiers (the address + /// without angle brackets). + pub fn return_path(&self) -> Option<TextList<'m>> { + self.text_list(HeaderId::ReturnPath) + } + + /// The phrases of the Keywords field. + pub fn keywords(&self) -> Option<TextList<'m>> { + self.text_list(HeaderId::Keywords) + } + + /// The last address of Return-Path, or else the first address of From. + pub fn return_address(&self) -> Option<&'m str> { + match self.known_value(HeaderId::ReturnPath) { + Some(value @ (HeaderValue::Text(_) | HeaderValue::TextList(_))) => value.as_text(), + _ => self.from()?.first()?.address(), + } + } + + /// The last Received field (the oldest hop). + pub fn received(&self) -> Option<Received<'m>> { + self.known_value(HeaderId::Received)?.as_received() + } + + /// Every Received field, in document order. + pub fn all_received(&self) -> impl Iterator<Item = Received<'m>> + use<'m> { + self.all(HeaderName::Received) + .filter_map(|header| header.value().as_received()) + } +} + +fn raw_name<'m>(resolver: Resolver<'m>, data: &'m MessageData, entry: &HeaderEntry) -> &'m str { + if entry.other_name != NONE { + return data + .text_items + .get(entry.other_name as usize) + .map_or("", |text| resolver.str(*text)); + } + let start = entry.offset_field as usize; + let region = resolver + .source() + .get(start..(entry.offset_start as usize).saturating_sub(1)) + .unwrap_or_default(); + let canonical = header_name::canonical(entry.name); + if region == canonical.as_bytes() { + return canonical; + } + let name = header_name::trim_blank_end(region); + resolver + .borrow(start..start + name.len()) + .unwrap_or_default() +} + +impl<'m> Header<'m> { + /// The name: a known variant, or `Other` with the original spelling. + #[inline] + pub fn name(&self) -> HeaderName<'m> { + match header_name::known(self.entry.name) { + Some(known) => known.clone(), + None => HeaderName::Other(Cow::Borrowed(self.raw_name())), + } + } + + /// The name as written in the message, original case kept. + pub fn raw_name(&self) -> &'m str { + raw_name(self.resolver, self.data, self.entry) + } + + /// The value, parsed with the form the parser used for this name. + #[inline] + pub fn value(&self) -> HeaderValue<'m> { + HeaderValue::new(self.resolver, self.data, self.entry.value) + } + + /// The bytes after the colon up to the end of the field, final line + /// break included. + pub fn raw_value(&self) -> &'m [u8] { + self.resolver + .source() + .get(self.entry.offset_start as usize..self.entry.offset_end as usize) + .unwrap_or_default() + } + + /// Parses the raw value again with another form, for names the parser + /// kept raw or parsed differently. + /// + /// ``` + /// use mail_parser::{HeaderForm, MessageParser}; + /// + /// let raw = b"X-Sender: Jane <jane@example.com>\r\n\r\nbody"; + /// let message = MessageParser::new().parse(raw).expect("message"); + /// let header = message.headers().get("x-sender").expect("header"); + /// let parsed = header.parse_as(HeaderForm::Addresses); + /// let sender = parsed.value().as_address().and_then(|list| list.first()); + /// assert_eq!(sender.and_then(|mailbox| mailbox.address()), Some("jane@example.com")); + /// ``` + pub fn parse_as(&self, form: HeaderForm) -> ParsedValue<'m> { + ParsedValue::new( + form, + self.resolver.source(), + self.entry.offset_start as usize..self.entry.offset_end as usize, + ) + } + + /// Offset of the first byte of the name in the message's source buffer. + pub fn offset_field(&self) -> u32 { + self.entry.offset_field + } + + /// Offset of the byte after the colon. + pub fn offset_start(&self) -> u32 { + self.entry.offset_start + } + + /// Offset of the byte after the final line break of the field. For the + /// last field of a header block cut short by a MIME delimiter, this is + /// one line break past the part's body offset. + pub fn offset_end(&self) -> u32 { + self.entry.offset_end + } +} + +impl<'m> HeaderValue<'m> { + #[inline] + pub(crate) fn new(resolver: Resolver<'m>, data: &'m MessageData, value: Value) -> Self { + match value { + Value::Empty => HeaderValue::Empty, + Value::Text(text) => HeaderValue::Text(resolver.str(text)), + Value::TextList(span) => HeaderValue::TextList(TextList { + resolver, + items: data.text_items.get(span.range()).unwrap_or_default(), + }), + Value::Address(span) => HeaderValue::Address(AddressList::new( + resolver, + data.address_items.get(span.range()).unwrap_or_default(), + )), + Value::DateTime(date) => HeaderValue::DateTime(date), + Value::ContentType(index) => data + .content_types + .get(index as usize) + .map_or(HeaderValue::Empty, |entry| { + HeaderValue::ContentType(ContentType::new(resolver, data, entry)) + }), + Value::Received(index) => data + .received + .get(index as usize) + .map_or(HeaderValue::Empty, |entry| { + HeaderValue::Received(Received::new(resolver, entry)) + }), + } + } + + /// Whether the value is [`HeaderValue::Empty`]. + pub fn is_empty(&self) -> bool { + matches!(self, HeaderValue::Empty) + } + + /// The text, or the last item of a text list (the identifier of a + /// Message-ID field, for instance). + pub fn as_text(&self) -> Option<&'m str> { + match self { + HeaderValue::Text(text) => Some(text), + HeaderValue::TextList(list) => list.last(), + _ => None, + } + } + + /// The text list. + pub fn as_text_list(&self) -> Option<TextList<'m>> { + match self { + HeaderValue::TextList(list) => Some(*list), + _ => None, + } + } + + /// The address list. + pub fn as_address(&self) -> Option<AddressList<'m>> { + match self { + HeaderValue::Address(list) => Some(*list), + _ => None, + } + } + + /// The date. + pub fn as_datetime(&self) -> Option<DateTime> { + match self { + HeaderValue::DateTime(date) => Some(*date), + _ => None, + } + } + + /// The Content-Type or Content-Disposition value. + pub fn as_content_type(&self) -> Option<ContentType<'m>> { + match self { + HeaderValue::ContentType(content_type) => Some(*content_type), + _ => None, + } + } + + /// The Received trace field. + pub fn as_received(&self) -> Option<Received<'m>> { + match self { + HeaderValue::Received(received) => Some(*received), + _ => None, + } + } +} + +impl<'m> TextList<'m> { + /// Number of items. + pub fn len(&self) -> usize { + self.items.len() + } + + /// Whether the list has no item. + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + /// The item at `index`. + pub fn get(&self, index: usize) -> Option<&'m str> { + self.items.get(index).map(|item| self.resolver.str(*item)) + } + + /// The first item. + pub fn first(&self) -> Option<&'m str> { + self.items.first().map(|item| self.resolver.str(*item)) + } + + /// The last item. + pub fn last(&self) -> Option<&'m str> { + self.items.last().map(|item| self.resolver.str(*item)) + } + + /// Every item in order. + pub fn iter(&self) -> impl ExactSizeIterator<Item = &'m str> + DoubleEndedIterator + use<'m> { + let resolver = self.resolver; + self.items.iter().map(move |item| resolver.str(*item)) + } + + /// Whether an item equals `text` exactly. + pub fn contains(&self, text: &str) -> bool { + self.iter().any(|item| item == text) + } +} + +impl fmt::Debug for Headers<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl fmt::Debug for Header<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Header") + .field("name", &self.raw_name()) + .field("value", &self.value()) + .field("offset_field", &self.offset_field()) + .field("offset_start", &self.offset_start()) + .field("offset_end", &self.offset_end()) + .finish() + } +} + +impl fmt::Debug for HeaderIter<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("HeaderIter") + .field("remaining", &self.entries.len()) + .finish_non_exhaustive() + } +} + +impl fmt::Debug for NamedHeaders<'_, '_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NamedHeaders") + .field("name", &self.name) + .finish_non_exhaustive() + } +} + +impl fmt::Debug for TextList<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl PartialEq for TextList<'_> { + fn eq(&self, other: &Self) -> bool { + self.items.len() == other.items.len() && self.iter().eq(other.iter()) + } +} + +impl Eq for TextList<'_> {} diff --git a/src/view/message.rs b/src/view/message.rs new file mode 100644 index 0000000..78e67ac --- /dev/null +++ b/src/view/message.rs @@ -0,0 +1,753 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{ + AddressList, ContentType, Ctx, Headers, MessagePart, PartKind, PartRole, Received, TextList, +}; +use crate::{ + DateTime, MessageBuffers, + decoders::{self, Limit, preview::preview_html_prefix}, + html_to_text, preview_html, preview_text, + store::{MessageData, MessageEntry, MessageId, NONE, PartId, Span}, + text_to_html, +}; +use memchr::{memchr, memchr_iter}; +use std::{borrow::Cow, fmt}; + +const PREVIEW_SLACK: usize = 16; +const PREVIEW_CR_ALLOWANCE: usize = 16; +const PREVIEW_GROWTH: usize = 4; +const PREVIEW_HTML_RATIO: usize = 8; +const PREVIEW_HTML_MIN: usize = 4096; + +/// A parsed message: the raw bytes and a store of every nested message, MIME +/// part and header field, read through small `Copy` views such as +/// [`MessageRef`], [`MessagePart`] and [`crate::Header`]. Bodies are decoded +/// on access. +/// +/// A message is read-only, `Send + Sync`, and covariant in `'x`, the +/// lifetime of the raw bytes; [`crate::MessageParser::parse_owned`] and +/// [`Message::into_owned`] give a `Message<'static>`. Every accessor of the +/// root [`MessageRef`] is also available here: `message.subject()` is +/// `message.root().subject()`. +/// +/// ``` +/// use mail_parser::{MessageParser, PartKind}; +/// +/// let raw = concat!( +/// "From: Ann <ann@example.com>\r\n", +/// "Subject: Report\r\n", +/// "Content-Type: multipart/mixed; boundary=\"b\"\r\n", +/// "\r\n", +/// "--b\r\n", +/// "Content-Type: text/plain; charset=utf-8\r\n", +/// "\r\n", +/// "See the attachment.\r\n", +/// "--b\r\n", +/// "Content-Type: application/pdf; name=report.pdf\r\n", +/// "Content-Transfer-Encoding: base64\r\n", +/// "\r\n", +/// "JVBERi0xLjQK\r\n", +/// "--b--\r\n", +/// ); +/// let message = MessageParser::new().parse(raw).expect("message"); +/// assert_eq!(message.subject(), Some("Report")); +/// let sender = message.from().and_then(|from| from.first()); +/// assert_eq!(sender.and_then(|mailbox| mailbox.name()), Some("Ann")); +/// assert_eq!(message.body_text(0).as_deref(), Some("See the attachment.")); +/// let attachment = message.attachments().next().expect("attachment"); +/// assert_eq!(attachment.attachment_name(), Some("report.pdf")); +/// assert!(matches!(attachment.kind(), PartKind::Binary)); +/// assert_eq!(attachment.decoded().as_ref(), b"%PDF-1.4\n"); +/// ``` +#[derive(Clone)] +pub struct Message<'x> { + raw: Cow<'x, [u8]>, + data: MessageData, +} + +/// A message inside a [`Message`]: the root message, or a message nested in +/// a `message/rfc822` (or `message/global`) part. Each message has its own +/// root part, header fields and body lists. +#[derive(Clone, Copy)] +pub struct MessageRef<'m> { + ctx: Ctx<'m>, + id: MessageId, + entry: &'m MessageEntry, +} + +/// The buffer the offsets of a message's parts and headers refer to. +/// +/// A nested message that was not transfer-encoded is parsed in place, so its +/// offsets refer to the buffer of the message that contains it: the raw +/// input, or the decoded body of an encoded ancestor. A base64 or +/// quoted-printable encoded one is decoded during the parse and its offsets +/// refer to that decoded body, available from [`MessageRef::source_bytes`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Source { + /// The raw input, [`Message::raw`]. + Raw, + /// The transfer-decoded body of this `message/rfc822` part: the part + /// holding the message when the message was transfer-encoded, else the + /// closest transfer-encoded `message/rfc822` part it is nested in. + Decoded(PartId), +} + +macro_rules! header_getters { + ($lt:lifetime, $target:ident, $($captures:tt)*) => { + /// The Subject field, RFC 2047 encoded words decoded. + pub fn subject(&self) -> Option<&$lt str> { + self.$target().subject() + } + + /// The Comments field, decoded. + pub fn comments(&self) -> Option<&$lt str> { + self.$target().comments() + } + + /// The MIME-Version field, as written. + pub fn mime_version(&self) -> Option<&$lt str> { + self.$target().mime_version() + } + + /// The subject with reply and forward markers removed; see + /// [`crate::thread_name`]. + pub fn thread_name(&self) -> Option<&$lt str> { + self.$target().thread_name() + } + + /// The From field. + pub fn from(&self) -> Option<AddressList<$lt>> { + self.$target().from() + } + + /// The To field. + pub fn to(&self) -> Option<AddressList<$lt>> { + self.$target().to() + } + + /// The Cc field. + pub fn cc(&self) -> Option<AddressList<$lt>> { + self.$target().cc() + } + + /// The Bcc field. + pub fn bcc(&self) -> Option<AddressList<$lt>> { + self.$target().bcc() + } + + /// The Reply-To field. + pub fn reply_to(&self) -> Option<AddressList<$lt>> { + self.$target().reply_to() + } + + /// The Sender field. + pub fn sender(&self) -> Option<AddressList<$lt>> { + self.$target().sender() + } + + /// Every To field, in document order. + pub fn all_to(&self) -> impl Iterator<Item = AddressList<$lt>> $($captures)* { + self.$target().all_to() + } + + /// Every Cc field, in document order. + pub fn all_cc(&self) -> impl Iterator<Item = AddressList<$lt>> $($captures)* { + self.$target().all_cc() + } + + /// Every Bcc field, in document order. + pub fn all_bcc(&self) -> impl Iterator<Item = AddressList<$lt>> $($captures)* { + self.$target().all_bcc() + } + + /// The Resent-To field. + pub fn resent_to(&self) -> Option<AddressList<$lt>> { + self.$target().resent_to() + } + + /// The Resent-From field. + pub fn resent_from(&self) -> Option<AddressList<$lt>> { + self.$target().resent_from() + } + + /// The Resent-Cc field. + pub fn resent_cc(&self) -> Option<AddressList<$lt>> { + self.$target().resent_cc() + } + + /// The Resent-Bcc field. + pub fn resent_bcc(&self) -> Option<AddressList<$lt>> { + self.$target().resent_bcc() + } + + /// The Resent-Sender field. + pub fn resent_sender(&self) -> Option<AddressList<$lt>> { + self.$target().resent_sender() + } + + /// The List-Archive field; see [`Headers::list_archive`]. + pub fn list_archive(&self) -> Option<AddressList<$lt>> { + self.$target().list_archive() + } + + /// The List-Help field; see [`Headers::list_help`]. + pub fn list_help(&self) -> Option<AddressList<$lt>> { + self.$target().list_help() + } + + /// The List-ID field; see [`Headers::list_id`]. + pub fn list_id(&self) -> Option<AddressList<$lt>> { + self.$target().list_id() + } + + /// The List-Owner field; see [`Headers::list_owner`]. + pub fn list_owner(&self) -> Option<AddressList<$lt>> { + self.$target().list_owner() + } + + /// The List-Post field; see [`Headers::list_post`]. + pub fn list_post(&self) -> Option<AddressList<$lt>> { + self.$target().list_post() + } + + /// The List-Subscribe field; see [`Headers::list_subscribe`]. + pub fn list_subscribe(&self) -> Option<AddressList<$lt>> { + self.$target().list_subscribe() + } + + /// The List-Unsubscribe field; see [`Headers::list_unsubscribe`]. + pub fn list_unsubscribe(&self) -> Option<AddressList<$lt>> { + self.$target().list_unsubscribe() + } + + /// The Date field. + pub fn date(&self) -> Option<DateTime> { + self.$target().date() + } + + /// The Resent-Date field. + pub fn resent_date(&self) -> Option<DateTime> { + self.$target().resent_date() + } + + /// The last identifier of the Message-ID field, without angle + /// brackets. + pub fn message_id(&self) -> Option<&$lt str> { + self.$target().message_id() + } + + /// The identifiers of the In-Reply-To field. + pub fn in_reply_to(&self) -> Option<TextList<$lt>> { + self.$target().in_reply_to() + } + + /// The identifiers of the References field. + pub fn references(&self) -> Option<TextList<$lt>> { + self.$target().references() + } + + /// The identifiers of the Resent-Message-ID field. + pub fn resent_message_id(&self) -> Option<TextList<$lt>> { + self.$target().resent_message_id() + } + + /// The Return-Path field; see [`Headers::return_path`]. + pub fn return_path(&self) -> Option<TextList<$lt>> { + self.$target().return_path() + } + + /// The phrases of the Keywords field. + pub fn keywords(&self) -> Option<TextList<$lt>> { + self.$target().keywords() + } + + /// The last address of Return-Path, or else the first address of + /// From. + pub fn return_address(&self) -> Option<&$lt str> { + self.$target().return_address() + } + + /// The last Received field (the oldest hop). + pub fn received(&self) -> Option<Received<$lt>> { + self.$target().received() + } + + /// Every Received field, in document order (newest hop first). + pub fn all_received(&self) -> impl Iterator<Item = Received<$lt>> $($captures)* { + self.$target().all_received() + } + }; +} + +macro_rules! message_getters { + ($lt:lifetime) => { + /// The root part of the root message; see [`MessageRef::root_part`]. + pub fn root_part(&self) -> MessagePart<$lt> { + self.root().root_part() + } + + /// The header fields of the root message. + pub fn headers(&self) -> Headers<$lt> { + self.root().headers() + } + + /// The text body of the root message; see [`MessageRef::text_body`]. + pub fn text_body(&self) -> impl ExactSizeIterator<Item = MessagePart<$lt>> { + self.root().text_body() + } + + /// The HTML body of the root message; see [`MessageRef::html_body`]. + pub fn html_body(&self) -> impl ExactSizeIterator<Item = MessagePart<$lt>> { + self.root().html_body() + } + + /// The attachments of the root message; see + /// [`MessageRef::attachments`]. + pub fn attachments(&self) -> impl ExactSizeIterator<Item = MessagePart<$lt>> { + self.root().attachments() + } + + /// The parts of the root message in no list; see + /// [`MessageRef::other_parts`]. + pub fn other_parts(&self) -> impl Iterator<Item = MessagePart<$lt>> { + self.root().other_parts() + } + + /// Whether the root message has attachments; see + /// [`MessageRef::has_attachments`]. + pub fn has_attachments(&self) -> bool { + self.root().has_attachments() + } + + /// The text body of the root message as text; see + /// [`MessageRef::text_bodies`]. + pub fn text_bodies(&self) -> impl Iterator<Item = Cow<$lt, str>> { + self.root().text_bodies() + } + + /// The HTML body of the root message as HTML; see + /// [`MessageRef::html_bodies`]. + pub fn html_bodies(&self) -> impl Iterator<Item = Cow<$lt, str>> { + self.root().html_bodies() + } + + /// The text of the `index`-th part of the root text body; see + /// [`MessageRef::body_text`]. + pub fn body_text(&self, index: usize) -> Option<Cow<$lt, str>> { + self.root().body_text(index) + } + + /// The HTML of the `index`-th part of the root HTML body; see + /// [`MessageRef::body_html`]. + pub fn body_html(&self, index: usize) -> Option<Cow<$lt, str>> { + self.root().body_html(index) + } + + /// A preview of the root message's body; see + /// [`MessageRef::body_preview`]. + pub fn body_preview(&self, max_len: usize) -> Option<Cow<$lt, str>> { + self.root().body_preview(max_len) + } + + /// The Content-Type of the root part. + pub fn content_type(&self) -> Option<ContentType<$lt>> { + self.root().root_part().content_type() + } + + /// The Content-Disposition of the root part. + pub fn content_disposition(&self) -> Option<ContentType<$lt>> { + self.root().root_part().content_disposition() + } + + /// The attachment name of the root part; see + /// [`MessagePart::attachment_name`]. + pub fn attachment_name(&self) -> Option<&$lt str> { + self.root().root_part().attachment_name() + } + + /// Whether the Content-Type of the root part is `type_/subtype` + /// (ASCII case-insensitive). + pub fn is_content_type(&self, type_: &str, subtype: &str) -> bool { + self.root().root_part().is_content_type(type_, subtype) + } + + header_getters!($lt, headers,); + }; +} + +impl Default for Message<'_> { + /// An empty message: no bytes, and a root part with no header and an + /// empty body, in no body list. + fn default() -> Self { + Message { + raw: Cow::Borrowed(&[]), + data: MessageData::empty_message(), + } + } +} + +impl<'x> Message<'x> { + pub(crate) fn new(raw: Cow<'x, [u8]>, data: MessageData) -> Self { + Message { raw, data } + } + + pub(crate) fn split_mut(&mut self) -> (&[u8], &mut MessageData) { + (&self.raw, &mut self.data) + } + + fn ctx(&self) -> Ctx<'_> { + Ctx::new(&self.raw, &self.data) + } + + /// The raw input. + pub fn raw(&self) -> &[u8] { + &self.raw + } + + /// The top-level message, id 0. + pub fn root(&self) -> MessageRef<'_> { + self.ctx().message(0) + } + + /// Every message, the root first, then nested messages in document + /// order. + pub fn messages(&self) -> impl ExactSizeIterator<Item = MessageRef<'_>> + DoubleEndedIterator { + let ctx = self.ctx(); + (0..self.data.messages.len() as MessageId).map(move |id| ctx.message(id)) + } + + /// Every part of every message, in document order. + pub fn parts(&self) -> impl ExactSizeIterator<Item = MessagePart<'_>> + DoubleEndedIterator { + let ctx = self.ctx(); + (0..self.data.parts.len() as PartId).map(move |id| ctx.part_or_empty(id)) + } + + /// The part with this id; ids number every part of every message in + /// document order. + pub fn part(&self, id: PartId) -> Option<MessagePart<'_>> { + self.ctx().part(id) + } + + /// The multipart part whose `boundary` parameter is `boundary` (issue + /// #127); a linear scan over the parts. + pub fn part_by_boundary(&self, boundary: &str) -> Option<MessagePart<'_>> { + self.parts().find(|part| part.boundary() == Some(boundary)) + } + + /// Copies borrowed input so the message owns its bytes. Only the raw + /// bytes are copied; the parsed store is moved. + pub fn into_owned(self) -> Message<'static> { + Message { + raw: Cow::Owned(self.raw.into_owned()), + data: self.data, + } + } + + /// Drops the message and keeps its storage, cleared, for the next + /// [`crate::MessageParser::parse_with`]; see [`MessageBuffers`]. + pub fn into_buffers(self) -> MessageBuffers { + let mut data = self.data; + data.clear(); + MessageBuffers { data } + } + + message_getters!('_); +} + +impl<'m> MessageRef<'m> { + pub(crate) fn new(ctx: Ctx<'m>, id: MessageId, entry: &'m MessageEntry) -> Self { + MessageRef { ctx, id, entry } + } + + fn list( + &self, + skip: u32, + len: u32, + ) -> impl ExactSizeIterator<Item = MessagePart<'m>> + use<'m> { + let ctx = self.ctx; + ctx.ids(Span { + start: self.entry.lists + skip, + len, + }) + .iter() + .map(move |id| ctx.part_or_empty(*id)) + } + + /// The id of this message: 0 for the root, then nested messages in + /// document order. + pub fn id(&self) -> MessageId { + self.id + } + + /// The root part: the header block of this message and its body. + pub fn root_part(&self) -> MessagePart<'m> { + self.ctx.part_or_empty(self.entry.root) + } + + /// The `message/rfc822` part holding this message; `None` for the root + /// message. + pub fn container(&self) -> Option<MessagePart<'m>> { + (self.entry.container != NONE) + .then(|| self.ctx.part(self.entry.container)) + .flatten() + } + + /// The buffer this message's offsets refer to. + pub fn source(&self) -> Source { + self.ctx + .data() + .source_container(self.entry.source) + .map_or(Source::Raw, Source::Decoded) + } + + /// The bytes of the buffer this message's offsets refer to. + pub fn source_bytes(&self) -> &'m [u8] { + self.ctx.source_of(self.id) + } + + /// The bytes of this message, from its first header to its end. + pub fn raw(&self) -> &'m [u8] { + self.root_part().raw() + } + + /// The header fields of this message: those of its root part. + pub fn headers(&self) -> Headers<'m> { + self.root_part().headers() + } + + /// The parts of this message (nested messages excluded), in document + /// order. + pub fn parts(&self) -> impl Iterator<Item = MessagePart<'m>> + use<'m> { + let ctx = self.ctx; + let id = self.id; + let end = if self.entry.parts_end == NONE { + ctx.data().parts.len() as PartId + } else { + self.entry.parts_end + }; + let start = if self.entry.root == NONE { + end + } else { + self.entry.root + }; + (start..end) + .filter_map(move |part| ctx.part(part)) + .filter(move |part| part.message_id() == id) + } + + /// The parts that make up the text body (RFC 8621 `textBody`): text + /// parts, HTML parts standing in for a missing text version, and inline + /// media, in reading order. [`MessageRef::text_bodies`] gives them as + /// text. + pub fn text_body(&self) -> impl ExactSizeIterator<Item = MessagePart<'m>> + use<'m> { + self.list(0, self.entry.text_len) + } + + /// The parts that make up the HTML body (RFC 8621 `htmlBody`): HTML + /// parts, text parts standing in for a missing HTML version, and inline + /// media, in reading order. [`MessageRef::html_bodies`] gives them as + /// HTML. + pub fn html_body(&self) -> impl ExactSizeIterator<Item = MessagePart<'m>> + use<'m> { + self.list(self.entry.text_len, self.entry.html_len) + } + + /// The attachments (RFC 8621 `attachments`): the leaf parts, nested + /// messages included, that are not shown as part of the body, plus inline + /// media shown in only one of the two bodies. + pub fn attachments(&self) -> impl ExactSizeIterator<Item = MessagePart<'m>> + use<'m> { + self.list( + self.entry.text_len + self.entry.html_len, + self.entry.attachments_len, + ) + } + + /// Whether a client should offer this message as having attachments: + /// RFC 8621 `hasAttachment`, true when [`MessageRef::attachments`] holds + /// a part without `Content-Disposition: inline`. Images referenced by + /// `cid:` count unless they are marked inline; the RFC's optional + /// exception for embedded images is not applied. + pub fn has_attachments(&self) -> bool { + self.attachments().any(|part| { + !part + .content_disposition() + .is_some_and(|disposition| disposition.is_inline()) + }) + } + + /// The parts of this message that are in no list (issue #107): + /// containers excluded, nested messages excluded. For a message from + /// [`crate::MessageParser::parse_headers`] this is the root part. + pub fn other_parts(&self) -> impl Iterator<Item = MessagePart<'m>> + use<'m> { + self.parts().filter(|part| part.role() == PartRole::Dropped) + } + + fn as_text(part: MessagePart<'m>) -> Option<Cow<'m, 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<'m>) -> Option<Cow<'m, str>> { + match part.kind() { + PartKind::Html => part.text(), + PartKind::Text => part.text().map(|text| Cow::Owned(text_to_html(&text))), + _ => None, + } + } + + /// The text body as text: HTML parts converted, non-text parts skipped. + pub fn text_bodies(&self) -> impl Iterator<Item = Cow<'m, str>> + use<'m> { + self.text_body().filter_map(Self::as_text) + } + + /// The HTML body as HTML: text parts converted, non-text parts skipped. + pub fn html_bodies(&self) -> impl Iterator<Item = Cow<'m, str>> + use<'m> { + self.html_body().filter_map(Self::as_html) + } + + /// The text of the `index`-th part of the text body. + pub fn body_text(&self, index: usize) -> Option<Cow<'m, str>> { + self.text_body().nth(index).and_then(Self::as_text) + } + + /// The HTML of the `index`-th part of the HTML body. + pub fn body_html(&self, index: usize) -> Option<Cow<'m, str>> { + self.html_body().nth(index).and_then(Self::as_html) + } + + /// A preview of at most `max_len` bytes of the first text body, else of + /// the first HTML body, without carriage returns; see [`preview_text`]. + pub fn body_preview(&self, max_len: usize) -> Option<Cow<'m, str>> { + if self.entry.text_len > 0 { + let part = self.text_body().next()?; + match part.kind() { + PartKind::Text => Self::preview_text_part(part, max_len), + PartKind::Html => Self::preview_html_part(part, max_len), + _ => None, + } + } else if self.entry.html_len > 0 { + let part = self.html_body().next()?; + match part.kind() { + PartKind::Html => Self::preview_html_part(part, max_len), + PartKind::Text => Some(Cow::Owned(preview_html( + &text_to_html(&part.text()?), + max_len, + ))), + _ => None, + } + } else { + None + } + } + + fn preview_text_part(part: MessagePart<'m>, max_len: usize) -> Option<Cow<'m, str>> { + let mut bytes = max_len + .saturating_add(max_len / PREVIEW_CR_ALLOWANCE) + .saturating_add(PREVIEW_SLACK); + loop { + let prefix = part.text_prefix_state(Limit::Bytes(bytes))?; + if prefix.complete || exceeds_without_cr(prefix.text.as_bytes(), max_len) { + return Some(decoders::rewrite(prefix.text, |text| { + preview_text(text, max_len) + })); + } + bytes = bytes.saturating_mul(PREVIEW_GROWTH); + } + } + + fn preview_html_part(part: MessagePart<'m>, max_len: usize) -> Option<Cow<'m, str>> { + let mut bytes = max_len + .saturating_mul(PREVIEW_HTML_RATIO) + .max(PREVIEW_HTML_MIN); + loop { + let prefix = part.text_prefix_state(Limit::Bytes(bytes))?; + if let Some(preview) = preview_html_prefix(&prefix.text, max_len, prefix.complete) { + return Some(Cow::Owned(preview)); + } + bytes = bytes.saturating_mul(PREVIEW_GROWTH); + } + } + + /// The Content-Type of the root part. + pub fn content_type(&self) -> Option<ContentType<'m>> { + self.root_part().content_type() + } + + /// The Content-Disposition of the root part. + pub fn content_disposition(&self) -> Option<ContentType<'m>> { + self.root_part().content_disposition() + } + + /// The attachment name of the root part; see + /// [`MessagePart::attachment_name`]. + pub fn attachment_name(&self) -> Option<&'m str> { + self.root_part().attachment_name() + } + + /// Whether the Content-Type of the root part is `type_/subtype` (ASCII + /// case-insensitive). + pub fn is_content_type(&self, type_: &str, subtype: &str) -> bool { + self.root_part().is_content_type(type_, subtype) + } + + header_getters!('m, headers, + use<'m>); +} + +fn exceeds_without_cr(text: &[u8], max_len: usize) -> bool { + let needed = max_len.saturating_add(1); + match text.get(..needed) { + Some(window) if memchr(b'\r', window).is_none() => true, + _ => text.len() - memchr_iter(b'\r', text).count() >= needed, + } +} + +impl fmt::Debug for Message<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Message") + .field("len", &self.raw.len()) + .field("messages", &self.data.messages.len()) + .field("parts", &self.data.parts.len()) + .field("headers", &self.data.headers.len()) + .finish() + } +} + +impl fmt::Debug for MessageRef<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MessageRef") + .field("id", &self.id) + .field("root", &self.entry.root) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::exceeds_without_cr; + use crate::scan::tests::Rng; + use memchr::memchr_iter; + + #[test] + fn carriage_returns_do_not_count() { + let mut rng = Rng(0x5eed_cafe_f00d_0001); + for _ in 0..20_000 { + let len = rng.below(40); + let text: Vec<u8> = (0..len) + .map(|_| if rng.below(3) == 0 { b'\r' } else { b'a' }) + .collect(); + let max_len = rng.below(40); + let expected = text.len() - memchr_iter(b'\r', &text).count() > max_len; + assert_eq!( + exceeds_without_cr(&text, max_len), + expected, + "{text:?} {max_len}" + ); + } + } +} diff --git a/src/view/mod.rs b/src/view/mod.rs new file mode 100644 index 0000000..1830374 --- /dev/null +++ b/src/view/mod.rs @@ -0,0 +1,108 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod address; +mod content_type; +mod headers; +mod message; +mod part; +mod received; +#[cfg(feature = "serde")] +mod serialize; + +pub use address::{Address, AddressList, AddressRun, Group, Mailbox}; +pub use content_type::ContentType; +pub use headers::{Header, HeaderIter, HeaderValue, Headers, NamedHeaders, TextList}; +pub use message::{Message, MessageRef, Source}; +pub use part::{DecodeProblems, MessagePart, PartFlags, PartKind, PartRole}; +pub use received::{Greeting, Host, Protocol, Received, TlsVersion}; + +use crate::store::{Blank, MessageData, MessageEntry, MessageId, PartEntry, PartId, Span, Str}; +use std::ops::Range; + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Resolver<'m> { + source: &'m [u8], + pool: &'m str, +} + +impl<'m> Resolver<'m> { + pub(crate) fn new(source: &'m [u8], pool: &'m str) -> Self { + Resolver { source, pool } + } + + pub(crate) fn source(self) -> &'m [u8] { + self.source + } + + pub(crate) fn str(self, text: Str) -> &'m str { + text.resolve(self.source, self.pool) + } + + pub(crate) fn opt(self, text: Str) -> Option<&'m str> { + text.resolve_option(self.source, self.pool) + } + + pub(crate) fn borrow(self, range: Range<usize>) -> Option<&'m str> { + Str::borrow(self.source, range).map(|text| self.str(text)) + } +} + +#[derive(Debug, Clone, Copy)] +pub(crate) struct Ctx<'m> { + raw: &'m [u8], + data: &'m MessageData, +} + +static EMPTY_MESSAGE: MessageEntry = MessageEntry::BLANK; +static EMPTY_PART: PartEntry = PartEntry::EMPTY; + +impl<'m> Ctx<'m> { + pub(crate) fn new(raw: &'m [u8], data: &'m MessageData) -> Self { + Ctx { raw, data } + } + + pub(crate) fn data(self) -> &'m MessageData { + self.data + } + + pub(crate) fn message_entry(self, id: MessageId) -> &'m MessageEntry { + self.data + .messages + .get(id as usize) + .unwrap_or(&EMPTY_MESSAGE) + } + + pub(crate) fn part_entry(self, id: PartId) -> Option<&'m PartEntry> { + self.data.parts.get(id as usize) + } + + pub(crate) fn source_of(self, message: MessageId) -> &'m [u8] { + self.data.message_source(self.raw, message) + } + + #[inline] + pub(crate) fn resolver(self, message: MessageId) -> Resolver<'m> { + Resolver::new(self.source_of(message), &self.data.strings) + } + + pub(crate) fn message(self, id: MessageId) -> MessageRef<'m> { + MessageRef::new(self, id, self.message_entry(id)) + } + + pub(crate) fn part(self, id: PartId) -> Option<MessagePart<'m>> { + self.part_entry(id) + .map(|entry| MessagePart::new(self, id, entry)) + } + + pub(crate) fn part_or_empty(self, id: PartId) -> MessagePart<'m> { + MessagePart::new(self, id, self.part_entry(id).unwrap_or(&EMPTY_PART)) + } + + pub(crate) fn ids(self, span: Span) -> &'m [PartId] { + self.data.ids.get(span.range()).unwrap_or_default() + } +} diff --git a/src/view/part.rs b/src/view/part.rs new file mode 100644 index 0000000..6f1b9ae --- /dev/null +++ b/src/view/part.rs @@ -0,0 +1,655 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{ContentType, Ctx, Headers, MessageRef, Resolver, TextList}; +use crate::{ + Charset, Encoding, HeaderName, + decoders::{self, html::strip_charset_meta}, + store::{KindTag, MessageId, NONE, PartEntry, PartId, flag, role}, +}; +use std::{borrow::Cow, fmt}; + +/// A MIME part: a header block and a body. Parts are numbered in document +/// order across nested messages ([`MessagePart::id`]), and every message has +/// a root part holding its own header fields. +/// +/// Bodies are decoded on access: [`MessagePart::decoded`] for the transfer +/// encoding, [`MessagePart::text`] for text parts (transfer encoding and +/// charset), [`MessagePart::text_prefix`] and [`MessagePart::decoded_len`] +/// to avoid decoding the whole body. +#[derive(Clone, Copy)] +pub struct MessagePart<'m> { + ctx: Ctx<'m>, + id: PartId, + entry: &'m PartEntry, +} + +/// What a part contains. +#[derive(Debug, Clone, Copy)] +pub enum PartKind<'m> { + /// A text part (any `text/*` except HTML, or a part without type). Also + /// a `message/rfc822` part that is not transfer-encoded and whose nested + /// message was empty or had no header block (flagged + /// [`PartFlags::NO_BLANK_LINE`]), or was cut by the part limit + /// ([`PartFlags::LIMIT_REACHED`]). + Text, + /// A `text/html` part. + Html, + /// A non-text part. Also a `message/rfc822` part that was not parsed: + /// beyond the depth limit, or transfer-encoded and beyond the encoded + /// nesting limit, with encoded nested parsing turned off, or holding a + /// message that was empty or cut by the part limit. + Binary, + /// A non-text part marked to be rendered inline; see + /// [`MessagePart::is_inline`]. + InlineBinary, + /// A multipart container; see [`MessagePart::children`]. + Multipart, + /// A nested `message/rfc822` or `message/global`. + Message(MessageRef<'m>), +} + +/// How the body classification used a part (issue #107). Every part has +/// exactly one role; the roles of a message's parts partition them. +/// +/// The role is a summary of the list memberships +/// ([`MessagePart::in_text_body`], [`MessagePart::in_html_body`], +/// [`MessagePart::is_attachment`]). [`PartRole::CopiedBody`] takes priority +/// over [`PartRole::TextBody`] and [`PartRole::HtmlBody`]: a text or HTML +/// part copied into the other list is in both lists. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PartRole { + /// A multipart; its children have their own roles. + Container, + /// A text part of the body lists. + TextBody, + /// An HTML part of the body lists. + HtmlBody, + /// A body part of a `multipart/alternative` that had no version of the + /// other type, copied into the other body list as its stand-in; it is in + /// both body lists. + CopiedBody, + /// An image, audio or video part displayed in the body lists (it may + /// also be an attachment; see [`MessageRef::attachments`]). + MediaBody, + /// A part offered as an attachment and in no body list. + Attachment, + /// A part in no list. + Dropped, +} + +macro_rules! flag_set { + ($set:ident) => { + impl $set { + /// The flags as a bit mask. + pub fn bits(&self) -> u8 { + self.0 + } + + /// Whether no flag is set. + pub fn is_empty(&self) -> bool { + self.0 == 0 + } + + /// Whether every flag of `other` is set. + pub fn contains(&self, other: $set) -> bool { + self.0 & other.0 == other.0 + } + + /// Whether at least one flag of `other` is set. + pub fn intersects(&self, other: $set) -> bool { + self.0 & other.0 != 0 + } + + /// Names of the flags that are set, in bit order. + pub fn names(&self) -> impl Iterator<Item = &'static str> + use<> { + let flags = *self; + <$set>::NAMES + .into_iter() + .filter(move |(value, _)| flags.contains(*value)) + .map(|(_, name)| name) + } + } + + impl std::ops::BitOr for $set { + type Output = $set; + + fn bitor(self, other: $set) -> $set { + $set(self.0 | other.0) + } + } + + impl std::ops::BitOrAssign for $set { + fn bitor_assign(&mut self, other: $set) { + self.0 |= other.0; + } + } + }; +} + +/// What happened while a part was parsed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub struct PartFlags(u8); + +flag_set!(PartFlags); + +/// Problems found while decoding a body, returned by +/// [`MessagePart::decoded_checked`] and [`MessagePart::text_checked`]. A +/// non-empty set is what RFC 8621 calls `isEncodingProblem`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub struct DecodeProblems(u8); + +flag_set!(DecodeProblems); + +impl DecodeProblems { + /// The transfer encoding had malformed sections: bytes outside the + /// base64 alphabet were skipped, or malformed quoted-printable escapes + /// were kept as written. + pub const MALFORMED_TRANSFER_ENCODING: DecodeProblems = DecodeProblems(1); + /// The Content-Transfer-Encoding is none of `7bit`, `8bit`, `binary`, + /// `base64` and `quoted-printable`; the body was left as written. + pub const UNKNOWN_TRANSFER_ENCODING: DecodeProblems = DecodeProblems(1 << 1); + /// The charset is unknown, or not supported by this build (the + /// multi-byte charsets need the `full_encoding` feature); the text was + /// decoded as UTF-8. + pub const UNKNOWN_CHARSET: DecodeProblems = DecodeProblems(1 << 2); + /// Byte sequences that are not valid in the charset were replaced by + /// U+FFFD. For UTF-7 also: 8-bit bytes were read as Latin-1, or an + /// unterminated shift sequence at the end was dropped. + pub const MALFORMED_CHARSET: DecodeProblems = DecodeProblems(1 << 3); + + pub(crate) const NAMES: [(DecodeProblems, &'static str); 4] = [ + ( + DecodeProblems::MALFORMED_TRANSFER_ENCODING, + "malformed_transfer_encoding", + ), + ( + DecodeProblems::UNKNOWN_TRANSFER_ENCODING, + "unknown_transfer_encoding", + ), + (DecodeProblems::UNKNOWN_CHARSET, "unknown_charset"), + (DecodeProblems::MALFORMED_CHARSET, "malformed_charset"), + ]; +} + +impl PartFlags { + /// No delimiter of the enclosing multipart ended this part; it runs to + /// the parent's next delimiter or to the end of the input. On a + /// multipart: its first delimiter was its close delimiter, so it has no + /// children and its content is the preamble in + /// [`MessagePart::raw_body`]. + pub const MISSING_DELIMITER: PartFlags = PartFlags(flag::MISSING_DELIMITER as u8); + /// The part ended at a delimiter found in the middle of a line. On a + /// multipart: its first delimiter was found in the middle of a line, + /// because no delimiter at the start of a line opened it (only its close + /// delimiter, or a delimiter of an enclosing multipart, was found). + pub const FALLBACK_DELIMITER: PartFlags = PartFlags(flag::FALLBACK_DELIMITER as u8); + /// The header block did not end with a blank line: it runs to the end of + /// the input, or a delimiter cut it, and the body is empty. On a + /// `message/rfc822` part that is not [`PartKind::Message`]: the nested + /// message was empty or had no header block, so the part keeps its body + /// as text ([`PartKind::Text`], or [`PartKind::Binary`] when it was + /// transfer-encoded). + pub const NO_BLANK_LINE: PartFlags = PartFlags(flag::NO_BLANK_LINE as u8); + /// A multipart without its close delimiter. Not set on the multiparts + /// left open when the part limit stopped the parse. + pub const UNTERMINATED: PartFlags = PartFlags(flag::UNTERMINATED as u8); + /// A transfer-encoded nested message beyond the encoded nesting limit. + pub const NESTING_LIMIT: PartFlags = PartFlags(flag::NESTING_LIMIT as u8); + /// A limit was reached here. Depth limit: this multipart or + /// `message/rfc822` part was not opened and is kept as a leaf. Part + /// limit: the parse stopped inside this part, which holds the content + /// that was not parsed. That is the last part when it is a leaf child of + /// the innermost open multipart (it then runs to the end of its source), + /// else that multipart, or the `message/rfc822` part whose nested + /// message had no part yet; the containers still open all run to the + /// end of their source. + pub const LIMIT_REACHED: PartFlags = PartFlags(flag::LIMIT_REACHED as u8); + + pub(crate) const NAMES: [(PartFlags, &'static str); 6] = [ + (PartFlags::MISSING_DELIMITER, "missing_delimiter"), + (PartFlags::FALLBACK_DELIMITER, "fallback_delimiter"), + (PartFlags::NO_BLANK_LINE, "no_blank_line"), + (PartFlags::UNTERMINATED, "unterminated"), + (PartFlags::NESTING_LIMIT, "nesting_limit"), + (PartFlags::LIMIT_REACHED, "limit_reached"), + ]; +} + +impl<'m> MessagePart<'m> { + pub(crate) fn new(ctx: Ctx<'m>, id: PartId, entry: &'m PartEntry) -> Self { + MessagePart { ctx, id, entry } + } + + #[inline] + fn resolver(&self) -> Resolver<'m> { + self.ctx.resolver(self.entry.message) + } + + fn source(&self) -> &'m [u8] { + self.ctx.source_of(self.entry.message) + } + + fn slice(&self, start: u32, end: u32) -> &'m [u8] { + self.source() + .get(start as usize..end as usize) + .unwrap_or_default() + } + + /// The id of this part in [`crate::Message::parts`]: parts of every + /// message are numbered in document order. + pub fn id(&self) -> PartId { + self.id + } + + pub(crate) fn message_id(&self) -> MessageId { + self.entry.message + } + + /// The message this part belongs to. + pub fn message(&self) -> MessageRef<'m> { + self.ctx.message(self.entry.message) + } + + /// The enclosing multipart; `None` for the root part of a message. + pub fn parent(&self) -> Option<MessagePart<'m>> { + (self.entry.parent != NONE) + .then(|| self.ctx.part(self.entry.parent)) + .flatten() + } + + /// What the part contains, from its Content-Type (and + /// Content-Disposition for [`PartKind::InlineBinary`]). + pub fn kind(&self) -> PartKind<'m> { + match self.entry.kind { + KindTag::Text => PartKind::Text, + KindTag::Html => PartKind::Html, + KindTag::Binary => PartKind::Binary, + KindTag::InlineBinary => PartKind::InlineBinary, + KindTag::Multipart => PartKind::Multipart, + KindTag::Message => PartKind::Message(self.ctx.message(self.entry.children.start)), + } + } + + /// Whether the part is [`PartKind::Text`] or [`PartKind::Html`]. + pub fn is_text(&self) -> bool { + matches!(self.entry.kind, KindTag::Text | KindTag::Html) + } + + /// Whether the part is [`PartKind::Multipart`]. + pub fn is_multipart(&self) -> bool { + self.entry.kind == KindTag::Multipart + } + + /// Whether the part is [`PartKind::Message`]. + pub fn is_message(&self) -> bool { + self.entry.kind == KindTag::Message + } + + /// Children of a multipart, in order. + pub fn children( + &self, + ) -> impl ExactSizeIterator<Item = MessagePart<'m>> + DoubleEndedIterator + use<'m> { + let ctx = self.ctx; + let ids = if self.entry.kind == KindTag::Multipart { + ctx.ids(self.entry.children) + } else { + &[] + }; + ids.iter().map(move |id| ctx.part_or_empty(*id)) + } + + /// The nested message of a `message/rfc822` part. + pub fn nested(&self) -> Option<MessageRef<'m>> { + (self.entry.kind == KindTag::Message).then(|| self.ctx.message(self.entry.children.start)) + } + + /// The header fields of this part. + #[inline] + pub fn headers(&self) -> Headers<'m> { + Headers::new( + self.resolver(), + self.ctx.data(), + self.ctx + .data() + .headers + .get(self.entry.headers.range()) + .unwrap_or_default(), + ) + } + + fn content(&self, index: u32) -> Option<ContentType<'m>> { + let data = self.ctx.data(); + data.content_types + .get(index as usize) + .map(|entry| ContentType::new(self.resolver(), data, entry)) + } + + /// The last Content-Type field, when it parsed. + pub fn content_type(&self) -> Option<ContentType<'m>> { + self.content(self.entry.content_type) + } + + /// The last Content-Disposition field, when it parsed. + pub fn content_disposition(&self) -> Option<ContentType<'m>> { + self.content(self.entry.content_disposition) + } + + /// The Content-Disposition `filename`, else the Content-Type `name`. + pub fn attachment_name(&self) -> Option<&'m str> { + self.content_disposition() + .and_then(|disposition| disposition.attribute("filename")) + .or_else(|| self.content_type()?.attribute("name")) + } + + /// Whether the Content-Type is `type_/subtype` (ASCII case-insensitive). + pub fn is_content_type(&self, type_: &str, subtype: &str) -> bool { + self.content_type().is_some_and(|content_type| { + content_type.ctype().eq_ignore_ascii_case(type_) + && content_type + .subtype() + .is_some_and(|value| value.eq_ignore_ascii_case(subtype)) + }) + } + + /// The Content-ID field, without angle brackets. + pub fn content_id(&self) -> Option<&'m str> { + self.headers().value(HeaderName::ContentId)?.as_text() + } + + /// The Content-Description field, decoded. + pub fn content_description(&self) -> Option<&'m str> { + self.headers() + .value(HeaderName::ContentDescription)? + .as_text() + } + + /// The Content-Location field. + pub fn content_location(&self) -> Option<&'m str> { + self.headers().value(HeaderName::ContentLocation)?.as_text() + } + + /// The languages of the Content-Language field. + pub fn content_language(&self) -> Option<TextList<'m>> { + self.headers() + .value(HeaderName::ContentLanguage)? + .as_text_list() + } + + /// The Content-Transfer-Encoding field as text: unfolded, trimmed, with + /// encoded words decoded (the [`crate::HeaderForm::Text`] form), in the + /// case it was written in. [`MessagePart::encoding`] gives the transfer + /// encoding the body is decoded with. + pub fn content_transfer_encoding(&self) -> Option<&'m str> { + self.headers() + .value(HeaderName::ContentTransferEncoding)? + .as_text() + } + + /// The declared transfer encoding: base64, quoted-printable, or none + /// (`7bit`, `8bit`, `binary`, no field, or an unknown value). + pub fn encoding(&self) -> Encoding { + self.entry.encoding + } + + /// What happened while the part was parsed. + pub fn flags(&self) -> PartFlags { + PartFlags((self.entry.flags & flag::MASK) as u8) + } + + /// Whether the structure of this part was damaged: any of its + /// [`PartFlags`] is set (this replaces 0.11's `is_encoding_problem`). + /// Problems found while decoding the body are reported by + /// [`MessagePart::decoded_checked`] and [`MessagePart::text_checked`]. + pub fn has_problems(&self) -> bool { + self.entry.flags & flag::MASK != 0 + } + + /// Whether the part is in the text body of its message + /// ([`MessageRef::text_body`]). + pub fn in_text_body(&self) -> bool { + self.entry.has_role(role::IN_TEXT_BODY) + } + + /// Whether the part is in the HTML body of its message + /// ([`MessageRef::html_body`]). + pub fn in_html_body(&self) -> bool { + self.entry.has_role(role::IN_HTML_BODY) + } + + /// Whether the part is in the attachments of its message + /// ([`MessageRef::attachments`]). + pub fn is_attachment(&self) -> bool { + self.entry.has_role(role::ATTACHMENT) + } + + /// Whether the part is marked to be rendered inside the message rather + /// than offered as a download (issue #70): `Content-Disposition: inline`, + /// or no disposition on a child of `multipart/related` other than the + /// first (the target of a `cid:` reference). `Content-Disposition: + /// attachment` is never inline. + /// + /// This answers the disposition question only. It does not say whether + /// the part is shown in a body list or offered as an attachment; see + /// [`MessagePart::role`] and the list membership accessors for that. + pub fn is_inline(&self) -> bool { + self.entry.has_role(role::INLINE) + } + + /// The classifier's decision for this part. A part copied into the + /// other body list of a `multipart/alternative` is reported as + /// [`PartRole::CopiedBody`], although it is also in its own list. + pub fn role(&self) -> PartRole { + let flags = self.entry.flags; + match self.entry.kind { + KindTag::Multipart => PartRole::Container, + _ if flags & role::COPIED != 0 => PartRole::CopiedBody, + kind if flags & (role::IN_TEXT_BODY | role::IN_HTML_BODY) != 0 => match kind { + KindTag::Html => PartRole::HtmlBody, + KindTag::Text => PartRole::TextBody, + _ => PartRole::MediaBody, + }, + _ if flags & role::ATTACHMENT != 0 => PartRole::Attachment, + _ => PartRole::Dropped, + } + } + + /// The `boundary` parameter of a multipart part. + pub fn boundary(&self) -> Option<&'m str> { + if self.entry.kind == KindTag::Multipart { + self.content_type()?.attribute("boundary") + } else { + None + } + } + + /// The boundary of the enclosing multipart, whose delimiter starts this + /// part. + pub fn delimiter(&self) -> Option<&'m str> { + self.parent()?.boundary() + } + + /// Headers and body, excluding the line break before the next + /// delimiter. + pub fn raw(&self) -> &'m [u8] { + self.slice(self.entry.offset_header, self.entry.offset_end) + } + + /// The header block, from the first header to the start of the body + /// (the blank line included). The part ends, like any part, before the + /// line break that precedes its delimiter; when that delimiter cuts the + /// header block ([`PartFlags::NO_BLANK_LINE`]), or ends the part and its + /// container right after the blank line, the header block stops there + /// too and excludes that line break, which the last header field + /// ([`crate::Header::offset_end`]) or the blank line still covers. + pub fn raw_headers(&self) -> &'m [u8] { + self.slice(self.entry.offset_header, self.entry.offset_body) + } + + /// The body as written (still transfer-encoded), excluding the line + /// break before the next delimiter. + pub fn raw_body(&self) -> &'m [u8] { + self.slice(self.entry.offset_body, self.entry.offset_end) + } + + /// Offset of the first header of this part in the source buffer of its + /// message ([`MessageRef::source`]). + pub fn offset_header(&self) -> u32 { + self.entry.offset_header + } + + /// Offset of the body of this part in the source buffer of its message. + pub fn offset_body(&self) -> u32 { + self.entry.offset_body + } + + /// Offset of the end of this part in the source buffer of its message. + pub fn offset_end(&self) -> u32 { + self.entry.offset_end + } + + /// The transfer-decoded body; borrowed when nothing needs decoding. + /// Malformed input is decoded on a best-effort basis: bytes outside the + /// base64 alphabet are skipped, malformed quoted-printable escapes are + /// kept as written. [`MessagePart::decoded_checked`] also reports those + /// problems. + pub fn decoded(&self) -> Cow<'m, [u8]> { + decoders::transfer_decode(self.raw_body(), self.entry.encoding) + } + + /// Appends the transfer-decoded body to `out`, for reusing a buffer in + /// a loop. + pub fn decode_into(&self, out: &mut Vec<u8>) { + decoders::transfer_decode_append(self.raw_body(), self.entry.encoding, out) + } + + /// Length of the transfer-decoded body. Base64 and quoted-printable + /// bodies are measured without being decoded, except base64 with bytes + /// outside the alphabet. + pub fn decoded_len(&self) -> usize { + decoders::transfer_decoded_len(self.raw_body(), self.entry.encoding) + } + + /// [`MessagePart::decoded`] together with the problems found while + /// decoding: malformed base64 or quoted-printable, or an unknown + /// Content-Transfer-Encoding. The bytes are the ones `decoded()` + /// returns; `decoded()` stays the faster call when the problems are not + /// needed. + pub fn decoded_checked(&self) -> (Cow<'m, [u8]>, DecodeProblems) { + let (decoded, malformed) = + decoders::transfer_decode_checked(self.raw_body(), self.entry.encoding); + let mut problems = DecodeProblems::default(); + if malformed { + problems |= DecodeProblems::MALFORMED_TRANSFER_ENCODING; + } + if !self.has_known_transfer_encoding() { + problems |= DecodeProblems::UNKNOWN_TRANSFER_ENCODING; + } + (decoded, problems) + } + + fn has_known_transfer_encoding(&self) -> bool { + self.headers() + .get(HeaderName::ContentTransferEncoding) + .is_none_or(|header| decoders::is_known_transfer_encoding(header.raw_value())) + } + + fn charset(&self) -> Option<&'m str> { + self.content_type()?.attribute("charset") + } + + /// The text of a text or HTML part: transfer-decoded, then converted + /// from its charset (UTF-8 when the charset is missing or unknown; byte + /// sequences that are not valid in the charset become U+FFFD). Borrowed + /// when the body needs no conversion. `None` for other parts. + /// [`MessagePart::text_checked`] also reports decoding problems. + pub fn text(&self) -> Option<Cow<'m, str>> { + self.is_text() + .then(|| decoders::to_text(self.decoded(), decoders::charset(self.charset()))) + } + + /// [`MessagePart::text`] together with the problems found while decoding + /// it: those of [`MessagePart::decoded_checked`], an unknown charset, + /// and byte sequences that are not valid in the charset. The text is the + /// one `text()` returns. `None` for parts that are not text. + /// + /// For JMAP, `isEncodingProblem` is `!problems.is_empty()`. + pub fn text_checked(&self) -> Option<(Cow<'m, str>, DecodeProblems)> { + if !self.is_text() { + return None; + } + let (decoded, mut problems) = self.decoded_checked(); + let charset = match self.charset() { + None => Charset::default(), + Some(label) => Charset::from_label(label.as_bytes()).unwrap_or_else(|| { + problems |= DecodeProblems::UNKNOWN_CHARSET; + Charset::default() + }), + }; + if !charset.is_supported() { + problems |= DecodeProblems::UNKNOWN_CHARSET; + } + let (text, malformed) = decoders::to_text_checked(decoded, charset); + if malformed { + problems |= DecodeProblems::MALFORMED_CHARSET; + } + Some((text, problems)) + } + + /// The first `max_chars` characters of [`MessagePart::text`], decoding + /// only as much of the body as they need. `None` for other parts. + pub fn text_prefix(&self, max_chars: usize) -> Option<Cow<'m, str>> { + self.text_prefix_state(decoders::Limit::Chars(max_chars)) + .map(|prefix| prefix.text) + } + + pub(crate) fn text_prefix_state( + &self, + limit: decoders::Limit, + ) -> Option<decoders::TextPrefix<'m>> { + self.is_text().then(|| { + decoders::text_prefix( + self.raw_body(), + self.entry.encoding, + decoders::charset(self.charset()), + limit, + ) + }) + } + + /// Appends the text of a text or HTML part to `out`; returns `false` + /// for other parts. + pub fn text_into(&self, out: &mut String) -> bool { + if !self.is_text() { + return false; + } + decoders::charset(self.charset()).decode_append(&self.decoded(), out); + true + } + + /// The HTML of an HTML part with its `<meta>` charset declarations + /// rewritten to UTF-8 (issue #109), so that a browser reading the + /// decoded text does not apply the original charset a second time. + /// `None` for other parts. + pub fn html_utf8(&self) -> Option<Cow<'m, str>> { + if self.entry.kind != KindTag::Html { + return None; + } + Some(decoders::rewrite(self.text()?, strip_charset_meta)) + } +} + +impl fmt::Debug for MessagePart<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MessagePart") + .field("id", &self.id) + .field("kind", &self.entry.kind) + .field("offset_header", &self.entry.offset_header) + .field("offset_body", &self.entry.offset_body) + .field("offset_end", &self.entry.offset_end) + .finish() + } +} diff --git a/src/view/received.rs b/src/view/received.rs new file mode 100644 index 0000000..edf2946 --- /dev/null +++ b/src/view/received.rs @@ -0,0 +1,332 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::Resolver; +use crate::{ + DateTime, + store::{HostEntry, ReceivedEntry}, +}; +use std::{fmt, net::IpAddr}; + +/// A parsed Received trace field (RFC 5321 section 4.4). Every clause is +/// optional; values compare by content. +#[derive(Clone, Copy)] +pub struct Received<'m> { + resolver: Resolver<'m>, + entry: &'m ReceivedEntry, +} + +/// A host name or an IP address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Host<'m> { + /// A host name, or an address literal that is not an IP address. + Name(&'m str), + /// An IPv4 or IPv6 address. + IpAddr(IpAddr), +} + +/// The TLS version of a Received `with` clause comment. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum TlsVersion { + /// SSL 2. + SSLv2, + /// SSL 3. + SSLv3, + /// TLS 1.0. + TLSv1_0, + /// TLS 1.1. + TLSv1_1, + /// TLS 1.2. + TLSv1_2, + /// TLS 1.3. + TLSv1_3, + /// DTLS 1.0. + DTLSv1_0, + /// DTLS 1.2. + DTLSv1_2, + /// DTLS 1.3. + DTLSv1_3, +} + +/// The greeting command of a Received `from` clause comment. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Greeting { + /// `HELO` (SMTP). + Helo, + /// `EHLO` (ESMTP). + Ehlo, + /// `LHLO` (LMTP). + Lhlo, +} + +/// The protocol of a Received `with` clause (the IANA mail transmission +/// types of RFC 3848 and later). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[allow(clippy::upper_case_acronyms)] +pub enum Protocol { + /// `SMTP`. + SMTP, + /// `ESMTP`. + ESMTP, + /// `ESMTPA`: ESMTP with authentication. + ESMTPA, + /// `ESMTPS`: ESMTP with TLS. + ESMTPS, + /// `ESMTPSA`: ESMTP with TLS and authentication. + ESMTPSA, + /// `LMTP`. + LMTP, + /// `LMTPA`: LMTP with authentication. + LMTPA, + /// `LMTPS`: LMTP with TLS. + LMTPS, + /// `LMTPSA`: LMTP with TLS and authentication. + LMTPSA, + /// `MMS`. + MMS, + /// `UTF8SMTP`. + UTF8SMTP, + /// `UTF8SMTPA`. + UTF8SMTPA, + /// `UTF8SMTPS`. + UTF8SMTPS, + /// `UTF8SMTPSA`. + UTF8SMTPSA, + /// `UTF8LMTP`. + UTF8LMTP, + /// `UTF8LMTPA`. + UTF8LMTPA, + /// `UTF8LMTPS`. + UTF8LMTPS, + /// `UTF8LMTPSA`. + UTF8LMTPSA, + /// `HTTP`. + HTTP, + /// `HTTPS`. + HTTPS, + /// `IMAP`. + IMAP, + /// `POP3`. + POP3, + /// `Local`. + Local, +} + +impl<'m> Received<'m> { + pub(crate) fn new(resolver: Resolver<'m>, entry: &'m ReceivedEntry) -> Self { + Received { resolver, entry } + } + + fn host(&self, host: HostEntry) -> Option<Host<'m>> { + match host { + HostEntry::None => None, + HostEntry::Name(name) => Some(Host::Name(self.resolver.str(name))), + HostEntry::Ip(ip) => Some(Host::IpAddr(ip)), + } + } + + /// Host that sent the message. + pub fn from(&self) -> Option<Host<'m>> { + self.host(self.entry.from) + } + + /// IP address of the sending host: an address literal or an address in + /// a comment. + pub fn from_ip(&self) -> Option<IpAddr> { + self.entry.from_ip + } + + /// The name the sending address resolved to, from a comment. + pub fn from_iprev(&self) -> Option<&'m str> { + self.resolver.opt(self.entry.from_iprev) + } + + /// Host that received the message. + pub fn by(&self) -> Option<Host<'m>> { + self.host(self.entry.by) + } + + /// The recipient of the `for` clause. + pub fn for_(&self) -> Option<&'m str> { + self.resolver.opt(self.entry.for_) + } + + /// The protocol of the `with` clause. + pub fn with(&self) -> Option<Protocol> { + self.entry.with + } + + /// The TLS version named in a comment. + pub fn tls_version(&self) -> Option<TlsVersion> { + self.entry.tls_version + } + + /// The TLS cipher suite, when one is named. + pub fn tls_cipher(&self) -> Option<&'m str> { + self.resolver.opt(self.entry.tls_cipher) + } + + /// The identifier of the `id` clause. + pub fn id(&self) -> Option<&'m str> { + self.resolver.opt(self.entry.id) + } + + /// The ident (RFC 1413) user, from a comment. + pub fn ident(&self) -> Option<&'m str> { + self.resolver.opt(self.entry.ident) + } + + /// The name the sender greeted with (`helo=` in a comment). + pub fn helo(&self) -> Option<Host<'m>> { + self.host(self.entry.helo) + } + + /// The greeting command named in a comment. + pub fn helo_cmd(&self) -> Option<Greeting> { + self.entry.helo_cmd + } + + /// The link of the `via` clause. + pub fn via(&self) -> Option<&'m str> { + self.resolver.opt(self.entry.via) + } + + /// The date after the `;`. + pub fn date(&self) -> Option<DateTime> { + self.entry.date + } +} + +impl fmt::Debug for Received<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Received") + .field("from", &self.from()) + .field("from_ip", &self.from_ip()) + .field("from_iprev", &self.from_iprev()) + .field("by", &self.by()) + .field("for", &self.for_()) + .field("with", &self.with()) + .field("tls_version", &self.tls_version()) + .field("tls_cipher", &self.tls_cipher()) + .field("id", &self.id()) + .field("ident", &self.ident()) + .field("helo", &self.helo()) + .field("helo_cmd", &self.helo_cmd()) + .field("via", &self.via()) + .field("date", &self.date()) + .finish() + } +} + +impl PartialEq for Received<'_> { + fn eq(&self, other: &Self) -> bool { + self.from() == other.from() + && self.from_ip() == other.from_ip() + && self.from_iprev() == other.from_iprev() + && self.by() == other.by() + && self.for_() == other.for_() + && self.with() == other.with() + && self.tls_version() == other.tls_version() + && self.tls_cipher() == other.tls_cipher() + && self.id() == other.id() + && self.ident() == other.ident() + && self.helo() == other.helo() + && self.helo_cmd() == other.helo_cmd() + && self.via() == other.via() + && self.date() == other.date() + } +} + +impl Eq for Received<'_> {} + +impl TlsVersion { + /// The version as usually written (`TLSv1.3`). + pub fn as_str(&self) -> &'static str { + match self { + TlsVersion::SSLv2 => "SSLv2", + TlsVersion::SSLv3 => "SSLv3", + TlsVersion::TLSv1_0 => "TLSv1.0", + TlsVersion::TLSv1_1 => "TLSv1.1", + TlsVersion::TLSv1_2 => "TLSv1.2", + TlsVersion::TLSv1_3 => "TLSv1.3", + TlsVersion::DTLSv1_0 => "DTLSv1.0", + TlsVersion::DTLSv1_2 => "DTLSv1.2", + TlsVersion::DTLSv1_3 => "DTLSv1.3", + } + } +} + +impl Greeting { + /// The command in uppercase. + pub fn as_str(&self) -> &'static str { + match self { + Greeting::Helo => "HELO", + Greeting::Ehlo => "EHLO", + Greeting::Lhlo => "LHLO", + } + } +} + +impl Protocol { + /// The protocol name as written in a `with` clause. + pub fn as_str(&self) -> &'static str { + match self { + Protocol::SMTP => "SMTP", + Protocol::LMTP => "LMTP", + Protocol::ESMTP => "ESMTP", + Protocol::ESMTPS => "ESMTPS", + Protocol::ESMTPA => "ESMTPA", + Protocol::ESMTPSA => "ESMTPSA", + Protocol::LMTPA => "LMTPA", + Protocol::LMTPS => "LMTPS", + Protocol::LMTPSA => "LMTPSA", + Protocol::UTF8SMTP => "UTF8SMTP", + Protocol::UTF8SMTPA => "UTF8SMTPA", + Protocol::UTF8SMTPS => "UTF8SMTPS", + Protocol::UTF8SMTPSA => "UTF8SMTPSA", + Protocol::UTF8LMTP => "UTF8LMTP", + Protocol::UTF8LMTPA => "UTF8LMTPA", + Protocol::UTF8LMTPS => "UTF8LMTPS", + Protocol::UTF8LMTPSA => "UTF8LMTPSA", + Protocol::HTTP => "HTTP", + Protocol::HTTPS => "HTTPS", + Protocol::IMAP => "IMAP", + Protocol::POP3 => "POP3", + Protocol::MMS => "MMS", + Protocol::Local => "Local", + } + } +} + +impl fmt::Display for Host<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Host::Name(name) => f.write_str(name), + Host::IpAddr(ip) => ip.fmt(f), + } + } +} + +impl fmt::Display for Protocol { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl fmt::Display for Greeting { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl fmt::Display for TlsVersion { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} diff --git a/src/view/serialize.rs b/src/view/serialize.rs new file mode 100644 index 0000000..a068aa6 --- /dev/null +++ b/src/view/serialize.rs @@ -0,0 +1,295 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use super::{ + Address, AddressList, AddressRun, ContentType, DecodeProblems, Group, Header, HeaderValue, + Headers, Host, Mailbox, Message, MessagePart, MessageRef, PartFlags, PartKind, PartRole, + Received, Source, TextList, +}; +use crate::Encoding; +use serde::{ + Serialize, Serializer, + ser::{SerializeMap, SerializeStruct}, +}; +use std::cell::Cell; + +struct Seq<I>(Cell<Option<I>>); + +fn seq<I>(iter: I) -> Seq<I> { + Seq(Cell::new(Some(iter))) +} + +impl<I> Serialize for Seq<I> +where + I: Iterator, + I::Item: Serialize, +{ + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.collect_seq(self.0.take().into_iter().flatten()) + } +} + +struct Tagged<'a, T>(&'static str, &'a T); + +impl<T: Serialize> Serialize for Tagged<'_, T> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut map = serializer.serialize_map(Some(1))?; + map.serialize_entry(self.0, self.1)?; + map.end() + } +} + +impl Serialize for Message<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("Message", 2)?; + state.serialize_field("messages", &seq(self.messages()))?; + state.serialize_field("parts", &seq(self.parts()))?; + state.end() + } +} + +impl Serialize for MessageRef<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let ids = |parts: &mut dyn Iterator<Item = MessagePart<'_>>| { + parts.map(|part| part.id()).collect::<Vec<_>>() + }; + let mut state = serializer.serialize_struct("MessageRef", 8)?; + state.serialize_field("id", &self.id())?; + state.serialize_field("root", &self.root_part().id())?; + state.serialize_field("container", &self.container().map(|part| part.id()))?; + state.serialize_field("source", &self.source())?; + state.serialize_field("text_body", &ids(&mut self.text_body()))?; + state.serialize_field("html_body", &ids(&mut self.html_body()))?; + state.serialize_field("attachments", &ids(&mut self.attachments()))?; + state.serialize_field("has_attachments", &self.has_attachments())?; + state.end() + } +} + +impl Serialize for Source { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + match self { + Source::Raw => serializer.serialize_str("raw"), + Source::Decoded(part) => Tagged("decoded", part).serialize(serializer), + } + } +} + +impl Serialize for Encoding { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.serialize_str(match self { + Encoding::None => "none", + Encoding::QuotedPrintable => "quoted-printable", + Encoding::Base64 => "base64", + }) + } +} + +impl Serialize for PartFlags { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + seq(self.names()).serialize(serializer) + } +} + +impl Serialize for DecodeProblems { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + seq(self.names()).serialize(serializer) + } +} + +impl Serialize for PartKind<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.serialize_str(match self { + PartKind::Text => "text", + PartKind::Html => "html", + PartKind::Binary => "binary", + PartKind::InlineBinary => "inline_binary", + PartKind::Multipart => "multipart", + PartKind::Message(_) => "message", + }) + } +} + +impl Serialize for PartRole { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.serialize_str(match self { + PartRole::Container => "container", + PartRole::TextBody => "text_body", + PartRole::HtmlBody => "html_body", + PartRole::CopiedBody => "copied_body", + PartRole::MediaBody => "media_body", + PartRole::Attachment => "attachment", + PartRole::Dropped => "dropped", + }) + } +} + +impl Serialize for MessagePart<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("MessagePart", 16)?; + state.serialize_field("id", &self.id())?; + state.serialize_field("message", &self.message().id())?; + state.serialize_field("parent", &self.parent().map(|part| part.id()))?; + state.serialize_field("kind", &self.kind())?; + match self.kind() { + PartKind::Multipart => { + state.serialize_field("children", &seq(self.children().map(|part| part.id())))? + } + PartKind::Message(nested) => state.serialize_field("nested", &nested.id())?, + _ => state.skip_field("children")?, + } + state.serialize_field("encoding", &self.encoding())?; + state.serialize_field("flags", &self.flags())?; + let roles = [ + (self.in_text_body(), "text_body"), + (self.in_html_body(), "html_body"), + (self.is_attachment(), "attachment"), + (self.is_inline(), "inline"), + ]; + state.serialize_field( + "roles", + &seq(roles.iter().filter(|(set, _)| *set).map(|(_, name)| *name)), + )?; + state.serialize_field("role", &self.role())?; + state.serialize_field("offset_header", &self.offset_header())?; + state.serialize_field("offset_body", &self.offset_body())?; + state.serialize_field("offset_end", &self.offset_end())?; + state.serialize_field("headers", &self.headers())?; + match self.kind() { + PartKind::Text | PartKind::Html => { + let (text, problems) = self.text_checked().unwrap_or_default(); + state.serialize_field("text", &text)?; + state.serialize_field("decode_problems", &problems)?; + } + PartKind::Binary | PartKind::InlineBinary => { + let (decoded, problems) = self.decoded_checked(); + state.serialize_field("binary", &encodify::base64::STANDARD.encode(decoded))?; + state.serialize_field("decode_problems", &problems)?; + } + PartKind::Multipart | PartKind::Message(_) => state.skip_field("text")?, + } + state.end() + } +} + +impl Serialize for Headers<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + seq(self.iter()).serialize(serializer) + } +} + +impl Serialize for Header<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("Header", 5)?; + state.serialize_field("name", self.raw_name())?; + state.serialize_field("value", &self.value())?; + state.serialize_field("offset_field", &self.offset_field())?; + state.serialize_field("offset_start", &self.offset_start())?; + state.serialize_field("offset_end", &self.offset_end())?; + state.end() + } +} + +impl Serialize for HeaderValue<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + match self { + HeaderValue::Empty => serializer.serialize_none(), + HeaderValue::Text(text) => Tagged("text", text).serialize(serializer), + HeaderValue::TextList(list) => Tagged("text_list", list).serialize(serializer), + HeaderValue::Address(list) => Tagged("address", list).serialize(serializer), + HeaderValue::DateTime(date) => Tagged("date_time", date).serialize(serializer), + HeaderValue::ContentType(content_type) => { + Tagged("content_type", content_type).serialize(serializer) + } + HeaderValue::Received(received) => Tagged("received", received).serialize(serializer), + } + } +} + +impl Serialize for TextList<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + seq(self.iter()).serialize(serializer) + } +} + +impl Serialize for AddressList<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + serializer.collect_seq(self.iter()) + } +} + +impl Serialize for Address<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + match self { + Address::Mailbox(mailbox) => Tagged("mailbox", mailbox).serialize(serializer), + Address::Group(group) => Tagged("group", group).serialize(serializer), + } + } +} + +impl Serialize for Mailbox<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("Mailbox", 2)?; + state.serialize_field("name", &self.name())?; + state.serialize_field("address", &self.address())?; + state.end() + } +} + +impl Serialize for Group<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("Group", 2)?; + state.serialize_field("name", &self.name())?; + state.serialize_field("mailboxes", &self.mailboxes())?; + state.end() + } +} + +impl Serialize for AddressRun<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + seq(*self).serialize(serializer) + } +} + +impl Serialize for ContentType<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("ContentType", 3)?; + state.serialize_field("type", self.ctype())?; + state.serialize_field("subtype", &self.subtype())?; + state.serialize_field("attributes", &seq(self.attributes()))?; + state.end() + } +} + +impl Serialize for Host<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + match self { + Host::Name(name) => Tagged("name", name).serialize(serializer), + Host::IpAddr(ip) => Tagged("ip", ip).serialize(serializer), + } + } +} + +impl Serialize for Received<'_> { + fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut state = serializer.serialize_struct("Received", 14)?; + state.serialize_field("from", &self.from())?; + state.serialize_field("from_ip", &self.from_ip())?; + state.serialize_field("from_iprev", &self.from_iprev())?; + state.serialize_field("by", &self.by())?; + state.serialize_field("for", &self.for_())?; + state.serialize_field("with", &self.with())?; + state.serialize_field("tls_version", &self.tls_version())?; + state.serialize_field("tls_cipher", &self.tls_cipher())?; + state.serialize_field("id", &self.id())?; + state.serialize_field("ident", &self.ident())?; + state.serialize_field("helo", &self.helo())?; + state.serialize_field("helo_cmd", &self.helo_cmd())?; + state.serialize_field("via", &self.via())?; + state.serialize_field("date", &self.date())?; + state.end() + } +} diff --git a/tests/api.rs b/tests/api.rs new file mode 100644 index 0000000..97cf709 --- /dev/null +++ b/tests/api.rs @@ -0,0 +1,357 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use mail_parser::{ + Address, AddressList, AddressRun, Charset, ContentType, DateTime, DecodeProblems, Encoding, + Greeting, Group, Header, HeaderForm, HeaderIter, HeaderKey, HeaderName, HeaderValue, Headers, + Host, Mailbox, Message, MessageBuffers, MessageParser, MessagePart, MessageRef, NamedHeaders, + ParsedValue, PartFlags, PartKind, PartRole, Protocol, Received, Source, TextList, TlsVersion, +}; +use std::fmt::Debug; + +const MULTIPART: &[u8] = b"From: Ann <ann@example.com>\r\n\ +To: team: bob@example.com;\r\n\ +Subject: Report\r\n\ +Content-Type: multipart/mixed; boundary=\"b\"\r\n\ +\r\n\ +--b\r\n\ +Content-Type: text/plain\r\n\ +\r\n\ +Hello\r\n\ +--b\r\n\ +Content-Type: application/pdf; name=report.pdf\r\n\ +\r\n\ +%PDF\r\n\ +--b--\r\n"; + +fn send_sync<T: Send + Sync>() {} + +fn copy<T: Copy + Debug>() {} + +fn clone<T: Clone + Debug>() {} + +fn eq<T: Eq + Debug>() {} + +#[test] +fn public_types_are_send_and_sync() { + send_sync::<Message<'static>>(); + send_sync::<MessageParser>(); + send_sync::<MessageBuffers>(); + send_sync::<MessageRef<'static>>(); + send_sync::<MessagePart<'static>>(); + send_sync::<Headers<'static>>(); + send_sync::<Header<'static>>(); + send_sync::<NamedHeaders<'static, 'static>>(); + send_sync::<HeaderIter<'static>>(); + send_sync::<HeaderKey<'static>>(); + send_sync::<HeaderValue<'static>>(); + send_sync::<HeaderName<'static>>(); + send_sync::<AddressList<'static>>(); + send_sync::<Address<'static>>(); + send_sync::<Mailbox<'static>>(); + send_sync::<Group<'static>>(); + send_sync::<AddressRun<'static>>(); + send_sync::<TextList<'static>>(); + send_sync::<ContentType<'static>>(); + send_sync::<Received<'static>>(); + send_sync::<Host<'static>>(); + send_sync::<PartKind<'static>>(); + send_sync::<ParsedValue<'static>>(); +} + +#[test] +fn views_and_small_values_are_copy() { + copy::<MessageRef<'static>>(); + copy::<MessagePart<'static>>(); + copy::<Headers<'static>>(); + copy::<Header<'static>>(); + copy::<HeaderValue<'static>>(); + copy::<AddressList<'static>>(); + copy::<Address<'static>>(); + copy::<Mailbox<'static>>(); + copy::<Group<'static>>(); + copy::<AddressRun<'static>>(); + copy::<TextList<'static>>(); + copy::<ContentType<'static>>(); + copy::<Received<'static>>(); + copy::<Host<'static>>(); + copy::<PartKind<'static>>(); + copy::<PartRole>(); + copy::<PartFlags>(); + copy::<DecodeProblems>(); + copy::<Source>(); + copy::<Encoding>(); + copy::<HeaderForm>(); + copy::<Charset>(); + copy::<DateTime>(); + copy::<Protocol>(); + copy::<Greeting>(); + copy::<TlsVersion>(); + clone::<Message<'static>>(); + clone::<MessageParser>(); + clone::<MessageBuffers>(); + clone::<ParsedValue<'static>>(); + clone::<NamedHeaders<'static, 'static>>(); + clone::<HeaderName<'static>>(); +} + +#[test] +fn values_compare_by_content() { + eq::<HeaderValue<'static>>(); + eq::<AddressList<'static>>(); + eq::<TextList<'static>>(); + eq::<ContentType<'static>>(); + eq::<Received<'static>>(); + eq::<MessageParser>(); + eq::<ParsedValue<'static>>(); + let parser = MessageParser::new(); + let first = parser.parse(MULTIPART).expect("message"); + let copy = MULTIPART.to_vec(); + let second = parser.parse(©).expect("message"); + for name in [ + HeaderName::From, + HeaderName::To, + HeaderName::Subject, + HeaderName::ContentType, + ] { + let value = first.headers().value(name.clone()); + assert!(value.is_some_and(|value| !value.is_empty())); + assert_eq!(value, second.headers().value(name)); + } + assert_ne!( + first.headers().value(HeaderName::From), + first.headers().value(HeaderName::To) + ); + let received = b" from a (b [10.0.0.1]) by c with ESMTPS id 1; Sat, 20 Nov 2021 14:22:01 -0800"; + let parsed = HeaderForm::Received.parse(received); + let again = HeaderForm::Received.parse(received); + assert_eq!(parsed, again); + assert_eq!(parsed.value(), again.value()); + assert_ne!(parsed, HeaderForm::Raw.parse(received)); + assert_eq!( + parsed + .value() + .as_received() + .and_then(|received| received.with()), + Some(Protocol::ESMTPS) + ); +} + +fn shorten_message<'short, 'long: 'short>(message: Message<'long>) -> Message<'short> { + message +} + +fn shorten_part<'short, 'long: 'short>(part: MessagePart<'long>) -> MessagePart<'short> { + part +} + +fn shorten_value<'short, 'long: 'short>(value: HeaderValue<'long>) -> HeaderValue<'short> { + value +} + +fn shorten_name<'short, 'long: 'short>(name: HeaderName<'long>) -> HeaderName<'short> { + name +} + +#[test] +fn message_is_covariant() { + let parser = MessageParser::new(); + let owned: Message<'static> = parser.parse_owned(MULTIPART.to_vec()).expect("message"); + let local = b"Subject: local\r\n\r\nbody".to_vec(); + let mut message = parser.parse(&local).expect("message"); + assert_eq!(message.subject(), Some("local")); + message = owned; + assert_eq!(message.subject(), Some("Report")); + let message = shorten_message(message); + let part = shorten_part(message.root_part()); + assert_eq!(part.children().len(), 2); + let value = shorten_value( + part.headers() + .value(HeaderName::Subject) + .unwrap_or_default(), + ); + assert_eq!(value.as_text(), Some("Report")); + assert!(shorten_name(HeaderName::Other("X-Local".into())).is_other()); +} + +#[test] +fn owned_messages_move_across_threads() { + let message = MessageParser::new() + .parse(MULTIPART) + .expect("message") + .into_owned(); + let subject = std::thread::spawn(move || message.subject().map(str::to_string)) + .join() + .expect("thread"); + assert_eq!(subject.as_deref(), Some("Report")); +} + +#[test] +fn headers_only_messages() { + let parser = MessageParser::new(); + let message = parser.parse_headers(MULTIPART).expect("message"); + let root = message.root_part(); + assert_eq!(message.parts().len(), 1); + assert!(matches!(root.kind(), PartKind::Multipart)); + assert_eq!(root.children().len(), 0); + assert_eq!(root.role(), PartRole::Container); + assert_eq!(root.offset_end() as usize, MULTIPART.len()); + assert_eq!(message.text_body().len(), 0); + assert_eq!(message.html_body().len(), 0); + assert_eq!(message.attachments().len(), 0); + assert_eq!(message.other_parts().count(), 0); + assert!(!message.has_attachments()); + assert_eq!(message.subject(), Some("Report")); + + let single = b"Subject: plain\r\n\r\nHello\r\n"; + let message = parser.parse_headers(single).expect("message"); + let root = message.root_part(); + assert!(matches!(root.kind(), PartKind::Text)); + assert_eq!(root.role(), PartRole::Dropped); + assert_eq!( + message + .other_parts() + .map(|part| part.id()) + .collect::<Vec<_>>(), + [0] + ); + assert!(!message.has_attachments()); + assert_eq!(root.text().as_deref(), Some("Hello\r\n")); +} + +#[test] +fn buffers_stay_usable_after_inputs_that_do_not_parse() { + let parser = MessageParser::new(); + let mut buffers = MessageBuffers::new(); + let mut subjects = Vec::new(); + for raw in [ + MULTIPART, + b"".as_slice(), + b"Subject: second\r\n\r\nbody".as_slice(), + ] { + match parser.parse_with(raw, &mut buffers) { + Some(message) => { + subjects.push(message.subject().map(str::to_string)); + buffers = message.into_buffers(); + } + None => subjects.push(None), + } + } + assert_eq!( + subjects, + [Some("Report".to_string()), None, Some("second".to_string())] + ); +} + +#[test] +fn debug_output_shows_content() { + let message = MessageParser::new().parse(MULTIPART).expect("message"); + let headers = format!("{:?}", message.headers()); + assert!(headers.contains("name: \"Subject\", value: Text(\"Report\")")); + assert!(headers.len() < 2_000); + assert_eq!( + format!("{:?}", message.from().expect("from")), + "[Mailbox(Mailbox { name: Some(\"Ann\"), address: Some(\"ann@example.com\") })]" + ); + assert_eq!( + format!("{:?}", message.to().expect("to")), + "[Group(Group { name: Some(\"team\"), members: [Mailbox { name: None, address: Some(\"bob@example.com\") }] })]" + ); + assert_eq!( + format!("{:?}", message.content_type().expect("content type")), + "ContentType { type: \"multipart\", subtype: Some(\"mixed\"), attributes: {\"boundary\": \"b\"} }" + ); + let parsed = HeaderForm::MessageIds.parse(b" <a@b> <c@d>"); + assert_eq!( + format!("{parsed:?}"), + "ParsedValue { value: TextList([\"a@b\", \"c@d\"]) }" + ); + assert_eq!( + format!("{:?}", MessageBuffers::new()), + "MessageBuffers { .. }" + ); +} + +#[test] +fn headers_iterate_in_for_loops() { + let message = MessageParser::new().parse(MULTIPART).expect("message"); + let headers = message.headers(); + let mut names = Vec::new(); + for header in headers { + names.push(header.raw_name()); + } + assert_eq!(names, ["From", "To", "Subject", "Content-Type"]); + let by_ref: Vec<_> = (&headers) + .into_iter() + .map(|header| header.raw_name()) + .collect(); + assert_eq!(by_ref, names); + let iter: HeaderIter<'_> = headers.iter(); + assert_eq!(iter.len(), 4); + assert_eq!( + headers.iter().rev().map(|header| header.raw_name()).next(), + Some("Content-Type") + ); + assert_eq!( + format!("{:?}", headers.iter()), + "HeaderIter { remaining: 4, .. }" + ); +} + +#[test] +fn all_received_lists_every_trace_field() { + let raw = b"Received: from a.example by b.example; Tue, 1 Jul 2003 10:52:37 +0200\r\n\ +Received: from c.example by d.example; Tue, 1 Jul 2003 10:52:36 +0200\r\n\ +Subject: trace\r\n\r\nbody\r\n"; + let message = MessageParser::new().parse(&raw[..]).expect("message"); + let hosts: Vec<_> = message + .all_received() + .map(|received| received.from().map(|host| host.to_string())) + .collect(); + assert_eq!( + hosts, + [Some("a.example".to_string()), Some("c.example".to_string())] + ); +} + +#[test] +fn header_keys_find_what_names_find() { + let message = MessageParser::new().parse(MULTIPART).expect("message"); + let headers = message.headers(); + for name in [ + HeaderName::Subject, + HeaderName::from("subject"), + HeaderName::Other("SUBJECT".into()), + HeaderName::from("x-missing"), + HeaderName::from("Content-Type"), + ] { + let key: HeaderKey<'_> = name.key(); + let copy = key; + assert_eq!(copy, key); + assert_eq!( + headers + .all_key(key) + .map(|h| h.raw_value()) + .collect::<Vec<_>>(), + headers + .all(name.clone()) + .map(|h| h.raw_value()) + .collect::<Vec<_>>() + ); + assert_eq!( + headers.get_key(key).map(|h| h.raw_value()), + headers.get(name.clone()).map(|h| h.raw_value()) + ); + } + let content_type = HeaderName::from("content-type"); + let key = content_type.key(); + for part in message.parts() { + assert_eq!( + part.headers().get_key(key).is_some(), + part.headers().get("Content-Type").is_some() + ); + } +} diff --git a/tests/classification.rs b/tests/classification.rs new file mode 100644 index 0000000..2ab5816 --- /dev/null +++ b/tests/classification.rs @@ -0,0 +1,139 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod support; + +use mail_parser::{Message, MessageParser, PartKind, PartRole}; +use std::path::PathBuf; +use support::{ids, line_endings, lists, resource}; + +#[test] +fn rfc8621_example() { + for (raw, _) in line_endings(&resource("rfc/007.eml")) { + let message = MessageParser::new().parse(&raw).expect("parses"); + assert_eq!( + lists(message.root()), + [ + vec![1, 5, 6, 7, 15], + vec![1, 9, 15], + vec![6, 10, 11, 12, 13] + ] + ); + let nested = message.messages().nth(1).expect("nested message J"); + assert_eq!(lists(nested), [vec![14], vec![14], vec![]]); + } +} + +#[test] +fn has_attachments_is_per_message() { + for (raw, _) in line_endings(&support::fixture("127.eml")) { + let message = MessageParser::new().parse(&raw).expect("parses"); + let flags: Vec<bool> = message + .messages() + .map(|owner| owner.has_attachments()) + .collect(); + assert_eq!(flags, [false, true]); + } +} + +const DROPPED: [&str; 2] = ["alternative-dropped-footer", "alternative-nested-dropped"]; + +fn fixtures() -> Vec<PathBuf> { + let mut dirs = vec![PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/eml")]; + let mut files = Vec::new(); + while let Some(dir) = dirs.pop() { + for path in std::fs::read_dir(&dir) + .expect("directory") + .flatten() + .map(|entry| entry.path()) + { + if path.is_dir() { + dirs.push(path); + } else if path.extension().is_some_and(|ext| ext == "eml") { + files.push(path); + } + } + } + files.sort(); + files +} + +fn check_roles(message: &Message<'_>, name: &str) -> usize { + for part in message.parts() { + let owner = part.message(); + let in_text = owner.text_body().any(|item| item.id() == part.id()); + let in_html = owner.html_body().any(|item| item.id() == part.id()); + let in_attachments = owner.attachments().any(|item| item.id() == part.id()); + let context = format!("{name} part {} {:?}", part.id(), part.role()); + let kind = part.kind(); + let listed = in_text || in_html; + let consistent = match part.role() { + PartRole::Container => { + matches!(kind, PartKind::Multipart) && !listed && !in_attachments + } + PartRole::TextBody => matches!(kind, PartKind::Text) && listed, + PartRole::HtmlBody => matches!(kind, PartKind::Html) && listed, + PartRole::CopiedBody => in_text && in_html, + PartRole::MediaBody => { + matches!(kind, PartKind::Binary | PartKind::InlineBinary) && listed + } + PartRole::Attachment => in_attachments && !listed, + PartRole::Dropped => !matches!(kind, PartKind::Multipart) && !listed && !in_attachments, + }; + assert!(consistent, "{context}"); + if part + .content_disposition() + .is_some_and(|disposition| disposition.ctype().eq_ignore_ascii_case("attachment")) + { + assert!(!part.is_inline(), "{context}"); + } + if matches!(part.kind(), PartKind::InlineBinary) { + assert!(part.is_inline(), "{context}"); + } + if matches!(part.kind(), PartKind::Binary) { + assert!(!part.is_inline(), "{context}"); + } + } + message + .messages() + .map(|owner| { + let dropped: Vec<u32> = owner + .parts() + .filter(|part| part.role() == PartRole::Dropped) + .map(|part| part.id()) + .collect(); + assert_eq!(ids(owner.other_parts()), dropped, "{name}"); + dropped.len() + }) + .sum() +} + +#[test] +fn roles_partition_every_fixture() { + let files = fixtures(); + assert!(files.len() > 100); + let mut dropped = Vec::new(); + for path in files { + let name = path.display().to_string(); + let raw = std::fs::read(&path).expect("fixture"); + for (raw, _) in line_endings(&raw) { + if let Some(message) = MessageParser::new().parse(&raw) + && check_roles(&message, &name) > 0 + { + dropped.push( + path.file_stem() + .map(|stem| stem.to_string_lossy().into_owned()), + ); + } + } + } + dropped.dedup(); + assert_eq!( + dropped, + DROPPED.map(|name| Some(name.to_string())), + "only these fixtures have a part in no list" + ); +} diff --git a/tests/integration_test.rs b/tests/integration_test.rs index e394801..c072c44 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -4,149 +4,172 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT */ -use mail_parser::*; +mod support; + +use mail_parser::{Address, MessageParser, PartKind}; +use support::regression; + +const README_EXAMPLE: &str = "readme-example"; #[test] fn test_api() { - let input = br#"From: Art Vandelay <art@vandelay.com> (Vandelay Industries) -To: "Colleagues": "James Smythe" <james@vandelay.com>; Friends: - jane@example.com, =?UTF-8?Q?John_Sm=C3=AEth?= <john@example.com>; -Date: Sat, 20 Nov 2021 14:22:01 -0800 -Subject: Why not both importing AND exporting? =?utf-8?b?4pi6?= -Content-Type: multipart/mixed; boundary="festivus"; + let raw = regression(README_EXAMPLE); + let message = MessageParser::default() + .parse(&raw) + .expect("the message parses"); + let headers = MessageParser::default() + .parse_headers(&raw) + .expect("the headers parse"); ---festivus -Content-Type: text/html; charset="us-ascii" -Content-Transfer-Encoding: base64 - -PGh0bWw+PHA+SSB3YXMgdGhpbmtpbmcgYWJvdXQgcXVpdHRpbmcgdGhlICZsZHF1bztle -HBvcnRpbmcmcmRxdW87IHRvIGZvY3VzIGp1c3Qgb24gdGhlICZsZHF1bztpbXBvcnRpbm -cmcmRxdW87LDwvcD48cD5idXQgdGhlbiBJIHRob3VnaHQsIHdoeSBub3QgZG8gYm90aD8 -gJiN4MjYzQTs8L3A+PC9odG1sPg== ---festivus -Content-Type: message/rfc822 - -From: "Cosmo Kramer" <kramer@kramerica.com> -Subject: Exporting my book about coffee tables -Content-Type: multipart/mixed; boundary="giddyup"; - ---giddyup -Content-Type: text/plain; charset="utf-16" -Content-Transfer-Encoding: quoted-printable - -=FF=FE=0C!5=D8"=DD5=D8)=DD5=D8-=DD =005=D8*=DD5=D8"=DD =005=D8"= -=DD5=D85=DD5=D8-=DD5=D8,=DD5=D8/=DD5=D81=DD =005=D8*=DD5=D86=DD = -=005=D8=1F=DD5=D8,=DD5=D8,=DD5=D8(=DD =005=D8-=DD5=D8)=DD5=D8"= -=DD5=D8=1E=DD5=D80=DD5=D8"=DD!=00 ---giddyup -Content-Type: image/gif; name*1="about "; name*0="Book "; - name*2*=utf-8''%e2%98%95 tables.gif -Content-Transfer-Encoding: Base64 -Content-Disposition: attachment - -R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7 ---giddyup-- ---festivus-- -"#; - - // Default parser - let message = MessageParser::default().parse(input).unwrap(); - let headers = MessageParser::default().parse_headers(input).unwrap(); - let custom_message = MessageParser::default() - .with_minimal_headers() - .parse(input) - .unwrap(); - - assert_eq!(message.headers(), headers.headers()); - assert_eq!(message.headers(), custom_message.headers()); - assert_eq!(message.parts.len(), 3); - assert_eq!(headers.parts.len(), 1); - assert_eq!(message.parts.len(), custom_message.parts.len()); - assert_eq!(message.parts, custom_message.parts); + assert_eq!(message.headers().len(), headers.headers().len()); + for (full, only) in message.headers().iter().zip(headers.headers().iter()) { + assert_eq!(full.name(), only.name()); + assert_eq!(full.raw_value(), only.raw_value()); + assert_eq!(full.offset_start(), only.offset_start()); + } + assert_eq!(message.messages().len(), 2); + assert_eq!(message.parts().len(), 6); + assert_eq!(headers.parts().len(), 1); assert_eq!( - bincode::deserialize::<Vec<Header>>( - &bincode::serialize(&message.parts[0].headers).unwrap() - ) - .unwrap(), - message.parts[0].headers - ); - - assert_eq!( - message.from().unwrap().first().unwrap(), - &Addr::new( - "Art Vandelay (Vandelay Industries)".into(), - "art@vandelay.com" - ) - ); - - assert_eq!( - message.to().unwrap().as_group().unwrap(), - &[ - 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!( - message.date().unwrap().to_rfc3339(), - "2021-11-20T14:22:01-08:00" - ); - - assert_eq!( - message.subject().unwrap(), - "Why not both importing AND exporting? ☺" - ); - - assert_eq!( - message.body_html(0).unwrap(), - concat!( + message.body_html(0).as_deref(), + Some(concat!( "<html><p>I was thinking about quitting the “exporting” to ", "focus just on the “importing”,</p><p>but then I thought,", " why not do both? ☺</p></html>" + )) + ); + assert_eq!( + message.body_text(0).as_deref(), + Some(concat!( + "I was thinking about quitting the \u{201c}exporting\u{201d} to focus just on the", + " \u{201c}importing\u{201d},\nbut then I thought, why not do both? \u{263a}\n" + )) + ); + + let container = message.attachments().next().expect("attachment"); + let PartKind::Message(nested) = container.kind() else { + panic!("expected a nested message"); + }; + assert_eq!(nested.id(), 1); + assert_eq!( + nested.body_text(0).as_deref(), + Some( + "\u{210c}\u{1d522}\u{1d529}\u{1d52d} \u{1d52a}\u{1d522} \u{1d522}\u{1d535}\u{1d52d}\u{1d52c}\u{1d52f}\u{1d531} \u{1d52a}\u{1d536} \u{1d51f}\u{1d52c}\u{1d52c}\u{1d528} \u{1d52d}\u{1d529}\u{1d522}\u{1d51e}\u{1d530}\u{1d522}!" + ) + ); + assert_eq!( + nested.body_html(0).as_deref(), + Some( + "<html><body>\u{210c}\u{1d522}\u{1d529}\u{1d52d} \u{1d52a}\u{1d522} \u{1d522}\u{1d535}\u{1d52d}\u{1d52c}\u{1d52f}\u{1d531} \u{1d52a}\u{1d536} \u{1d51f}\u{1d52c}\u{1d52c}\u{1d528} \u{1d52d}\u{1d529}\u{1d522}\u{1d51e}\u{1d530}\u{1d522}!</body></html>" ) ); + let nested_attachment = nested.attachments().next().expect("nested attachment"); + assert_eq!(nested_attachment.decoded_len(), 42); + assert_eq!(nested_attachment.decoded().len(), 42); assert_eq!( - message.body_text(0).unwrap(), - concat!( - "I was thinking about quitting the “exporting” to focus just on the", - " “importing”,\nbut then I thought, why not do both? ☺\n" - ) + nested_attachment.attachment_name(), + Some("Book about \u{2615} tables.gif") ); +} - let nested_message = message.attachment(0).unwrap().message().unwrap(); +#[cfg(all(feature = "serde", feature = "full_encoding"))] +mod full_messages { + use crate::support::{snapshot_inputs, snapshot_messages}; + use mail_parser::MessageParser; + use std::fs; + #[test] + fn parse_full_messages() { + let parser = MessageParser::new(); + let mut failed = Vec::new(); + for path in snapshot_messages() { + let raw = fs::read(&path).expect("the message is readable"); + for (input, extension) in snapshot_inputs(&raw) { + let json = serde_json::to_string_pretty(&parser.parse(&input)) + .expect("the message serializes"); + let expected = path.with_extension(extension); + if fs::read(&expected).ok().as_deref() != Some(json.as_bytes()) { + let output = expected.with_extension("failed"); + fs::write(&output, &json).expect("the output is writable"); + failed.push(output.display().to_string()); + } + } + } + assert!( + failed.is_empty(), + "{} parses differ from their fixture; the parsed messages were saved to:\n{}", + failed.len(), + failed.join("\n") + ); + } +} + +#[test] +fn test_api_field_parsers() { + let raw = regression(README_EXAMPLE); + let message = MessageParser::default() + .parse(&raw) + .expect("the message parses"); + + let from = message.from().and_then(|from| from.first()).expect("from"); + assert_eq!(from.name(), Some("Art Vandelay (Vandelay Industries)")); + assert_eq!(from.address(), Some("art@vandelay.com")); + + let groups: Vec<_> = message + .to() + .expect("to") + .iter() + .map(|address| match address { + Address::Group(group) => ( + group.name().map(str::to_string), + group + .mailboxes() + .map(|mailbox| { + ( + mailbox.name().map(str::to_string), + mailbox.address().map(str::to_string), + ) + }) + .collect::<Vec<_>>(), + ), + Address::Mailbox(_) => panic!("expected groups"), + }) + .collect(); assert_eq!( - nested_message.subject().unwrap(), - "Exporting my book about coffee tables" + groups, + [ + ( + Some("Colleagues".to_string()), + vec![( + Some("James Smythe".to_string()), + Some("james@vandelay.com".to_string()) + )] + ), + ( + Some("Friends".to_string()), + vec![ + (None, Some("jane@example.com".to_string())), + ( + Some("John Sm\u{ee}th".to_string()), + Some("john@example.com".to_string()) + ), + ] + ), + ] ); - assert_eq!( - nested_message.body_text(0).unwrap(), - "ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!" + message.date().map(|date| date.to_rfc3339()).as_deref(), + Some("2021-11-20T14:22:01-08:00") ); - assert_eq!( - nested_message.body_html(0).unwrap(), - "<html><body>ℌ𝔢𝔩𝔭 𝔪𝔢 𝔢𝔵𝔭𝔬𝔯𝔱 𝔪𝔶 𝔟𝔬𝔬𝔨 𝔭𝔩𝔢𝔞𝔰𝔢!</body></html>" + message.subject(), + Some("Why not both importing AND exporting? \u{263a}") ); - - let nested_attachment = nested_message.attachment(0).unwrap(); - - assert_eq!(nested_attachment.len(), 42); - + let container = message.attachments().next().expect("attachment"); assert_eq!( - nested_attachment.attachment_name().unwrap(), - "Book about ☕ tables.gif" + container.nested().and_then(|nested| nested.subject()), + Some("Exporting my book about coffee tables") ); } diff --git a/tests/issue_109.rs b/tests/issue_109.rs new file mode 100644 index 0000000..b4925c7 --- /dev/null +++ b/tests/issue_109.rs @@ -0,0 +1,121 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use mail_parser::{MessageParser, PartKind, strip_charset_meta}; +use std::{borrow::Cow, path::PathBuf}; + +const EM_DASH: char = '\u{2014}'; + +const FIXTURES: [(&str, &str, &str); 5] = [ + ( + "109.eml", + "content=\"text/html; charset=Windows-1252\"", + "content=\"text/html; charset=utf-8\"", + ), + ( + "109-charset.eml", + "<meta charset=Windows-1252>", + "<meta charset=utf-8>", + ), + ( + "109-charset-quoted.eml", + "<meta charset=\"Windows-1252\">", + "<meta charset=\"utf-8\">", + ), + ( + "109-http-equiv.eml", + "content=\"text/html; charset=Windows-1252\"", + "content=\"text/html; charset=utf-8\"", + ), + ( + "109-http-equiv-quot.eml", + "charset="Windows-1252"", + "charset="utf-8"", + ), +]; + +fn fixture(name: &str) -> Vec<u8> { + std::fs::read( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("resources/eml/issues") + .join(name), + ) + .expect("fixture exists") +} + +fn line_endings(raw: &[u8]) -> [Vec<u8>; 2] { + let lf: Vec<u8> = raw.iter().copied().filter(|&byte| byte != b'\r').collect(); + let mut crlf = Vec::with_capacity(lf.len() * 2); + for &byte in &lf { + if byte == b'\n' { + crlf.push(b'\r'); + } + crlf.push(byte); + } + [lf, crlf] +} + +#[test] +fn issue_109_charset_declarations() { + for (name, declared, rewritten) in FIXTURES { + for raw in line_endings(&fixture(name)) { + let message = MessageParser::new() + .parse(&raw) + .expect("the message parses"); + let html_part = message + .html_body() + .next() + .expect("an HTML body part exists"); + assert!(matches!(html_part.kind(), PartKind::Html), "{name}"); + + let html = html_part.text().expect("the HTML part has text"); + assert!(html.contains(declared), "{name}: {html:?}"); + assert!(html.contains(EM_DASH), "{name}: {html:?}"); + + let utf8 = html_part.html_utf8().expect("an HTML part"); + assert!(!utf8.contains(declared), "{name}: {utf8:?}"); + assert!(utf8.contains(rewritten), "{name}: {utf8:?}"); + assert!( + !utf8.to_ascii_lowercase().contains("windows-1252"), + "{name}: {utf8:?}" + ); + assert!(utf8.contains(EM_DASH), "{name}: {utf8:?}"); + assert_eq!( + utf8.replacen(rewritten, declared, 1), + html.as_ref(), + "{name}: only the declaration changes" + ); + + assert_eq!( + message.body_html(0).as_deref(), + Some(html.as_ref()), + "{name}: the default output keeps the declaration" + ); + + let text_part = message.text_body().next().expect("a text body part exists"); + assert!(matches!(text_part.kind(), PartKind::Text), "{name}"); + assert!( + text_part.text().is_some_and(|text| text.contains(EM_DASH)), + "{name}" + ); + assert!(text_part.html_utf8().is_none(), "{name}"); + } + } +} + +#[test] +fn issue_109_unchanged_html_is_borrowed() { + for html in [ + "<html><head><meta charset=\"utf-8\"></head><body>\u{2014}</body></html>", + "<html><head></head><body><meta charset=Windows-1252></body></html>", + "no markup", + ] { + assert!( + matches!(strip_charset_meta(html), Cow::Borrowed(_)), + "{html}" + ); + } +} diff --git a/tests/issues.rs b/tests/issues.rs new file mode 100644 index 0000000..450384f --- /dev/null +++ b/tests/issues.rs @@ -0,0 +1,475 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod support; + +use mail_parser::{ + Address, Message, MessageParser, PartFlags, PartKind, PartRole, html_to_text, text_to_html, +}; +use std::path::PathBuf; +use support::{fixture, ids, line_endings, lists, regression, resource}; + +fn texts(raw: &[u8]) -> Vec<(String, PartFlags)> { + MessageParser::new() + .parse(raw) + .expect("the message parses") + .parts() + .filter(|part| matches!(part.kind(), PartKind::Text)) + .map(|part| (part.text().unwrap_or_default().into_owned(), part.flags())) + .collect() +} + +#[test] +fn issue_156_mid_line_boundary() { + for (raw, eol) in line_endings(&fixture("156.eml")) { + let message = MessageParser::new() + .parse(&raw) + .expect("the message parses"); + assert_eq!(message.parts().len(), 2); + assert!(matches!(message.root_part().kind(), PartKind::Multipart)); + assert_eq!( + texts(&raw), + [( + format!("visit --BND for details{eol}SECRET"), + PartFlags::default() + )] + ); + assert!(message.parts().all(|part| !part.has_problems())); + assert_eq!( + message + .text_body() + .map(|part| part.id()) + .collect::<Vec<_>>(), + [1] + ); + } +} + +#[test] +fn issue_156_boundary_with_suffix() { + for (raw, eol) in line_endings(&fixture("156-suffix.eml")) { + assert_eq!( + texts(&raw), + [( + format!("first{eol}--BNDX not a delimiter{eol}last"), + PartFlags::default() + )] + ); + } +} + +#[test] +fn issue_156_fallback_is_flagged() { + for (raw, _) in line_endings(&fixture("156-fallback.eml")) { + let parts = texts(&raw); + assert_eq!(parts.len(), 2); + assert_eq!(parts[0], ("first part".to_string(), PartFlags::default())); + assert_eq!(parts[1].0, "second part ends here"); + assert!(parts[1].1.contains(PartFlags::FALLBACK_DELIMITER)); + let message = MessageParser::new() + .parse(&raw) + .expect("the message parses"); + assert!( + !message + .root_part() + .flags() + .contains(PartFlags::UNTERMINATED) + ); + } +} + +#[derive(Debug, PartialEq, Eq)] +enum Item<'x> { + Mailbox(&'x str), + Group(&'x str, Vec<&'x str>), +} + +#[test] +fn issue_98_address_lists_in_document_order() { + let mailbox = Item::Mailbox; + let cases = [ + ("98-list.eml", vec![mailbox("x@y.com"), mailbox("x@y.com")]), + ( + "98-mixed.eml", + vec![ + mailbox("x@y.com"), + Item::Group("group", vec!["some text"]), + mailbox("x@y.com"), + ], + ), + ( + "98-group-first.eml", + vec![ + Item::Group("first", vec!["a@b.c", "d@e.f"]), + mailbox("x@y.com"), + ], + ), + ( + "98-group-last.eml", + vec![mailbox("x@y.com"), Item::Group("last", vec!["a@b.c"])], + ), + ( + "98-adjacent-groups.eml", + vec![ + Item::Group("one", vec!["a@b.c"]), + Item::Group("two", vec!["d@e.f"]), + ], + ), + ]; + for (name, expected) in cases { + for (raw, _) in line_endings(&fixture(name)) { + let message = MessageParser::new() + .parse(&raw) + .expect("the message parses"); + let to = message.to().expect("To is an address list"); + let items: Vec<_> = to + .iter() + .map(|item| match item { + Address::Mailbox(mailbox) => { + Item::Mailbox(mailbox.address().unwrap_or_default()) + } + Address::Group(group) => Item::Group( + group.name().unwrap_or_default(), + group + .mailboxes() + .map(|member| member.address().or(member.name()).unwrap_or_default()) + .collect(), + ), + }) + .collect(); + assert_eq!(items, expected, "{name}"); + assert_eq!( + to.has_groups(), + expected.iter().any(|item| matches!(item, Item::Group(..))), + "{name}" + ); + } + } +} + +#[test] +fn every_fixture_parses_in_both_line_endings() { + let mut dirs = vec![PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/eml")]; + let mut count = 0; + while let Some(dir) = dirs.pop() { + for path in std::fs::read_dir(&dir) + .expect("directory") + .flatten() + .map(|entry| entry.path()) + { + if path.is_dir() { + dirs.push(path); + } else if path.extension().is_some_and(|ext| ext == "eml") { + let raw = std::fs::read(&path).expect("file"); + for (raw, _) in line_endings(&raw) { + if let Some(message) = MessageParser::new().parse(&raw) { + for part in message.parts() { + let _ = part.decoded(); + let _ = part.text(); + for header in part.headers().iter() { + let _ = header.value(); + let _ = header.name(); + } + } + } + } + count += 1; + } + } + } + assert!(count > 100); +} + +#[test] +fn issue_70_inline_images_in_related() { + for (raw, eol) in line_endings(&fixture("70.eml")) { + let message = MessageParser::new() + .parse(&raw) + .expect("the message parses"); + assert_eq!(message.parts().len(), 6); + assert_eq!(lists(message.root()), [vec![2], vec![3], vec![4, 5]]); + for (id, body) in [(4, "A"), (5, "B")] { + let image = message.part(id).expect("image part"); + assert!(image.is_inline(), "part {id}"); + assert!(matches!(image.kind(), PartKind::InlineBinary), "part {id}"); + assert_eq!(image.decoded().as_ref(), format!("{body}{eol}").as_bytes()); + assert_eq!(image.role(), PartRole::Attachment); + } + for id in [0, 1, 2, 3] { + assert!(!message.part(id).expect("part").is_inline(), "part {id}"); + } + assert!(!message.has_attachments()); + } +} + +#[test] +fn issue_67_legacy_032_lists() { + for (raw, _) in line_endings(&resource("legacy/032.eml")) { + let message = MessageParser::new().parse(&raw).expect("parses"); + assert_eq!( + lists(message.root()), + [vec![2, 4, 5], vec![3, 4, 5], vec![]] + ); + assert_eq!(message.other_parts().count(), 0); + assert!(!message.has_attachments()); + } +} + +#[test] +fn issue_67_alternative_with_inline_image() { + for (raw, _) in line_endings(&fixture("67-alternative.eml")) { + let message = MessageParser::new() + .parse(&raw) + .expect("the message parses"); + assert_eq!(lists(message.root()), [vec![1], vec![1], vec![2]]); + let image = message.part(2).expect("image"); + assert!(image.is_inline()); + assert!(matches!(image.kind(), PartKind::InlineBinary)); + assert_eq!(image.role(), PartRole::Attachment); + assert_eq!(message.part(1).expect("text").role(), PartRole::CopiedBody); + assert!(!message.has_attachments()); + } +} + +fn assert_partition(message: &Message<'_>, expected: &[PartRole]) { + assert_eq!( + message.parts().map(|part| part.role()).collect::<Vec<_>>(), + expected + ); + for part in message.parts() { + let owner = part.message(); + let in_text = owner.text_body().any(|item| item.id() == part.id()); + let in_html = owner.html_body().any(|item| item.id() == part.id()); + let in_attachments = owner.attachments().any(|item| item.id() == part.id()); + let buckets = [ + part.role() == PartRole::Container, + matches!( + part.role(), + PartRole::TextBody + | PartRole::HtmlBody + | PartRole::CopiedBody + | PartRole::MediaBody + ) && (in_text || in_html), + part.role() == PartRole::Attachment && in_attachments && !in_text && !in_html, + part.role() == PartRole::Dropped && !in_text && !in_html && !in_attachments, + ]; + assert_eq!( + buckets.iter().filter(|bucket| **bucket).count(), + 1, + "part {} is in exactly one role", + part.id() + ); + } +} + +#[test] +fn issue_107_every_part_has_one_role() { + use PartRole::{Container, HtmlBody, MediaBody, TextBody}; + for (raw, _) in line_endings(&resource("legacy/032.eml")) { + let message = MessageParser::new().parse(&raw).expect("parses"); + assert_partition( + &message, + &[ + Container, Container, TextBody, HtmlBody, MediaBody, MediaBody, + ], + ); + assert_eq!(message.other_parts().count(), 0); + } + for (raw, _) in line_endings(&fixture("107-image-first.eml")) { + let message = MessageParser::new().parse(&raw).expect("parses"); + assert_partition( + &message, + &[ + Container, MediaBody, Container, TextBody, HtmlBody, MediaBody, + ], + ); + assert_eq!( + lists(message.root()), + [vec![1, 3, 5], vec![1, 4, 5], vec![]] + ); + assert!(message.body_html(0).is_none()); + assert_eq!( + message + .parts() + .filter(|part| part.role() == HtmlBody) + .map(|part| part.id()) + .collect::<Vec<_>>(), + [4] + ); + } +} + +#[test] +fn issue_73_text_bodies_yield_text() { + for (raw, _) in line_endings(&fixture("73.eml")) { + let message = MessageParser::new().parse(&raw).expect("parses"); + let html_part = message.part(1).expect("html part"); + assert!(matches!(html_part.kind(), PartKind::Html)); + assert_eq!(ids(message.text_body()), [1]); + assert_eq!(ids(message.html_body()), [1]); + assert_eq!(html_part.role(), PartRole::CopiedBody); + + let html = html_part.text().expect("html text"); + assert!(html.starts_with("<html><p>I was thinking")); + let texts: Vec<String> = message + .text_bodies() + .map(|text| text.into_owned()) + .collect(); + assert_eq!(texts, [html_to_text(&html)]); + assert!(!texts[0].contains('<')); + assert!(texts[0].contains("the \u{201c}exporting\u{201d} to focus")); + assert_eq!(message.body_text(0).as_deref(), Some(texts[0].as_str())); + + let htmls: Vec<String> = message + .html_bodies() + .map(|html| html.into_owned()) + .collect(); + assert_eq!(htmls, [html.as_ref()]); + } + + for (raw, _) in line_endings(®ression("mixed-text-image-html")) { + let message = MessageParser::new().parse(&raw).expect("parses"); + assert_eq!(ids(message.text_body()), [1, 2, 3]); + let texts: Vec<String> = message + .text_bodies() + .map(|text| text.into_owned()) + .collect(); + assert_eq!(texts, ["first".to_string(), html_to_text("<p>third</p>")]); + let htmls: Vec<String> = message + .html_bodies() + .map(|html| html.into_owned()) + .collect(); + assert_eq!(htmls, [text_to_html("first"), "<p>third</p>".to_string()]); + } +} + +const OUTER_HEADERS: &str = "From: Boundary Tester <tester@example.com>\n\ +To: Recipient <recipient@example.com>\n\ +Subject: Boundaries of every part\n\ +MIME-Version: 1.0\n\ +Content-Type: multipart/mixed; boundary=\"outer-mixed\"\n\n"; +const ALTERNATIVE_HEADERS: &str = + "Content-Type: multipart/alternative; boundary=\"inner-alternative\"\n\n"; +const PLAIN_HEADERS: &str = "Content-Type: text/plain; charset=us-ascii\n\n"; +const HTML_HEADERS: &str = "Content-Type: text/html; charset=us-ascii\n\n"; +const RFC822_HEADERS: &str = "Content-Type: message/rfc822\nContent-Disposition: inline\n\n"; +const NESTED_HEADERS: &str = "From: Nested Sender <nested@example.com>\n\ +Subject: Nested message\n\ +MIME-Version: 1.0\n\ +Content-Type: multipart/mixed; boundary=\"nested-mixed\"\n\n"; +const BINARY_HEADERS: &str = + "Content-Type: application/octet-stream\nContent-Transfer-Encoding: base64\n\n"; +const ALTERNATIVE_BODY: &str = "--inner-alternative\n\ +Content-Type: text/plain; charset=us-ascii\n\n\ +Plain version.\n\ +--inner-alternative\n\ +Content-Type: text/html; charset=us-ascii\n\n\ +<p>HTML version.</p>\n\ +--inner-alternative--\n\ +Alternative epilogue."; +const NESTED_BODY: &str = "--nested-mixed\n\ +Content-Type: text/plain; charset=us-ascii\n\n\ +Nested text.\n\ +--nested-mixed\n\ +Content-Type: application/octet-stream\n\ +Content-Transfer-Encoding: base64\n\n\ +AAECAw==\n\ +--nested-mixed--"; + +#[test] +fn issue_127_boundaries_and_raw_ranges() { + let original = fixture("127.eml"); + let original = String::from_utf8(original).expect("ascii fixture"); + let nested = format!("{NESTED_HEADERS}{NESTED_BODY}"); + let expected: [(Option<&str>, Option<&str>, &str, String); 8] = [ + ( + Some("outer-mixed"), + None, + OUTER_HEADERS, + original + .strip_prefix(OUTER_HEADERS) + .expect("headers first") + .to_string(), + ), + ( + Some("inner-alternative"), + Some("outer-mixed"), + ALTERNATIVE_HEADERS, + ALTERNATIVE_BODY.to_string(), + ), + ( + None, + Some("inner-alternative"), + PLAIN_HEADERS, + "Plain version.".to_string(), + ), + ( + None, + Some("inner-alternative"), + HTML_HEADERS, + "<p>HTML version.</p>".to_string(), + ), + (None, Some("outer-mixed"), RFC822_HEADERS, nested.clone()), + ( + Some("nested-mixed"), + None, + NESTED_HEADERS, + NESTED_BODY.to_string(), + ), + ( + None, + Some("nested-mixed"), + PLAIN_HEADERS, + "Nested text.".to_string(), + ), + ( + None, + Some("nested-mixed"), + BINARY_HEADERS, + "AAECAw==".to_string(), + ), + ]; + for (raw, eol) in line_endings(original.as_bytes()) { + let message = MessageParser::new().parse(&raw).expect("parses"); + assert_eq!(message.parts().len(), expected.len()); + assert_eq!(message.messages().len(), 2); + for (part, (boundary, delimiter, headers, body)) in message.parts().zip(&expected) { + let headers = headers.replace('\n', eol); + let body = body.replace('\n', eol); + let id = part.id(); + assert_eq!(part.boundary(), *boundary, "part {id} boundary"); + assert_eq!(part.delimiter(), *delimiter, "part {id} delimiter"); + assert_eq!(part.raw_headers(), headers.as_bytes(), "part {id} headers"); + assert_eq!(part.raw_body(), body.as_bytes(), "part {id} body"); + assert_eq!( + part.raw(), + format!("{headers}{body}").as_bytes(), + "part {id} raw" + ); + } + assert_eq!(message.root_part().raw(), raw.as_slice()); + for (boundary, id) in [ + ("outer-mixed", 0), + ("inner-alternative", 1), + ("nested-mixed", 5), + ] { + assert_eq!( + message.part_by_boundary(boundary).map(|part| part.id()), + Some(id), + "{boundary}" + ); + } + assert!(message.part_by_boundary("missing").is_none()); + assert!(message.part_by_boundary("outer").is_none()); + let nested_message = message + .part(4) + .and_then(|part| part.nested()) + .expect("nested"); + assert_eq!(nested_message.root_part().id(), 5); + assert_eq!(nested_message.raw(), nested.replace('\n', eol).as_bytes()); + assert!(message.part(4).expect("rfc822").is_inline()); + } +} diff --git a/tests/review_fields.rs b/tests/review_fields.rs new file mode 100644 index 0000000..b060ac4 --- /dev/null +++ b/tests/review_fields.rs @@ -0,0 +1,240 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod support; + +use mail_parser::{DateTime, HeaderForm, HeaderName, HeaderValue, Message, MessageParser}; +use std::{ + borrow::Cow, + time::{Duration, Instant}, +}; +use support::regression; + +const BUDGET: Duration = Duration::from_secs(3); + +fn parse(raw: &[u8]) -> Message<'_> { + MessageParser::new().parse(raw).expect("message") +} + +fn parse_within_budget<'x>(label: &str, raw: &'x [u8]) -> Message<'x> { + let started = Instant::now(); + let message = parse(raw); + let elapsed = started.elapsed(); + assert!( + elapsed < BUDGET, + "{label}: {elapsed:?} for {} bytes", + raw.len() + ); + message +} + +#[test] +fn folded_colon_less_lines_are_linear() { + let mut raw = b"Subject: x\nX".to_vec(); + for _ in 0..200_000 { + raw.extend_from_slice(b"\n a"); + } + raw.extend_from_slice(b"\n\nbody\n"); + let message = parse_within_budget("folded colon-less lines", &raw); + assert_eq!(message.subject(), Some("x")); + assert_eq!(message.headers().len(), 1); + assert_eq!(message.root_part().raw_body(), b"body\n"); +} + +#[test] +fn rfc2231_continuations_are_joined_once_and_capped() { + let mut raw = b"Content-Type: text/plain; name*0=start".to_vec(); + for index in 1..=45_000 { + raw.extend_from_slice(format!(";\n name*{index}=abcdefghij").as_bytes()); + } + raw.extend_from_slice(b"\n\nbody\n"); + let message = parse_within_budget("rfc2231 continuations", &raw); + let content_type = message.content_type().expect("content type"); + let name = content_type.attribute("name").expect("joined value"); + assert_eq!(name.len(), "start".len() + 999 * "abcdefghij".len()); + assert!(name.starts_with("startabcdefghij")); + assert_eq!(content_type.attributes().count(), 1); +} + +#[test] +fn rfc2231_distinct_sections_and_languages_are_linear() { + for (label, param) in [ + ("distinct sections", ";\n n{i}*1=v"), + ("encoded params with a language", ";\n p{i}*0*=utf-8'en'v"), + ] { + let mut raw = b"Content-Type: text/plain".to_vec(); + for index in 0..60_000 { + raw.extend_from_slice(param.replace("{i}", &index.to_string()).as_bytes()); + } + raw.extend_from_slice(b"\n\nbody\n"); + let message = parse_within_budget(label, &raw); + let count = message + .content_type() + .map_or(0, |content_type| content_type.attributes().count()); + assert!((500..=1_000).contains(&count), "{label}: {count}"); + } + + let mut raw = b"Content-Type: multipart/mixed; boundary=b\n\n".to_vec(); + for _ in 0..40 { + raw.extend_from_slice(b"--b\nContent-Type: text/plain"); + for index in 0..990 { + raw.extend_from_slice(format!(";\n n{index}*1=v").as_bytes()); + } + raw.extend_from_slice(b"\n\nbody\n"); + } + raw.extend_from_slice(b"--b--\n"); + let message = parse_within_budget("many capped fields", &raw); + assert_eq!(message.parts().len(), 41); + for part in message.parts().skip(1) { + let content_type = part.content_type().expect("content type"); + assert_eq!(content_type.attributes().count(), 990); + assert_eq!(content_type.attribute("n989"), Some("v")); + } +} + +#[test] +fn empty_text_and_raw_fields_are_empty_strings() { + for name in [ + "empty-subject", + "empty-subject-blanks", + "empty-subject-folded", + ] { + let raw = regression(name); + assert_eq!(parse(&raw).thread_name(), Some(""), "{name}"); + } + assert_eq!(HeaderForm::Raw.parse(b"").value(), HeaderValue::Text("")); + assert_eq!( + HeaderForm::Ignore.parse(b" x\n").value(), + HeaderValue::Empty + ); +} + +fn check_strict_name(raw: &[u8], spelling: &str) { + let message = parse(raw); + let from = message + .from() + .and_then(|from| from.first()) + .and_then(|mailbox| mailbox.address()); + assert_eq!(from, Some("good@x.com"), "{spelling:?}"); + let odd = message.headers().iter().nth(1).expect("second header"); + assert_eq!(odd.raw_name(), spelling); + assert_eq!(odd.name(), HeaderName::Other(spelling.into())); + assert!(message.headers().get(spelling).is_some(), "{spelling:?}"); +} + +#[test] +fn header_names_are_strict() { + for (name, spelling) in [ + ("header-name-space", "Fr om"), + ("header-name-leading-colon", ":From"), + ("header-name-colons-and-blanks", ":: From"), + ("header-name-form-feed", "F\x0crom"), + ("header-name-nul", "Fr\x00om"), + ] { + check_strict_name(®ression(name), spelling); + } + check_strict_name(b"From: good@x.com\nFrom\r: evil@x.com\n\nbody\n", "From\r"); + let raw = regression("header-name-smuggled-subject"); + assert!(!parse(&raw).headers().has_known()); +} + +#[test] +fn other_names_spelled_like_known_names_are_normalised() { + let raw = b"X-Mailer: Ann <ann@example.com>\nSubject: s\nReceived: a\nReceived: b\n\nbody\n"; + let by_other = + MessageParser::new().header(HeaderName::Other("x-MAILER".into()), HeaderForm::Addresses); + let message = by_other.parse(raw).expect("message"); + let mailer = message.headers().value(HeaderName::XMailer); + assert!( + mailer.and_then(|value| value.as_address()).is_some(), + "{mailer:?}" + ); + let ignored = MessageParser::new() + .header(HeaderName::Other("Content-Type".into()), HeaderForm::Raw) + .parse(b"Content-Type: text/html\n\nbody") + .expect("message"); + assert!(ignored.root_part().is_content_type("text", "html")); + + let message = parse(raw); + let headers = message.headers(); + let other = |name: &'static str| HeaderName::Other(Cow::Borrowed(name)); + assert_eq!( + headers + .get(other("X-Mailer")) + .map(|header| header.raw_name()), + Some("X-Mailer") + ); + assert_eq!( + headers + .get(other("subject")) + .map(|header| header.raw_value()), + Some(&b" s\n"[..]) + ); + assert_eq!(headers.all(other("RECEIVED")).count(), 2); + assert!(headers.contains(other("received"))); + assert_eq!(other("Subject"), HeaderName::Subject); + assert_ne!(other("X-Custom"), HeaderName::Subject); +} + +#[test] +fn every_field_name_character_can_be_named() { + let message = parse(b"X.Spam: yes\nX-Tag: t\n\nbody\n"); + assert_eq!( + message + .headers() + .get("X.Spam") + .map(|header| header.raw_value()), + Some(&b" yes\n"[..]) + ); + assert_eq!( + HeaderName::from("X.Spam"), + HeaderName::Other("X.Spam".into()) + ); + assert_eq!( + HeaderName::parse("X.Spam"), + Some(HeaderName::Other("X.Spam".into())) + ); + + let message = MessageParser::new() + .header("X.Sender", HeaderForm::Addresses) + .parse(b"X.Sender: Ann <ann@example.com>\n\nbody\n") + .expect("message"); + let header = message.headers().iter().next().expect("header"); + let address = header + .value() + .as_address() + .and_then(|list| list.first()) + .and_then(|mailbox| mailbox.address()); + assert_eq!(address, Some("ann@example.com")); + assert!(message.headers().get(header.name()).is_some()); +} + +#[test] +fn utf16_dangling_byte_is_replaced() { + let raw = regression("utf16-dangling-byte"); + let message = parse(&raw); + let part = message.part(1).expect("the first case"); + let (text, problems) = part.text_checked().expect("text part"); + assert_eq!(text, "ab\u{fffd}"); + assert!(!problems.is_empty()); + assert_eq!(part.text_prefix(10).as_deref(), Some("ab\u{fffd}")); + assert_eq!(part.text_prefix(2).as_deref(), Some("ab")); +} + +#[test] +fn to_timezone_saturates() { + let date = DateTime::from_timestamp(1_637_446_921); + for tz in [i64::MIN, i64::MIN + 1, i64::MAX, -1, 0, 3_600] { + let moved = date.to_timezone(tz); + assert_eq!(moved.tz_before_gmt, tz < 0); + assert!(moved.tz_minute < 60); + } + assert_eq!(date.to_timezone(i64::MIN).tz_hour, u8::MAX); + assert_eq!( + date.to_timezone(3_600).to_rfc3339(), + "2021-11-20T23:22:01+01:00" + ); +} diff --git a/tests/review_structure.rs b/tests/review_structure.rs new file mode 100644 index 0000000..1fb9f6d --- /dev/null +++ b/tests/review_structure.rs @@ -0,0 +1,417 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod support; + +use mail_parser::{ + Message, MessageBuffers, MessageParser, MessagePart, PartFlags, PartKind, Source, +}; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; +use support::{line_endings, resource}; + +const CHAIN_BUDGET: Duration = Duration::from_secs(5); +const NOISE_LINE: &[u8] = b"\n--X"; + +fn parse(raw: &[u8]) -> Message<'_> { + MessageParser::new().parse(raw).expect("the input parses") +} + +fn flags(part: MessagePart<'_>) -> Vec<&'static str> { + part.flags().names().collect() +} + +fn check_nesting(message: &Message<'_>) { + for part in message.parts() { + let label = format!("part {}", part.id()); + assert!(part.offset_header() <= part.offset_body(), "{label}"); + assert!(part.offset_body() <= part.offset_end(), "{label}"); + assert!( + part.offset_end() as usize <= part.message().source_bytes().len(), + "{label}" + ); + let container = part + .parent() + .or_else(|| part.message().container()) + .filter(|container| container.message().source() == part.message().source()); + if let Some(container) = container { + assert!( + container.offset_body() <= part.offset_header(), + "{label} starts before its container {}", + container.id() + ); + assert!( + part.offset_end() <= container.offset_end(), + "{label} ends past its container {}", + container.id() + ); + } + } +} + +fn chain(root: &[u8], part: &[u8], parts: usize, noise: usize, tail: &[u8]) -> Vec<u8> { + let mut raw = root.to_vec(); + for _ in 0..parts { + raw.extend_from_slice(part); + } + for _ in 0..noise { + raw.extend_from_slice(NOISE_LINE); + } + raw.extend_from_slice(tail); + raw +} + +fn fixtures() -> Vec<Vec<u8>> { + let mut files = Vec::new(); + for suite in [ + "rfc", + "legacy", + "thirdparty", + "malformed", + "issues", + "regressions", + ] { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("resources/eml") + .join(suite); + let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir) + .expect("the suite directory exists") + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| path.extension().is_some_and(|ext| ext == "eml")) + .collect(); + paths.sort_unstable(); + files.extend(paths.iter().filter_map(|path| std::fs::read(path).ok())); + } + files +} + +struct Rng(u64); + +impl Rng { + fn below(&mut self, bound: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % bound.max(1) as u64) as usize + } +} + +#[test] +fn security_bug_input_keeps_its_content() { + let raw = resource("malformed/023.eml"); + for (input, _) in line_endings(&raw) { + let message = parse(&input); + check_nesting(&message); + let root = message.root_part(); + assert!(matches!(root.kind(), PartKind::Multipart)); + assert_eq!(flags(root), ["fallback_delimiter"]); + let children: Vec<MessagePart<'_>> = root.children().collect(); + assert_eq!(children.len(), 1); + let child = children.first().copied().expect("one child"); + assert!(matches!(child.kind(), PartKind::Text)); + assert!(child.flags().is_empty()); + let text = child.text().expect("text"); + assert_eq!(text.replace('\r', ""), "5\nContent-Type:message/rfc822\n\n"); + assert_eq!(message.text_body().len(), 1); + for part in message.parts() { + let _ = (part.text(), part.decoded(), part.text_checked()); + let _ = (part.raw(), part.raw_headers(), part.raw_body()); + } + let _ = message.body_preview(64); + let headers = MessageParser::new() + .parse_headers(&input) + .expect("the headers parse"); + assert_eq!(headers.parts().len(), 1); + } +} + +#[test] +fn parts_stay_inside_their_containers() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let inserts: [&[u8]; 6] = [ + b"\n--", + b"\n\n", + b"\nContent-Type: message/rfc822\n\n", + b"\nContent-Type: multipart/mixed; boundary=x\n\n--x\n", + b"\nContent-Transfer-Encoding: base64\n", + b"--", + ]; + for file in fixtures() { + for (input, _) in line_endings(&file) { + if let Some(message) = MessageParser::new().parse(&input) { + check_nesting(&message); + } + for _ in 0..12 { + let mut mutated = input.clone(); + for _ in 0..=rng.below(3) { + let at = rng.below(mutated.len() + 1); + match rng.below(3) { + 0 => { + let end = (at + rng.below(64)).min(mutated.len()); + mutated.drain(at..end); + } + 1 => { + let insert = inserts.get(rng.below(inserts.len())).copied(); + let tail = mutated.split_off(at); + mutated.extend_from_slice(insert.unwrap_or_default()); + mutated.extend_from_slice(&tail); + } + _ => mutated.truncate(at), + } + } + if let Some(message) = MessageParser::new().parse(&mutated) { + check_nesting(&message); + } + } + } + } +} + +#[test] +fn fallback_chains_are_linear() { + let root = b"Content-Type: multipart/mixed; boundary=B\n\n"; + let encoded_part = b"x--B\nContent-Type: message/rfc822\nContent-Transfer-Encoding: base64\n\nU3ViamVjdDogcw0KDQpib2R5DQo=\n"; + let cases: [(&str, Vec<u8>, usize); 5] = [ + ( + "fallback chain", + chain(root, b"x--B\n\n", 4_000, 400_000, b"\n"), + 4_001, + ), + ( + "message/rfc822 fallback chain", + chain( + root, + b"x--B\nContent-Type: message/rfc822\n\nSubject: s\n\nbody\n", + 4_000, + 400_000, + b"\n", + ), + 8_001, + ), + ( + "nested fallback chain", + chain( + b"Content-Type: multipart/mixed; boundary=A\n\n--A\nContent-Type: multipart/mixed; boundary=B\n\n", + b"x--B\n\n", + 4_000, + 400_000, + b"\n--A--\n", + ), + 4_002, + ), + ( + "encoded message/rfc822 fallback chain", + chain(root, encoded_part, 2_000, 400_000, b"\n"), + 4_001, + ), + ( + "chain of multiparts whose boundary never occurs", + chain( + root, + b"x--B\nContent-Type: multipart/mixed; boundary=Z\n\ny\n", + 4_000, + 400_000, + b"\n", + ), + 4_001, + ), + ]; + for (name, raw, parts) in cases { + let start = Instant::now(); + let message = parse(&raw); + let elapsed = start.elapsed(); + assert_eq!(message.parts().len(), parts, "{name}"); + check_nesting(&message); + assert!( + elapsed < CHAIN_BUDGET, + "{name}: {} bytes took {elapsed:?}", + raw.len() + ); + } +} + +fn digest(count: usize) -> Vec<u8> { + let mut raw = b"Content-Type: multipart/digest; boundary=d\r\n\r\n".to_vec(); + for index in 0..count { + raw.extend_from_slice( + format!("--d\r\n\r\nSubject: {index}\r\n\r\nbody {index}\r\n").as_bytes(), + ); + } + raw.extend_from_slice(b"--d--\r\n"); + raw +} + +fn limited(raw: &[u8], parts: usize) -> Message<'_> { + MessageParser::new() + .max_parts(parts) + .parse(raw) + .expect("the input parses") +} + +fn flagged(message: &Message<'_>, flag: PartFlags) -> Vec<u32> { + message + .parts() + .filter(|part| part.flags().contains(flag)) + .map(|part| part.id()) + .collect() +} + +#[test] +fn part_limit_flags() { + let raw = digest(5); + let message = limited(&raw, 2); + check_nesting(&message); + assert!(message.root_part().flags().is_empty()); + let cut = message.part(1).expect("cut container"); + assert!(matches!(cut.kind(), PartKind::Text)); + assert_eq!(flags(cut), ["limit_reached"]); + assert_eq!(cut.offset_end() as usize, raw.len()); + + let message = limited(&raw, 3); + check_nesting(&message); + assert_eq!(flags(message.root_part()), ["limit_reached"]); + let nested_root = message.part(2).expect("nested root"); + assert!(nested_root.flags().is_empty()); + assert_eq!( + nested_root.offset_end(), + message.part(1).expect("container").offset_end() + ); + + let message = limited(&raw, 4); + check_nesting(&message); + assert_eq!(flagged(&message, PartFlags::LIMIT_REACHED), [3]); + assert!(message.root_part().flags().is_empty()); + + let mut mixed = b"Content-Type: multipart/mixed; boundary=d\r\n\r\n".to_vec(); + for index in 0..5 { + mixed.extend_from_slice(format!("--d\r\n\r\nbody {index}\r\n").as_bytes()); + } + mixed.extend_from_slice(b"--d--\r\n"); + let message = limited(&mixed, 3); + check_nesting(&message); + assert_eq!(flagged(&message, PartFlags::LIMIT_REACHED), [2]); + let last = message.part(2).expect("last"); + assert_eq!(last.offset_end() as usize, mixed.len()); + assert!(message.root_part().flags().is_empty()); + + let encoded = b"Content-Type: multipart/mixed; boundary=d\r\n\r\n--d\r\nContent-Type: message/rfc822\r\nContent-Transfer-Encoding: base64\r\n\r\nU3ViamVjdDogeA0KDQpib2R5DQo=\r\n--d\r\n\r\ntail\r\n--d--\r\n"; + let message = limited(encoded, 2); + check_nesting(&message); + let container = message.part(1).expect("container"); + assert!(matches!(container.kind(), PartKind::Binary)); + assert_eq!(flags(container), ["limit_reached"]); + assert!(message.root_part().flags().is_empty()); + let message = limited(encoded, 3); + check_nesting(&message); + assert_eq!(flagged(&message, PartFlags::LIMIT_REACHED), [0]); +} + +#[test] +fn part_limit_flags_on_fixtures() { + for file in fixtures() { + let Some(full) = MessageParser::new().parse(&file) else { + continue; + }; + let total = full.parts().len(); + for max in 1..total.min(12) { + let message = limited(&file, max); + check_nesting(&message); + assert_eq!(message.parts().len(), max); + assert_eq!(flagged(&message, PartFlags::LIMIT_REACHED).len(), 1); + for flag in [PartFlags::UNTERMINATED, PartFlags::NO_BLANK_LINE] { + let expected = flagged(&full, flag); + assert!( + flagged(&message, flag) + .iter() + .all(|id| expected.contains(id)), + "max_parts({max}) adds {flag:?}" + ); + } + } + } +} + +#[test] +fn source_of_every_message_is_constant_time() { + let inner = b"Subject: x\r\n\r\nbody\r\n"; + let encoded = "U3ViamVjdDogeA0KDQpib2R5DQo="; + assert_eq!(inner.len(), 20); + let mut raw = b"Content-Type: multipart/digest; boundary=d\r\n\r\n".to_vec(); + let count = 30_000; + for _ in 0..count { + raw.extend_from_slice( + b"--d\r\nContent-Type: message/rfc822\r\nContent-Transfer-Encoding: base64\r\n\r\n", + ); + raw.extend_from_slice(encoded.as_bytes()); + raw.extend_from_slice(b"\r\n"); + } + raw.extend_from_slice(b"--d--\r\n"); + let parser = MessageParser::new().max_parts(3 * count); + let start = Instant::now(); + let message = parser.parse(&raw).expect("the digest parses"); + let parsing = start.elapsed(); + assert_eq!(message.messages().len(), count + 1); + let start = Instant::now(); + let decoded = message + .messages() + .filter(|nested| { + nested + .container() + .is_some_and(|container| nested.source() == Source::Decoded(container.id())) + }) + .count(); + let walk = start.elapsed(); + assert_eq!(decoded, count); + assert!( + walk < parsing, + "source() on {count} messages took {walk:?}, the parse {parsing:?}" + ); +} + +#[test] +fn default_message_has_a_root_part() { + let message = Message::default(); + assert_eq!(message.raw(), b""); + assert_eq!(message.messages().len(), 1); + assert_eq!(message.parts().len(), 1); + let root = message.root_part(); + assert_eq!(root.id(), 0); + assert_eq!( + message.parts().next().map(|part| part.id()), + Some(root.id()) + ); + assert!(matches!(root.kind(), PartKind::Text)); + assert_eq!(root.text().as_deref(), Some("")); + assert!(root.headers().is_empty()); + assert!(root.parent().is_none()); + assert_eq!(message.text_body().len(), 0); + assert_eq!(message.attachments().len(), 0); + assert!(message.subject().is_none()); + assert_eq!(message.root().parts().count(), 1); + assert_eq!(message.root().source(), Source::Raw); +} + +#[test] +fn buffers_can_be_bounded() { + let parser = MessageParser::new(); + let mut large = b"Content-Type: multipart/mixed; boundary=b\n\n".to_vec(); + for index in 0..2_000 { + large.extend_from_slice(format!("--b\nX-Index: {index}\n\npart {index}\n").as_bytes()); + } + large.extend_from_slice(b"--b--\n"); + let mut buffers = MessageBuffers::new(); + let message = parser.parse_with(&large, &mut buffers).expect("parses"); + assert_eq!(message.parts().len(), 2_001); + buffers = message.into_buffers(); + buffers.shrink_to(usize::MAX); + buffers.shrink_to(0); + let message = parser + .parse_with(b"Subject: small\n\nbody\n", &mut buffers) + .expect("parses after shrinking"); + assert_eq!(message.subject(), Some("small")); +} diff --git a/tests/structure.rs b/tests/structure.rs new file mode 100644 index 0000000..2ae96d5 --- /dev/null +++ b/tests/structure.rs @@ -0,0 +1,203 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +mod support; + +use mail_parser::{MessageParser, MessagePart, MessageRef, PartKind, PartRole, Source}; +use serde_json::{Map, Value, json}; +use std::fs; +use support::{snapshot_inputs, snapshot_messages}; + +const MESSAGE_FIELDS: [&str; 8] = [ + "id", + "root", + "container", + "source", + "text_body", + "html_body", + "attachments", + "has_attachments", +]; +const PART_FIELDS: [&str; 12] = [ + "id", + "message", + "parent", + "kind", + "children", + "nested", + "flags", + "roles", + "role", + "offset_header", + "offset_body", + "offset_end", +]; +const HEADER_FIELDS: [&str; 4] = ["name", "offset_field", "offset_start", "offset_end"]; + +fn ids<'m>(parts: impl Iterator<Item = MessagePart<'m>>) -> Vec<u32> { + parts.map(|part| part.id()).collect() +} + +fn message_json(message: MessageRef<'_>) -> Value { + json!({ + "id": message.id(), + "root": message.root_part().id(), + "container": message.container().map(|part| part.id()), + "source": match message.source() { + Source::Raw => json!("raw"), + Source::Decoded(part) => json!({ "decoded": part }), + }, + "text_body": ids(message.text_body()), + "html_body": ids(message.html_body()), + "attachments": ids(message.attachments()), + "has_attachments": message.has_attachments(), + }) +} + +fn kind_name(kind: PartKind<'_>) -> &'static str { + match kind { + PartKind::Text => "text", + PartKind::Html => "html", + PartKind::Binary => "binary", + PartKind::InlineBinary => "inline_binary", + PartKind::Multipart => "multipart", + PartKind::Message(_) => "message", + } +} + +fn role_name(role: PartRole) -> &'static str { + match role { + PartRole::Container => "container", + PartRole::TextBody => "text_body", + PartRole::HtmlBody => "html_body", + PartRole::CopiedBody => "copied_body", + PartRole::MediaBody => "media_body", + PartRole::Attachment => "attachment", + PartRole::Dropped => "dropped", + } +} + +fn part_json(part: MessagePart<'_>) -> Value { + let roles = [ + (part.in_text_body(), "text_body"), + (part.in_html_body(), "html_body"), + (part.is_attachment(), "attachment"), + (part.is_inline(), "inline"), + ]; + let mut fields = json!({ + "id": part.id(), + "message": part.message().id(), + "parent": part.parent().map(|parent| parent.id()), + "kind": kind_name(part.kind()), + "flags": part.flags().names().collect::<Vec<_>>(), + "roles": roles + .iter() + .filter(|(set, _)| *set) + .map(|(_, name)| *name) + .collect::<Vec<_>>(), + "role": role_name(part.role()), + "offset_header": part.offset_header(), + "offset_body": part.offset_body(), + "offset_end": part.offset_end(), + "headers": part + .headers() + .iter() + .map(|header| { + json!({ + "name": header.raw_name(), + "offset_field": header.offset_field(), + "offset_start": header.offset_start(), + "offset_end": header.offset_end(), + }) + }) + .collect::<Vec<_>>(), + }); + let extra = match part.kind() { + PartKind::Multipart => Some(("children", json!(ids(part.children())))), + PartKind::Message(nested) => Some(("nested", json!(nested.id()))), + _ => None, + }; + if let (Some((name, value)), Some(object)) = (extra, fields.as_object_mut()) { + object.insert(name.to_string(), value); + } + fields +} + +fn project(value: &Value, names: &[&str]) -> Value { + Value::Object( + names + .iter() + .filter_map(|name| Some((name.to_string(), value.get(*name)?.clone()))) + .collect::<Map<_, _>>(), + ) +} + +fn expected_part(part: &Value) -> Value { + let mut fields = project(part, &PART_FIELDS); + let headers: Vec<Value> = part + .get("headers") + .and_then(Value::as_array) + .map(|headers| { + headers + .iter() + .map(|header| project(header, &HEADER_FIELDS)) + .collect() + }) + .unwrap_or_default(); + if let Some(object) = fields.as_object_mut() { + object.insert("headers".to_string(), Value::Array(headers)); + } + fields +} + +#[test] +fn structure_matches_the_snapshots() { + let parser = MessageParser::new(); + let mut checked = 0; + for path in snapshot_messages() { + let raw = fs::read(&path).expect("the message is readable"); + for (input, extension) in snapshot_inputs(&raw) { + let snapshot: Value = serde_json::from_slice( + &fs::read(path.with_extension(extension)).expect("the snapshot exists"), + ) + .expect("the snapshot is JSON"); + check( + &parser, + &input, + &snapshot, + &format!("{} ({extension})", path.display()), + ); + checked += 1; + } + } + assert!(checked > 300, "{checked}"); +} + +fn check(parser: &MessageParser, input: &[u8], snapshot: &Value, label: &str) { + let Some(message) = parser.parse(input) else { + assert!(snapshot.is_null(), "{label}"); + return; + }; + let expected_messages: Vec<Value> = snapshot + .get("messages") + .and_then(Value::as_array) + .map(|messages| { + messages + .iter() + .map(|message| project(message, &MESSAGE_FIELDS)) + .collect() + }) + .unwrap_or_default(); + let messages: Vec<Value> = message.messages().map(message_json).collect(); + assert_eq!(messages, expected_messages, "{label}"); + let expected_parts: Vec<Value> = snapshot + .get("parts") + .and_then(Value::as_array) + .map(|parts| parts.iter().map(expected_part).collect()) + .unwrap_or_default(); + let parts: Vec<Value> = message.parts().map(part_json).collect(); + assert_eq!(parts, expected_parts, "{label}"); +} diff --git a/tests/support/mod.rs b/tests/support/mod.rs new file mode 100644 index 0000000..17210f1 --- /dev/null +++ b/tests/support/mod.rs @@ -0,0 +1,85 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +#![allow(dead_code)] + +use mail_parser::{MessagePart, MessageRef}; +use std::{fs, path::PathBuf}; + +const SNAPSHOT_SUITES: [&str; 5] = ["rfc", "legacy", "thirdparty", "malformed", "regressions"]; + +pub fn resource(path: &str) -> Vec<u8> { + fs::read( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("resources/eml") + .join(path), + ) + .expect("fixture exists") +} + +pub fn fixture(name: &str) -> Vec<u8> { + resource(&format!("issues/{name}")) +} + +pub fn regression(name: &str) -> Vec<u8> { + resource(&format!("regressions/{name}.eml")) +} + +pub fn line_endings(raw: &[u8]) -> [(Vec<u8>, &'static str); 2] { + let lf: Vec<u8> = raw.iter().copied().filter(|&byte| byte != b'\r').collect(); + let mut crlf = Vec::with_capacity(lf.len() * 2); + for &byte in &lf { + if byte == b'\n' { + crlf.push(b'\r'); + } + crlf.push(byte); + } + [(lf, "\n"), (crlf, "\r\n")] +} + +pub fn ids<'m>(parts: impl Iterator<Item = MessagePart<'m>>) -> Vec<u32> { + parts.map(|part| part.id()).collect() +} + +pub fn lists(message: MessageRef<'_>) -> [Vec<u32>; 3] { + [ + ids(message.text_body()), + ids(message.html_body()), + ids(message.attachments()), + ] +} + +pub fn snapshot_messages() -> Vec<PathBuf> { + let mut found = Vec::new(); + for suite in SNAPSHOT_SUITES { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("resources/eml") + .join(suite); + let mut paths: Vec<PathBuf> = fs::read_dir(&dir) + .expect("the suite directory exists") + .map(|entry| entry.expect("the directory is readable").path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "eml")) + .collect(); + assert!(!paths.is_empty(), "no message in {}", dir.display()); + paths.sort_unstable(); + found.extend(paths); + } + found +} + +pub fn snapshot_inputs(raw: &[u8]) -> [(Vec<u8>, &'static str); 2] { + let lf = raw.iter().copied().filter(|&byte| byte != b'\r').collect(); + let mut crlf = Vec::with_capacity(raw.len() + raw.len() / 16); + let mut last = 0; + for &byte in raw { + if byte == b'\n' && last != b'\r' { + crlf.push(b'\r'); + } + crlf.push(byte); + last = byte; + } + [(lf, "json"), (crlf, "crlf.json")] +} diff --git a/tests/text_prefix.rs b/tests/text_prefix.rs new file mode 100644 index 0000000..377daa1 --- /dev/null +++ b/tests/text_prefix.rs @@ -0,0 +1,252 @@ +/* + * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art> + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + */ + +use mail_parser::{Message, MessageParser, PartKind, preview_html, preview_text}; +use std::{ + fs, + path::{Path, PathBuf}, +}; + +const LENGTHS: [usize; 16] = [ + 0, 1, 2, 3, 7, 10, 31, 50, 100, 255, 256, 257, 1000, 4096, 10_000, 1_000_000, +]; + +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 line_endings(raw: &[u8]) -> [Vec<u8>; 2] { + let lf: Vec<u8> = raw.iter().copied().filter(|&byte| byte != b'\r').collect(); + let mut crlf = Vec::with_capacity(lf.len() * 2); + for &byte in &lf { + if byte == b'\n' { + crlf.push(b'\r'); + } + crlf.push(byte); + } + [lf, crlf] +} + +fn first_chars(text: &str, count: usize) -> &str { + text.char_indices() + .nth(count) + .map_or(text, |(end, _)| text.get(..end).unwrap_or(text)) +} + +fn check_message(message: &Message<'_>, name: &str) -> usize { + let mut checked = 0; + for part in message.parts() { + let Some(text) = part.text() else { + assert!(part.text_prefix(10).is_none(), "{name}"); + continue; + }; + for count in LENGTHS { + let prefix = part.text_prefix(count).expect("a text part"); + assert_eq!( + prefix, + first_chars(&text, count), + "{name} part {} count {count}", + part.id() + ); + } + checked += 1; + } + for message in message.messages() { + for max_len in LENGTHS { + let expected = if message.text_body().len() > 0 { + let part = message.text_body().next().expect("text body"); + 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, + } + } else if message.html_body().len() > 0 { + let part = message.html_body().next().expect("html body"); + match part.kind() { + PartKind::Html => part.text().map(|html| preview_html(&html, max_len)), + PartKind::Text => part + .text() + .map(|text| preview_html(&mail_parser::text_to_html(&text), max_len)), + _ => None, + } + } else { + None + }; + assert_eq!( + message.body_preview(max_len).as_deref(), + expected.as_deref(), + "{name} preview {max_len}" + ); + } + } + checked +} + +#[test] +fn text_prefix_matches_text_on_every_fixture() { + let mut files = Vec::new(); + eml_files( + &PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/eml"), + &mut files, + ); + files.sort(); + assert!(files.len() > 100, "{}", files.len()); + let mut checked = 0; + for path in &files { + let raw = fs::read(path).expect("fixture"); + for raw in line_endings(&raw) { + let message = MessageParser::new().parse(&raw).expect("parses"); + checked += check_message(&message, &path.display().to_string()); + } + } + assert!(checked > 200, "{checked}"); +} + +fn wrap(encoded: &str, width: usize) -> String { + encoded + .as_bytes() + .chunks(width) + .map(|line| String::from_utf8_lossy(line).into_owned()) + .collect::<Vec<_>>() + .join("\r\n") +} + +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in bytes.chunks(3) { + let mut word = [0u8; 3]; + word.iter_mut() + .zip(chunk) + .for_each(|(slot, &byte)| *slot = byte); + let bits = u32::from_be_bytes([0, word[0], word[1], word[2]]); + for index in 0..4 { + if index <= chunk.len() { + out.push(char::from( + ALPHABET[((bits >> (18 - 6 * index)) & 0x3f) as usize], + )); + } else { + out.push('='); + } + } + } + out +} + +fn quoted_printable(bytes: &[u8]) -> String { + let mut out = String::new(); + let mut line = 0; + for &byte in bytes { + let piece = match byte { + b'\n' => { + out.push_str("\r\n"); + line = 0; + continue; + } + b'=' | 0x80..=0xff | 0..=0x1f => format!("={byte:02X}"), + _ => char::from(byte).to_string(), + }; + if line + piece.len() > 72 { + out.push_str("=\r\n"); + line = 0; + } + line += piece.len(); + out.push_str(&piece); + } + out +} + +#[test] +fn text_prefix_on_encoded_bodies() { + let text = "Caf\u{e9} na\u{ef}ve \u{65e5}\u{672c}\u{8a9e} \u{1f600} line\nsecond line with trailing spaces \n" + .repeat(120); + let mut messages = Vec::new(); + for (charset, bytes) in [ + ("utf-8", text.as_bytes().to_vec()), + ( + "utf-16", + [0xff, 0xfe] + .into_iter() + .chain(text.encode_utf16().flat_map(u16::to_le_bytes)) + .collect(), + ), + ( + "utf-16be", + text.encode_utf16().flat_map(u16::to_be_bytes).collect(), + ), + ( + "iso-8859-1", + text.chars() + .filter_map(|ch| u8::try_from(u32::from(ch)).ok()) + .collect(), + ), + ] { + for (encoding, body) in [ + ("base64", wrap(&base64(&bytes), 76)), + ("quoted-printable", quoted_printable(&bytes)), + ("8bit", String::from_utf8_lossy(&bytes).into_owned()), + ] { + if encoding == "8bit" && charset != "utf-8" { + continue; + } + for subtype in ["plain", "html"] { + messages.push(format!( + "Subject: prefix\r\nContent-Type: text/{subtype}; charset={charset}\r\nContent-Transfer-Encoding: {encoding}\r\n\r\n{body}" + )); + } + } + } + #[cfg(feature = "full_encoding")] + for label in [ + "shift_jis", + "euc-jp", + "iso-2022-jp", + "gb18030", + "big5", + "euc-kr", + ] { + let encoding = encoding_rs::Encoding::for_label(label.as_bytes()).expect("label"); + let cjk = "\u{65e5}\u{672c}\u{8a9e}\u{306e}\u{30c6}\u{30ad}\u{30b9}\u{30c8} text \u{c548}\u{b155} \u{4e2d}\u{6587}\n" + .repeat(200); + let (bytes, _, _) = encoding.encode(&cjk); + for (encoding, body) in [ + ("base64", wrap(&base64(&bytes), 76)), + ("quoted-printable", quoted_printable(&bytes)), + ] { + messages.push(format!( + "Subject: prefix\r\nContent-Type: text/plain; charset={label}\r\nContent-Transfer-Encoding: {encoding}\r\n\r\n{body}" + )); + } + } + messages.push( + "Content-Type: text/plain; charset=utf-7\r\n\r\nHi Mom -+Jjo--! +ZeVnLIqe- tail +AKM" + .repeat(40), + ); + messages.push( + "Content-Type: text/plain\r\nContent-Transfer-Encoding: base64\r\n\r\nSGVs bG8g?garbage=V29y bGQ=" + .to_string(), + ); + messages.push( + "Content-Type: text/plain\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nsoft=\r\nbreak =C3=\r\n=A9 end \r\n=41=\r\n" + .to_string(), + ); + for message in &messages { + let parsed = MessageParser::new() + .parse(message.as_bytes()) + .expect("parses"); + let name = message.lines().nth(1).unwrap_or_default(); + assert!(check_message(&parsed, name) > 0, "{name}"); + } +}