chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

View File

@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"fcc991274c3c1f0554e03b8e614abf69a8d8820c02e32bf8d6a64e0f8c231a78",".github/workflows/ci.yml":"20018e472e55d9cb67dac381f93c9d2e80c808b998e5454b99fa2f26170326f7","Cargo.lock":"6ff13df501b807ac68d0e384e4fc0dcf4bb50594d7790b83b22d75dc36270a80","Cargo.toml":"b3a1ae6d77b64116fef0ec2c6e998d60cd85952054237111ed9396ad02935e29","Cargo.toml.orig":"d9569ae28a61362a86063a642bf650c44f6f0c50fbc5298cfa87d24d57668637","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"c5d18f2569938b6d61594f799702b7a29b5c33fba64dc5669875a50d5523aee6","README.md":"00a8b9ff2f7bcb4ca12cbdaa9065f68ad399b0c12f198051bf6b007c12d6ca61","src/body/base64.rs":"2e655d80dad1dfd9149159be0624f6e371249f8e700e5d870ed21f989a30ba69","src/body/chooser.rs":"4e781767476c70c2993aafeaf92b818b011d16b01169500eab68ae51459ea1af","src/body/mod.rs":"992aa372ebf6270accd000a5520cf39252eecbd1d9e3de0eeda424bdbb6206f5","src/headers/hex.rs":"b9f2cfed004b4ba14137271c941722a6dc6fd8720cb550a8ef3d4822c039cf93","src/headers/hex_encoding.rs":"b0ecd08d981bb55ddc72a171b49b828aa27fb24a88597c7f998f01fdec47663c","src/headers/mod.rs":"348026b6469263aae231c646986b1981db0795057b60e08cde0d6e90f8ce05f5","src/headers/quoted_string.rs":"f9e154d9f016bada4d2af99f75d3496e7b2f4b378668b8e6c52e362a8aefa7ed","src/headers/rfc2047.rs":"916ba03de54268ebdc82473bd54c15006b31fa4c4681970eb06c6ab3d8ea92d9","src/headers/rfc2231.rs":"c7ac13c31ad75401d628422224a178919b8f4a4ad7111b1cbd1617fcc1bfd719","src/headers/utils.rs":"84bf54b3f9b42cdfdd91ba1f79134b25fbad5d3f5ab13c75052d67266ba84aad","src/headers/writer.rs":"bf0759351246b854a6a2dcdef2740553479174964cc451803a0c1551b2c11ed8","src/lib.rs":"5193d006daf0ae787f890072c7fed0174ad833b9632b812c945a21efa967c9d5"},"package":"9298e6504d9b9e780ed3f7dfd43a61be8cd0e09eb07f7706a945b0072b6670b6"}

View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "0e0d592847f56ea4d12e80fd6a2a0adba232099c"
},
"path_in_vcs": ""
}

View File

@@ -0,0 +1,90 @@
name: CI
on: [push, pull_request]
jobs:
fmt:
name: rustfmt / stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- name: Rust rustfmt
run: cargo fmt --all -- --check
clippy:
name: clippy / stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- name: Run clippy
run: cargo clippy -- -D warnings
test:
name: test / ${{ matrix.name }}
runs-on: ubuntu-latest
strategy:
matrix:
include:
- name: stable
rust: stable
- name: beta
rust: beta
- name: nightly
rust: nightly
- name: 1.63.0
rust: 1.63.0
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.rust }}
- name: Run tests
run: cargo test
- name: Run no_std tests
run: cargo test --no-default-features
coverage:
name: coverage / stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- name: Install cargo-tarpaulin
run: |
LINK="https://github.com/xd009642/tarpaulin/releases/download/0.31.2/cargo-tarpaulin-x86_64-unknown-linux-gnu.tar.gz"
curl -L --output tarpaulin.tar.gz "$LINK"
tar -xzvf tarpaulin.tar.gz
chmod +x cargo-tarpaulin
- name: Run cargo-tarpaulin
run: ./cargo-tarpaulin tarpaulin --out Xml
- name: Upload to codecov.io
uses: codecov/codecov-action@v5
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
- name: Archive code coverage results
uses: actions/upload-artifact@v4
with:
name: code-coverage-report
path: cobertura.xml

46
vendor/email-encoding/Cargo.lock generated vendored Normal file
View File

@@ -0,0 +1,46 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "diff"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
[[package]]
name = "email-encoding"
version = "0.4.1"
dependencies = [
"base64",
"memchr",
"pretty_assertions",
]
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "pretty_assertions"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d"
dependencies = [
"diff",
"yansi",
]
[[package]]
name = "yansi"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"

58
vendor/email-encoding/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,58 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.63"
name = "email-encoding"
version = "0.4.1"
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Low level email encoding RFCs implementations"
readme = "README.md"
keywords = [
"email",
"rfc2047",
"rfc2231",
]
categories = [
"email",
"encoding",
"no-std",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/lettre/email-encoding"
[features]
default = ["std"]
std = [
"base64/std",
"memchr/std",
]
[lib]
name = "email_encoding"
path = "src/lib.rs"
[dependencies.base64]
version = "0.22"
default-features = false
[dependencies.memchr]
version = "2.1"
default-features = false
[dev-dependencies.pretty_assertions]
version = "1"

201
vendor/email-encoding/LICENSE-APACHE vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

21
vendor/email-encoding/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-2024 Paolo Barbolini <paolo@paolo565.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

20
vendor/email-encoding/README.md vendored Normal file
View File

@@ -0,0 +1,20 @@
# email-encoding
[![crates.io](https://img.shields.io/crates/v/email-encoding.svg)](https://crates.io/crates/email-encoding)
[![Documentation](https://docs.rs/email-encoding/badge.svg)](https://docs.rs/email-encoding)
[![dependency status](https://deps.rs/crate/email-encoding/0.3.1/status.svg)](https://deps.rs/crate/email-encoding/0.3.1)
[![Rustc Version 1.63.0+](https://img.shields.io/badge/rustc-1.63.0+-lightgray.svg)](https://blog.rust-lang.org/2022/08/11/Rust-1.63.0.html)
[![CI](https://github.com/lettre/email-encoding/actions/workflows/ci.yml/badge.svg)](https://github.com/lettre/email-encoding/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/lettre/email-encoding/branch/main/graph/badge.svg)](https://codecov.io/gh/lettre/email-encoding)
Low-level `#[no_std]` crate implementing various RFCs for encoding emails.
Used internally by [lettre].
Implemented RFCs:
* [RFC 2047]
* [RFC 2231]
[lettre]: https://crates.io/crates/lettre
[RFC 2047]: https://datatracker.ietf.org/doc/html/rfc2047
[RFC 2231]: https://datatracker.ietf.org/doc/html/rfc2231

199
vendor/email-encoding/src/body/base64.rs vendored Normal file
View File

@@ -0,0 +1,199 @@
//! Base64 email body encoder.
use core::{
fmt::{self, Write},
str,
};
use ::base64::Engine;
const LINE_LEN: usize = 76;
const CRLF: &str = "\r\n";
/// Base64 encode the provided bytes.
///
/// Splits the provided `b` into 57 bytes chunks and
/// base64 encodes them, writing the resulting 76 characters
/// CRLF sequence into `w`.
///
/// The last line may be less than 76 characters in length
/// and will not end in CRLF.
///
/// # Examples
///
/// ```rust
/// # fn main() -> core::fmt::Result {
/// let input = "Hello!
/// You've got mail!
/// This one is base64 encoded.
///
/// Enjoy your bytes 📬📬📬";
///
/// let mut output = String::new();
/// email_encoding::body::base64::encode(input.as_bytes(), &mut output)?;
/// assert_eq!(
/// output,
/// concat!(
/// "SGVsbG8hCllvdSd2ZSBnb3QgbWFpbCEKVGhpcyBvbmUgaXMgYmFzZTY0IGVuY29kZWQuCgpFbmpv\r\n",
/// "eSB5b3VyIGJ5dGVzIPCfk6zwn5Os8J+TrA=="
/// )
/// );
/// # Ok(())
/// # }
/// ```
pub fn encode(b: &[u8], w: &mut dyn Write) -> fmt::Result {
let mut buf = [0; LINE_LEN];
let mut chunks = b.chunks(LINE_LEN / 4 * 3).peekable();
while let Some(chunk) = chunks.next() {
let len = ::base64::engine::general_purpose::STANDARD
.encode_slice(chunk, &mut buf)
.expect("base64 output `buf` is not big enough");
w.write_str(str::from_utf8(&buf[..len]).expect("base64 produced an invalid encode"))?;
if chunks.peek().is_some() {
w.write_str(CRLF)?;
}
}
Ok(())
}
/// Predict how many bytes [`encode`] is going to write given a `input_len` input length.
///
/// # Panics
///
/// Panics if any of the internal calculations overflow.
///
/// # Examples
///
/// ```rust
/// # use email_encoding::body::base64::encoded_len;
/// assert_eq!(encoded_len(0), 0);
/// assert_eq!(encoded_len(16), 24);
/// assert_eq!(encoded_len(300), 410);
/// ```
pub const fn encoded_len(input_len: usize) -> usize {
// FIXME: use `Option::expect` with MSRV >= 1.83
macro_rules! checked {
($val:expr) => {
match $val {
Some(val) => val,
None => panic!("overflow"),
}
};
}
let mut base64_len = checked!((input_len / 3).checked_mul(4));
if input_len % 3 != 0 {
base64_len = checked!(base64_len.checked_add(4));
}
let mut crlf_len = base64_len / LINE_LEN * CRLF.len();
if crlf_len >= CRLF.len() && base64_len % LINE_LEN == 0 {
crlf_len -= CRLF.len();
}
checked!(base64_len.checked_add(crlf_len))
}
#[cfg(test)]
mod tests {
use alloc::string::String;
use pretty_assertions::assert_eq;
use super::{encode, encoded_len};
#[test]
fn empty() {
let input = b"";
let mut output = String::new();
encode(input, &mut output).unwrap();
assert_eq!(output, "");
assert_eq!(output.len(), encoded_len(input.len()));
}
#[test]
fn oneline() {
let input = b"012";
let mut output = String::new();
encode(input, &mut output).unwrap();
assert_eq!(output, "MDEy");
assert_eq!(output.len(), encoded_len(input.len()));
}
#[test]
fn oneline_padded() {
let input = b"0123";
let mut output = String::new();
encode(input, &mut output).unwrap();
assert_eq!(output, "MDEyMw==");
assert_eq!(output.len(), encoded_len(input.len()));
}
#[test]
fn multiline() {
let input =
b"012345678998765432100123456789987654321001234567899876543210012345678998765432100";
let mut output = String::new();
encode(input, &mut output).unwrap();
assert_eq!(
output,
concat!(
"MDEyMzQ1Njc4OTk4NzY1NDMyMTAwMTIzNDU2Nzg5OTg3NjU0MzIxMDAxMjM0NTY3ODk5ODc2NTQz\r\n",
"MjEwMDEyMzQ1Njc4OTk4NzY1NDMyMTAw"
)
);
assert_eq!(output.len(), encoded_len(input.len()));
}
#[test]
fn multiline_padded() {
let input =
b"01234567899876543210012345678998765432100123456789987654321001234567899876543210";
let mut output = String::new();
encode(input, &mut output).unwrap();
assert_eq!(
output,
concat!(
"MDEyMzQ1Njc4OTk4NzY1NDMyMTAwMTIzNDU2Nzg5OTg3NjU0MzIxMDAxMjM0NTY3ODk5ODc2NTQz\r\n",
"MjEwMDEyMzQ1Njc4OTk4NzY1NDMyMTA="
)
);
assert_eq!(output.len(), encoded_len(input.len()));
}
#[test]
fn multiline_exact() {
let input =
b"012345678998765432100123456789987654321001234567899876543210012345678998765432100123456789987654321001234567899876543210012345678998765432100123456789987654321001234567899";
let mut output = String::new();
encode(input, &mut output).unwrap();
assert_eq!(
output,
concat!(
"MDEyMzQ1Njc4OTk4NzY1NDMyMTAwMTIzNDU2Nzg5OTg3NjU0MzIxMDAxMjM0NTY3ODk5ODc2NTQz\r\n",
"MjEwMDEyMzQ1Njc4OTk4NzY1NDMyMTAwMTIzNDU2Nzg5OTg3NjU0MzIxMDAxMjM0NTY3ODk5ODc2\r\n",
"NTQzMjEwMDEyMzQ1Njc4OTk4NzY1NDMyMTAwMTIzNDU2Nzg5OTg3NjU0MzIxMDAxMjM0NTY3ODk5"
)
);
assert_eq!(output.len(), encoded_len(input.len()));
}
#[test]
#[should_panic(expected = "overflow")]
fn overflow() {
encoded_len(usize::MAX);
}
}

View File

@@ -0,0 +1,259 @@
use core::mem;
use super::{Encoding, StrOrBytes};
enum InputKind {
Ascii,
Utf8,
Binary,
}
impl StrOrBytes<'_> {
fn kind(&self) -> InputKind {
if self.is_ascii() {
InputKind::Ascii
} else {
match self {
Self::Str(_) => InputKind::Utf8,
Self::Bytes(_) => InputKind::Binary,
}
}
}
}
impl Encoding {
/// Choose the most efficient `Encoding` for `input`
///
/// Look into `input` and decide what encoding format could best
/// be used to represent it.
///
/// If the SMTP server supports the `SMTPUTF8` extension
/// `supports_utf8` _may_ me set to `true`, otherwise `false`
/// is the safest option.
///
/// Possible return values based on `supports_utf8`
///
/// | `Encoding` | `false` | `true` |
/// | ------------------ | ------- | ------ |
/// | `7bit` | ✅ | ✅ |
/// | `8bit` | ❌ | ✅ |
/// | `quoted-printable` | ✅ | ✅ |
/// | `base64` | ✅ | ✅ |
///
/// # Examples
///
/// ```rust
/// # use email_encoding::body::Encoding;
/// // Ascii
/// {
/// let input = "Hello, World!";
/// assert_eq!(Encoding::choose(input, false), Encoding::SevenBit);
/// assert_eq!(Encoding::choose(input, true), Encoding::SevenBit);
/// }
///
/// // Mostly ascii + utf-8
/// {
/// let input = "Hello, World! 📬";
/// assert_eq!(Encoding::choose(input, false), Encoding::QuotedPrintable);
/// assert_eq!(Encoding::choose(input, true), Encoding::EightBit);
/// }
///
/// // Mostly utf-8
/// {
/// let input = "Hello! 📬📬📬📬📬📬📬📬📬📬";
/// assert_eq!(Encoding::choose(input, false), Encoding::Base64);
/// assert_eq!(Encoding::choose(input, true), Encoding::EightBit);
/// }
///
/// // Non utf-8 bytes
/// {
/// let input = &[255, 35, 123, 190];
/// assert_eq!(Encoding::choose(input, false), Encoding::Base64);
/// assert_eq!(Encoding::choose(input, true), Encoding::Base64);
/// }
/// ```
pub fn choose<'a>(input: impl Into<StrOrBytes<'a>>, supports_utf8: bool) -> Self {
let input = input.into();
Self::choose_impl(input, supports_utf8)
}
fn choose_impl(input: StrOrBytes<'_>, supports_utf8: bool) -> Self {
let line_too_long = line_too_long(&input);
match (input.kind(), line_too_long, supports_utf8) {
(InputKind::Ascii, false, _) => {
// Input is ascii and fits the maximum line length
Self::SevenBit
}
(InputKind::Ascii, true, _) => {
// Input is ascii but doesn't fix the maximum line length
quoted_printable_or_base64(&input)
}
(InputKind::Utf8, false, true) => {
// Input is utf-8, line fits, the server supports it
Self::EightBit
}
(InputKind::Utf8, true, true) => {
// Input is utf-8, line doesn't fit, the server supports it
quoted_printable_or_base64(&input)
}
(InputKind::Utf8, _, false) => {
// Input is utf-8, the server doesn't support it
quoted_printable_or_base64(&input)
}
(InputKind::Binary, _, _) => {
// Input is binary
Self::Base64
}
}
}
}
fn line_too_long(b: &[u8]) -> bool {
let mut last = 0;
memchr::memchr_iter(b'\n', b).any(|i| {
let last_ = mem::replace(&mut last, i);
(i - last_) >= 76
}) || (b.len() - last) >= 76
}
fn quoted_printable_or_base64(b: &[u8]) -> Encoding {
if quoted_printable_efficient(b) {
Encoding::QuotedPrintable
} else {
Encoding::Base64
}
}
fn quoted_printable_efficient(b: &[u8]) -> bool {
let requiring_escaping = b
.iter()
.filter(|&b| !matches!(b, b'\t' | b' '..=b'~'))
.count();
requiring_escaping <= (b.len() / 3) // 33.33% or less
}
#[cfg(test)]
mod tests {
use super::{line_too_long, Encoding};
#[test]
fn ascii_short_str() {
let input = "0123";
assert_eq!(Encoding::choose(input, false), Encoding::SevenBit);
}
#[test]
fn ascii_long_str() {
let input = concat!(
"0123\n",
"01234567899876543210012345678998765432100123456789987654321001234567899876543210\n",
"4567"
);
assert_eq!(Encoding::choose(input, false), Encoding::QuotedPrintable);
}
#[test]
fn ascii_short_binary() {
let input = b"0123";
assert_eq!(Encoding::choose(input, false), Encoding::SevenBit);
}
#[test]
fn ascii_long_binary() {
let input = concat!(
"0123\n",
"01234567899876543210012345678998765432100123456789987654321001234567899876543210\n",
"4567"
)
.as_bytes();
assert_eq!(Encoding::choose(input, false), Encoding::QuotedPrintable);
}
#[test]
fn utf8_short_str_supported() {
let input = "0123 📬";
assert_eq!(Encoding::choose(input, true), Encoding::EightBit);
}
#[test]
fn utf8_short_str_unsupported_efficient() {
let input = "01234567899876543210 📬";
assert_eq!(Encoding::choose(input, false), Encoding::QuotedPrintable);
}
#[test]
fn utf8_short_str_unsupported_inefficient() {
let input = "0123 📬";
assert_eq!(Encoding::choose(input, false), Encoding::Base64);
}
#[test]
fn utf8_long_str_efficient() {
let input =
"01234567899876543210012345678998765432100123456789987654321001234567899876543210";
assert_eq!(Encoding::choose(input, true), Encoding::QuotedPrintable);
}
#[test]
fn utf8_long_str_inefficient() {
let input = "0123 📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬📬";
assert_eq!(Encoding::choose(input, true), Encoding::Base64);
}
#[test]
fn binary() {
let input = &[255, 234, b'A', b'C', 210];
assert_eq!(Encoding::choose(input, false), Encoding::Base64);
}
#[test]
fn not_too_long_oneline() {
let input = b"0123";
assert!(!line_too_long(input));
}
#[test]
fn not_too_long_multiline() {
let input = concat!(
"0123\n",
"4567\n",
"00000000000000000000000000000000000000000\n",
"89"
)
.as_bytes();
assert!(!line_too_long(input));
}
#[test]
fn too_long_oneline() {
let input =
b"01234567899876543210012345678998765432100123456789987654321001234567899876543210";
assert!(line_too_long(input));
}
#[test]
fn too_long_multiline() {
let input = concat!(
"0123\n",
"01234567899876543210012345678998765432100123456789987654321001234567899876543210\n",
"4567"
)
.as_bytes();
assert!(line_too_long(input));
}
}

57
vendor/email-encoding/src/body/mod.rs vendored Normal file
View File

@@ -0,0 +1,57 @@
//! Email body encoding algorithms.
use core::ops::Deref;
pub mod base64;
mod chooser;
/// A possible email `Content-Transfer-Encoding`
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Encoding {
/// 7bit (US-ASCII)
SevenBit,
/// 8bit (UTF-8)
EightBit,
/// [Quoted Printable](https://docs.rs/quoted_printable/0.4.5/quoted_printable/fn.encode_to_str.html)
QuotedPrintable,
/// [Base64](self::base64::encode)
Base64,
}
/// A borrowed `str` or `[u8]`
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum StrOrBytes<'a> {
/// `str` variant
Str(&'a str),
/// `[u8]` variant
Bytes(&'a [u8]),
}
impl<'a> From<&'a str> for StrOrBytes<'a> {
fn from(s: &'a str) -> Self {
Self::Str(s)
}
}
impl<'a> From<&'a [u8]> for StrOrBytes<'a> {
fn from(s: &'a [u8]) -> Self {
Self::Bytes(s)
}
}
impl<'a, const N: usize> From<&'a [u8; N]> for StrOrBytes<'a> {
fn from(s: &'a [u8; N]) -> Self {
Self::Bytes(s)
}
}
impl Deref for StrOrBytes<'_> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
match self {
Self::Str(s) => s.as_bytes(),
Self::Bytes(b) => b,
}
}
}

View File

@@ -0,0 +1,9 @@
const HEX_CHARS: &[u8; 16] = b"0123456789ABCDEF";
pub(super) const fn encode_byte(byte: u8) -> [u8; 2] {
[lower_nibble_to_hex(byte >> 4), lower_nibble_to_hex(byte)]
}
const fn lower_nibble_to_hex(half_byte: u8) -> u8 {
HEX_CHARS[(half_byte & 0x0F) as usize]
}

View File

@@ -0,0 +1,42 @@
use core::fmt::{self, Write};
use super::{hex, utils, writer::EmailWriter};
pub(super) fn percent_encode_char(w: &mut EmailWriter<'_>, to_append: char) -> fmt::Result {
encode_char(w, '%', to_append)
}
fn encode_char(w: &mut EmailWriter<'_>, prefix: char, to_append: char) -> fmt::Result {
if utils::char_is_ascii_alphanumeric_plus(to_append) {
w.write_char(to_append)?;
} else {
let mut dst = [0; 4];
let written = to_append.encode_utf8(&mut dst).len();
encode_byte(w, prefix, dst[0])?;
// Manually unrolled loop over `dst`
if written >= 2 {
encode_byte(w, prefix, dst[1])?;
if written >= 3 {
encode_byte(w, prefix, dst[2])?;
if written >= 4 {
encode_byte(w, prefix, dst[3])?;
}
}
}
}
Ok(())
}
fn encode_byte(w: &mut EmailWriter<'_>, prefix: char, to_append: u8) -> fmt::Result {
let chars = hex::encode_byte(to_append);
w.write_char(prefix)?;
w.write_char(char::from(chars[0]))?;
w.write_char(char::from(chars[1]))?;
Ok(())
}

View File

@@ -0,0 +1,11 @@
//! Email header encoding algorithms.
mod hex;
mod hex_encoding;
pub mod quoted_string;
pub mod rfc2047;
pub mod rfc2231;
mod utils;
pub mod writer;
pub(super) const MAX_LINE_LEN: usize = 76;

View File

@@ -0,0 +1,225 @@
//! Quoted String encoder.
use core::fmt::{self, Write};
use super::{rfc2047, utils, writer::EmailWriter};
/// Encode a string that may need to be quoted.
///
/// # Examples
///
/// ```rust
/// # use email_encoding::headers::writer::EmailWriter;
/// # fn main() -> core::fmt::Result {
/// {
/// let input = "John";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::quoted_string::encode(input, &mut writer)?;
/// }
/// assert_eq!(output, "John");
/// }
///
/// {
/// let input = "John Smith";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::quoted_string::encode(input, &mut writer)?;
/// }
/// assert_eq!(output, "\"John Smith\"");
/// }
///
/// {
/// let input = "Rogue \" User";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::quoted_string::encode(input, &mut writer)?;
/// }
/// assert_eq!(output, "\"Rogue \\\" User\"");
/// }
///
/// {
/// let input = "Adrián";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::quoted_string::encode(input, &mut writer)?;
/// }
/// assert_eq!(output, "=?utf-8?b?QWRyacOhbg==?=");
/// }
/// # Ok(())
/// # }
/// ```
pub fn encode(value: &str, w: &mut EmailWriter<'_>) -> fmt::Result {
#[derive(Debug)]
enum Strategy {
Plain,
Quoted,
QuotedEscaped,
Rfc2047,
}
let mut strategy = Strategy::Plain;
let mut bytes = value.as_bytes();
// Plain -> Quoted
while !bytes.is_empty() {
let byte = bytes[0];
if !byte.is_ascii_alphanumeric() && !matches!(byte, b'-' | b'_' | b'.') {
strategy = Strategy::Quoted;
break;
}
bytes = &bytes[1..];
}
// Quoted -> QuotedEscaped
while !bytes.is_empty() {
let byte = bytes[0];
if !byte.is_ascii_alphanumeric() && !matches!(byte, b' ' | b'-' | b'_' | b'.') {
strategy = Strategy::QuotedEscaped;
break;
}
bytes = &bytes[1..];
}
// QuotedEscaped -> Rfc2047
while !bytes.is_empty() {
let byte = bytes[0];
if !byte.is_ascii_alphanumeric()
&& !matches!(byte, b'\\' | b'"' | b' ' | b'-' | b'_' | b'.')
{
strategy = Strategy::Rfc2047;
break;
}
bytes = &bytes[1..];
}
match strategy {
Strategy::Plain => {
w.write_str(value)?;
}
Strategy::Quoted => {
w.write_char('"')?;
w.folding().write_str(value)?;
w.write_char('"')?;
}
Strategy::QuotedEscaped => {
w.write_char('"')?;
utils::write_escaped(value, &mut w.folding())?;
w.write_char('"')?;
}
Strategy::Rfc2047 => {
rfc2047::encode(value, w)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use alloc::string::String;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn plain() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("1234567890abcd", &mut w).unwrap();
}
assert_eq!(s, "1234567890abcd");
}
#[test]
fn quoted() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("1234567890 abcd", &mut w).unwrap();
}
assert_eq!(s, "\"1234567890 abcd\"");
}
#[test]
fn quoted_long() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("1234567890 abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", &mut w).unwrap();
}
assert_eq!(s, concat!(
"\"1234567890\r\n",
" abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\""
));
}
#[test]
fn quoted_escaped() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("12345\\67890 ab\"cd", &mut w).unwrap();
}
assert_eq!(s, "\"12345\\\\67890 ab\\\"cd\"");
}
// TODO: get it working for the quoted escaped strategy
// #[test]
// fn quoted_escaped_long() {
// let mut s = String::new();
// let line_len = s.len();
//
// {
// let mut w = EmailWriter::new(&mut s, line_len, 0, false, false);
// encode("12345\\67890 ab\"cdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd", &mut w).unwrap();
// }
//
// assert_eq!(s, concat!(
// "\"12345\\\\67890\r\n",
// " ab\\\"cdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd\""
// ));
// }
#[test]
fn rfc2047() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("12345\\67890 perché ab\"cd", &mut w).unwrap();
}
assert_eq!(s, "=?utf-8?b?MTIzNDVcNjc4OTAgcGVyY2jDqSBhYiJjZA==?=");
}
}

View File

@@ -0,0 +1,170 @@
//! [RFC 2047] encoder.
//!
//! [RFC 2047]: https://datatracker.ietf.org/doc/html/rfc2047
use core::fmt::{self, Write};
use super::{utils, writer::EmailWriter, MAX_LINE_LEN};
const ENCODING_START_PREFIX: &str = "=?utf-8?b?";
const ENCODING_END_SUFFIX: &str = "?=";
/// Encode a string via RFC 2047.
///
/// # Examples
///
/// ```rust
/// # use email_encoding::headers::writer::EmailWriter;
/// # fn main() -> core::fmt::Result {
/// let input = "Adrián";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::rfc2047::encode(input, &mut writer)?;
/// }
/// assert_eq!(output, "=?utf-8?b?QWRyacOhbg==?=");
/// # Ok(())
/// # }
/// ```
pub fn encode(mut s: &str, w: &mut EmailWriter<'_>) -> fmt::Result {
let mut wrote = false;
while !s.is_empty() {
let remaining_line_len = MAX_LINE_LEN.saturating_sub(
ENCODING_START_PREFIX.len() + ENCODING_END_SUFFIX.len() + w.line_len() + "\r\n".len(),
);
let unencoded_remaining_line_len = remaining_line_len / 4 * 3;
let mut word =
utils::truncate_to_char_boundary(s, unencoded_remaining_line_len.min(s.len()));
if word.is_empty() {
if wrote || w.has_spaces() {
// No space remaining on this line, go to a new one
w.new_line()?;
if !w.has_spaces() {
// The last write before this call to `encode` most
// likely wasn't rfc2047 so we must write a "soft"
// space to let the decoder know we're still within the
// same header
w.space();
}
continue;
}
// No space remaining, but going to a new line will require us
// to introduce a new space, which will mess up things even more.
word = &s[..s.chars().next().expect("`s` is empty").len_utf8()];
}
// Write the prefix
w.write_str(ENCODING_START_PREFIX)?;
// Encode `word`
let encoder = base64::display::Base64Display::new(
word.as_bytes(),
&base64::engine::general_purpose::STANDARD,
);
write!(w, "{}", encoder)?;
// Write the suffix
w.write_str(ENCODING_END_SUFFIX)?;
s = &s[word.len()..];
wrote = true;
}
Ok(())
}
#[cfg(test)]
mod tests {
use alloc::string::String;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn empty() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("", &mut w).unwrap();
}
assert_eq!(s, "");
}
#[test]
fn basic() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("abcd", &mut w).unwrap();
}
assert_eq!(s, "=?utf-8?b?YWJjZA==?=");
}
#[test]
fn basic_nopad() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode("abcdef", &mut w).unwrap();
}
assert_eq!(s, "=?utf-8?b?YWJjZGVm?=");
}
#[test]
fn long() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode(&"lettre".repeat(20), &mut w).unwrap();
}
assert_eq!(
s,
concat!(
"=?utf-8?b?bGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0?=\r\n",
" =?utf-8?b?dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJl?=\r\n",
" =?utf-8?b?bGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJlbGV0dHJl?="
)
);
}
#[test]
fn long_encoded() {
let mut s = String::new();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, false);
encode(&"hétérogénéité".repeat(16), &mut w).unwrap();
}
assert_eq!(
s,
concat!(
"=?utf-8?b?aMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9n?=\r\n",
" =?utf-8?b?w6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOp?=\r\n",
" =?utf-8?b?aMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9n?=\r\n",
" =?utf-8?b?w6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOp?=\r\n",
" =?utf-8?b?aMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9n?=\r\n",
" =?utf-8?b?w6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOpaMOpdMOpcm9nw6luw6lpdMOp?=\r\n",
" =?utf-8?b?aMOpdMOpcm9nw6luw6lpdMOp?=",
)
);
}
}

View File

@@ -0,0 +1,385 @@
//! [RFC 2231] encoder.
//!
//! [RFC 2231]: https://datatracker.ietf.org/doc/html/rfc2231
use core::fmt::{self, Write};
use super::{hex_encoding, utils, writer::EmailWriter, MAX_LINE_LEN};
/// Encode a string via RFC 2231.
///
/// # Examples
///
/// ```rust
/// # use email_encoding::headers::writer::EmailWriter;
/// # fn main() -> core::fmt::Result {
/// {
/// let input = "invoice.pdf";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::rfc2231::encode("filename", input, &mut writer)?;
/// }
/// assert_eq!(output, "filename=\"invoice.pdf\"");
/// }
///
/// {
/// let input = "invoice_2022_06_04_letshaveaverylongfilenamewhynotemailcanhandleit.pdf";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::rfc2231::encode("filename", input, &mut writer)?;
/// }
/// assert_eq!(
/// output,
/// concat!(
/// "\r\n",
/// " filename*0=\"invoice_2022_06_04_letshaveaverylongfilenamewhynotemailcanha\";\r\n",
/// " filename*1=\"ndleit.pdf\""
/// )
/// );
/// }
///
/// {
/// let input = "faktúra.pdf";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false);
/// email_encoding::headers::rfc2231::encode("filename", input, &mut writer)?;
/// }
/// assert_eq!(
/// output,
/// concat!(
/// "\r\n",
/// " filename*0*=utf-8''fakt%C3%BAra.pdf"
/// )
/// );
/// }
/// # Ok(())
/// # }
/// ```
pub fn encode(key: &str, mut value: &str, w: &mut EmailWriter<'_>) -> fmt::Result {
assert!(
utils::str_is_ascii_alphanumeric(key),
"`key` must only be composed of ascii alphanumeric chars"
);
assert!(
key.len() + "*12*=utf-8'';".len() < MAX_LINE_LEN,
"`key` must not be too long to cause the encoder to overflow the max line length"
);
if utils::str_is_ascii_printable(value) {
// Can be written normally (Parameter Value Continuations)
let quoted_plain_combined_len = key.len() + "=\"".len() + value.len() + "\"\r\n".len();
if w.line_len() + quoted_plain_combined_len <= MAX_LINE_LEN {
// Fits line
w.write_str(key)?;
w.write_char('=')?;
w.write_char('"')?;
utils::write_escaped(value, w)?;
w.write_char('"')?;
} else {
// Doesn't fit line
w.new_line()?;
w.forget_spaces();
let mut i = 0_usize;
loop {
write!(w, " {}*{}=\"", key, i)?;
let remaining_len = MAX_LINE_LEN - w.line_len() - "\"\r\n".len();
let value_ =
utils::truncate_to_char_boundary(value, remaining_len.min(value.len()));
value = &value[value_.len()..];
utils::write_escaped(value_, w)?;
w.write_char('"')?;
if value.is_empty() {
// End of value
break;
}
// End of line
w.write_char(';')?;
w.new_line()?;
i += 1;
}
}
} else {
// Needs encoding (Parameter Value Character Set and Language Information)
w.new_line()?;
w.forget_spaces();
let mut i = 0_usize;
loop {
write!(w, " {}*{}*=", key, i)?;
if i == 0 {
w.write_str("utf-8''")?;
}
let mut chars = value.chars();
while w.line_len() < MAX_LINE_LEN - "=xx=xx=xx=xx;\r\n".len() {
match chars.next() {
Some(c) => {
hex_encoding::percent_encode_char(w, c)?;
value = chars.as_str();
}
None => {
break;
}
}
}
if value.is_empty() {
// End of value
break;
}
// End of line
w.write_char(';')?;
w.new_line()?;
i += 1;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use alloc::{borrow::ToOwned, string::String};
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn empty() {
let mut s = "Content-Disposition: attachment;".to_owned();
let line_len = 1;
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
encode("filename", "", &mut w).unwrap();
}
assert_eq!(s, concat!("Content-Disposition: attachment; filename=\"\""));
}
#[test]
fn parameter() {
let mut s = "Content-Disposition: attachment;".to_owned();
let line_len = 1;
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
encode("filename", "duck.txt", &mut w).unwrap();
}
assert_eq!(
s,
concat!("Content-Disposition: attachment; filename=\"duck.txt\"")
);
}
#[test]
fn parameter_to_escape() {
let mut s = "Content-Disposition: attachment;".to_owned();
let line_len = 1;
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
encode("filename", "du\"ck\\.txt", &mut w).unwrap();
}
assert_eq!(
s,
concat!("Content-Disposition: attachment; filename=\"du\\\"ck\\\\.txt\"")
);
}
#[test]
fn parameter_long() {
let mut s = "Content-Disposition: attachment;".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
encode(
"filename",
"a-fairly-long-filename-just-to-see-what-happens-when-we-encode-it-will-the-client-be-able-to-handle-it.txt",
&mut w,
)
.unwrap();
}
assert_eq!(
s,
concat!(
"Content-Disposition: attachment;\r\n",
" filename*0=\"a-fairly-long-filename-just-to-see-what-happens-when-we-enco\";\r\n",
" filename*1=\"de-it-will-the-client-be-able-to-handle-it.txt\""
)
);
}
#[test]
fn parameter_special() {
let mut s = "Content-Disposition: attachment;".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
encode("filename", "caffè.txt", &mut w).unwrap();
}
assert_eq!(
s,
concat!(
"Content-Disposition: attachment;\r\n",
" filename*0*=utf-8''caff%C3%A8.txt"
)
);
}
#[test]
fn parameter_special_long() {
let mut s = "Content-Disposition: attachment;".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
encode(
"filename",
"testing-to-see-what-happens-when-📕📕📕📕📕📕📕📕📕📕📕-are-placed-on-the-boundary.txt",
&mut w,
)
.unwrap();
}
assert_eq!(
s,
concat!(
"Content-Disposition: attachment;\r\n",
" filename*0*=utf-8''testing-to-see-what-happens-when-%F0%9F%93%95;\r\n",
" filename*1*=%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95;\r\n",
" filename*2*=%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95;\r\n",
" filename*3*=%F0%9F%93%95%F0%9F%93%95-are-placed-on-the-bound;\r\n",
" filename*4*=ary.txt"
)
);
}
#[test]
fn parameter_special_long_part2() {
let mut s = "Content-Disposition: attachment;".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
encode(
"filename",
"testing-to-see-what-happens-when-books-are-placed-in-the-second-part-📕📕📕📕📕📕📕📕📕📕📕.txt",
&mut w,
)
.unwrap();
}
assert_eq!(
s,
concat!(
"Content-Disposition: attachment;\r\n",
" filename*0*=utf-8''testing-to-see-what-happens-when-books-ar;\r\n",
" filename*1*=e-placed-in-the-second-part-%F0%9F%93%95%F0%9F%93%95;\r\n",
" filename*2*=%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95;\r\n",
" filename*3*=%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95%F0%9F%93%95;\r\n",
" filename*4*=%F0%9F%93%95.txt"
)
);
}
#[test]
fn parameter_dont_split_on_hex_boundary() {
let base_header = "Content-Disposition: attachment;".to_owned();
let line_len = base_header.len();
for start_offset in &["", "x", "xx", "xxx"] {
let mut filename = (*start_offset).to_owned();
for i in 1..256 {
// 'Ü' results in two hex chars %C3%9C
filename.push('Ü');
let mut output = base_header.clone();
{
let mut w = EmailWriter::new(&mut output, line_len, 0, true);
encode("filename", &filename, &mut w).unwrap();
}
// look for all hex encoded chars
let output_len = output.len();
let mut found_hex_count = 0;
for (percent_sign_idx, _) in output.match_indices('%') {
assert!(percent_sign_idx + 3 <= output_len);
// verify we get the expected hex sequence for an 'Ü'
let must_be_hex = &output[percent_sign_idx + 1..percent_sign_idx + 3];
assert!(
must_be_hex == "C3" || must_be_hex == "9C",
"unexpected hex char: {}",
must_be_hex
);
found_hex_count += 1;
}
// verify the number of hex encoded chars adds up
let number_of_chars_in_hex = 2;
assert_eq!(found_hex_count, i * number_of_chars_in_hex);
// verify max line length
let mut last_newline_pos = 0;
for (newline_idx, _) in output.match_indices("\r\n") {
let line_length = newline_idx - last_newline_pos;
assert!(
line_length < MAX_LINE_LEN,
"expected line length exceeded: {} > {}",
line_length,
MAX_LINE_LEN
);
last_newline_pos = newline_idx;
}
// ensure there was at least one newline
assert_ne!(0, last_newline_pos);
}
}
}
#[test]
#[should_panic(expected = "`key` must only be composed of ascii alphanumeric chars")]
fn non_ascii_key() {
let mut s = String::new();
let mut w = EmailWriter::new(&mut s, 0, 0, true);
let _ = encode("📬", "", &mut w);
}
}

View File

@@ -0,0 +1,84 @@
use core::fmt::{self, Write};
pub(super) fn str_is_ascii_alphanumeric(s: &str) -> bool {
s.bytes().all(|c| c.is_ascii_alphanumeric())
}
pub(super) const fn char_is_ascii_alphanumeric_plus(c: char) -> bool {
c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')
}
pub(super) fn str_is_ascii_printable(s: &str) -> bool {
s.bytes().all(char_is_ascii_printable)
}
const fn char_is_ascii_printable(c: u8) -> bool {
matches!(c, b' '..=b'~')
}
pub(super) fn write_escaped(s: &str, w: &mut impl Write) -> fmt::Result {
debug_assert!(s.is_ascii());
for b in s.bytes() {
match b {
b'\\' => {
w.write_str("\\\\")?;
}
b'"' => {
w.write_str("\\\"")?;
}
b => {
w.write_char(char::from(b))?;
}
}
}
Ok(())
}
pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> &str {
assert!(max <= s.len());
while !s.is_char_boundary(max) {
max -= 1;
}
&s[..max]
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn truncate_ascii() {
assert_eq!(truncate_to_char_boundary("12345678", 4), "1234");
}
#[test]
fn truncate0_ascii() {
assert_eq!(truncate_to_char_boundary("12345678", 0), "");
}
#[test]
fn truncate_utf8() {
assert_eq!(truncate_to_char_boundary("📬📬📬📬📬📬", 8), "📬📬");
}
#[test]
fn truncate0_utf8() {
assert_eq!(truncate_to_char_boundary("📬📬📬📬📬📬", 0), "");
}
#[test]
fn truncate_boundary_utf8() {
assert_eq!(truncate_to_char_boundary("📬📬📬📬📬📬", 9), "📬📬");
}
#[test]
#[should_panic]
fn truncate_out_of_bounds() {
let _ = truncate_to_char_boundary("12345678", 16);
}
}

View File

@@ -0,0 +1,363 @@
//! Utilities for writing email headers to a [`Write`]r.
//!
//! [`Write`]: core::fmt::Write
use core::fmt::{self, Write};
use super::MAX_LINE_LEN;
/// Wrapper around [`Write`] that remembers the length of the
/// last line written to it.
///
/// [`Write`]: core::fmt::Write
pub struct EmailWriter<'a> {
writer: &'a mut dyn Write,
line_len: usize,
spaces: usize,
can_go_to_new_line_now: bool,
}
impl<'a> EmailWriter<'a> {
/// Construct a new `EmailWriter`.
///
/// * `line_len` is the length of the last line in `writer`.
/// * `spaces` the number of spaces that must be written before
/// the next write.
/// * `can_go_to_new_line_now` is whether the current line can
/// be wrapped now or not.
pub fn new(
writer: &'a mut dyn Write,
line_len: usize,
spaces: usize,
can_go_to_new_line_now: bool,
) -> Self {
Self {
writer,
line_len,
spaces,
can_go_to_new_line_now,
}
}
/// Go to a new line and reset the `line_len` to `0`.
pub fn new_line(&mut self) -> fmt::Result {
self.writer.write_str("\r\n")?;
self.line_len = 0;
self.can_go_to_new_line_now = false;
Ok(())
}
/// Write a space which _might_ get wrapped to a new line on the next write.
pub fn space(&mut self) {
self.spaces += 1;
}
/// Forget all buffered spaces
pub(super) fn forget_spaces(&mut self) {
self.spaces = 0;
}
pub(super) fn has_spaces(&mut self) -> bool {
self.spaces >= 1
}
/// Get the length in bytes of the last line written to the inner writer.
pub fn line_len(&self) -> usize {
self.line_len
}
/// Get the length in bytes of the last line written to the inner writer
/// plus the spaces which might be written to in on the next write call.
pub fn projected_line_len(&self) -> usize {
self.line_len + self.spaces
}
/// Get a [`Write`]r which automatically line folds text written to it.
///
/// [`Write`]: core::fmt::Write
pub fn folding<'b>(&'b mut self) -> FoldingEmailWriter<'a, 'b> {
FoldingEmailWriter { writer: self }
}
fn write_spaces(&mut self) -> fmt::Result {
while self.spaces > 0 {
self.writer.write_char(' ')?;
self.line_len += 1;
self.spaces -= 1;
}
Ok(())
}
}
impl Write for EmailWriter<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.write_spaces()?;
let s_after = s.trim_end_matches(' ');
self.spaces += s.len() - s_after.len();
if !s_after.is_empty() {
self.writer.write_str(s_after)?;
self.line_len += s_after.len();
self.can_go_to_new_line_now = true;
}
Ok(())
}
fn write_char(&mut self, c: char) -> fmt::Result {
if c == ' ' {
self.spaces += 1;
} else {
self.write_spaces()?;
self.can_go_to_new_line_now = true;
self.writer.write_char(c)?;
self.line_len += c.len_utf8();
}
Ok(())
}
}
impl Drop for EmailWriter<'_> {
fn drop(&mut self) {
let _ = self.write_spaces();
}
}
/// Wrapper around [`Write`] that remembers the length of the
/// last line and automatically line folds text written to it.
///
/// [`Write`]: core::fmt::Write
pub struct FoldingEmailWriter<'a, 'b> {
writer: &'b mut EmailWriter<'a>,
}
impl Write for FoldingEmailWriter<'_, '_> {
fn write_str(&mut self, mut s: &str) -> fmt::Result {
while !s.is_empty() {
if s.starts_with(' ') {
self.writer.space();
s = &s[1..];
continue;
}
let (start, end) = s.find(' ').map_or((s, ""), |i| s.split_at(i));
if self.writer.can_go_to_new_line_now
&& self.writer.spaces >= 1
&& (self.writer.projected_line_len() + start.len()) > MAX_LINE_LEN
{
self.writer.new_line()?;
}
self.writer.write_str(start)?;
s = end;
}
Ok(())
}
fn write_char(&mut self, c: char) -> fmt::Result {
if c == ' ' {
self.writer.spaces += 1;
} else {
self.write_str(c.encode_utf8(&mut [0u8; 4]))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use alloc::borrow::ToOwned;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn wrap_immediate() {
let mut s =
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
for _ in 0..16 {
w.folding().write_str("0123456789").unwrap();
}
}
assert_eq!(
s,
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789",
);
}
#[test]
fn wrap_keeping_final_whitespace() {
let mut s = "Subject: AAAAAAAAAAAAAA".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 1, true);
w.folding().write_str("12345 ").unwrap();
w.new_line().unwrap();
w.folding().write_str("12345").unwrap();
}
assert_eq!(s, concat!("Subject: AAAAAAAAAAAAAA 12345\r\n", " 12345"));
}
#[test]
fn catch_space() {
let mut s = "Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 1, true);
w.folding().write_str("BBB ").unwrap();
w.folding().write_str("CCCCCCCCCCCCC").unwrap();
}
assert_eq!(
s,
concat!(
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBB\r\n",
" CCCCCCCCCCCCC"
)
);
}
#[test]
fn catch_spaces() {
let mut s = "Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 1, true);
w.folding().write_str("BBB ").unwrap();
w.folding().write_str("CCCCCCCCCCCCC").unwrap();
}
assert_eq!(
s,
concat!(
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBB\r\n",
" CCCCCCCCCCCCC"
)
);
}
#[test]
fn explicit_space() {
let mut s = "Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 1, true);
w.folding().write_str("BBB").unwrap();
w.space();
w.folding().write_str("CCCCCCCCCCCCC").unwrap();
}
assert_eq!(
s,
concat!(
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBB\r\n",
" CCCCCCCCCCCCC"
)
);
}
#[test]
fn explicit_spaces() {
let mut s = "Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 1, true);
w.folding().write_str("BBB").unwrap();
w.space();
w.write_char(' ').unwrap();
w.space();
w.folding().write_str("CCCCCCCCCCCCC").unwrap();
}
assert_eq!(
s,
concat!(
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBB\r\n",
" CCCCCCCCCCCCC"
)
);
}
#[test]
fn optional_breakpoint() {
let mut s = "Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
.to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.space();
w.folding().write_str("BBBBBBBBBB").unwrap();
w.space();
w.folding().write_str("CCCCCCCCCC").unwrap();
}
assert_eq!(
s,
concat!(
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n",
" BBBBBBBBBB CCCCCCCCCC",
)
);
}
#[test]
fn double_spaces_issue_949() {
let mut s = "Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.folding().write_str("BBBBBBBBBBBBB ").unwrap();
crate::headers::rfc2047::encode("sélection", &mut w).unwrap();
}
assert_eq!(
s,
concat!(
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBB\r\n",
" =?utf-8?b?c8OpbGVjdGlvbg==?=",
)
);
}
#[test]
fn double_spaces_issue_949_no_space() {
let mut s = "Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ".to_owned();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true);
w.folding().write_str("BBBBBBBBBBBBBBB").unwrap();
crate::headers::rfc2047::encode("sélection", &mut w).unwrap();
}
assert_eq!(
s,
concat!(
"Subject: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBB=?utf-8?b?cw==?=\r\n",
" =?utf-8?b?w6lsZWN0aW9u?=",
)
);
}
}

49
vendor/email-encoding/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,49 @@
//! Low-level crate implementing various RFCs for encoding emails.
//! Used internally by [lettre].
//!
//! [lettre]: https://crates.io/crates/lettre
#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
#![deny(
unreachable_pub,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unstable_features,
unused_import_braces,
rust_2018_idioms,
missing_docs,
rustdoc::broken_intra_doc_links,
clippy::string_add,
clippy::string_add_assign,
clippy::clone_on_ref_ptr,
clippy::verbose_file_reads,
clippy::unnecessary_self_imports,
clippy::string_to_string,
clippy::mem_forget,
clippy::cast_lossless,
clippy::inefficient_to_string,
clippy::inline_always,
clippy::linkedlist,
clippy::macro_use_imports,
clippy::manual_assert,
clippy::unnecessary_join,
clippy::wildcard_imports,
clippy::str_to_string,
clippy::empty_structs_with_brackets,
clippy::zero_sized_map_values,
clippy::manual_let_else,
clippy::semicolon_if_nothing_returned,
clippy::unnecessary_wraps,
clippy::doc_markdown,
clippy::explicit_iter_loop,
clippy::redundant_closure_for_method_calls,
// Rust 1.86: clippy::unnecessary_semicolon,
)]
#[cfg(test)]
extern crate alloc;
pub mod body;
pub mod headers;