email_encoding/headers/rfc2231.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
//! [RFC 2231] encoder.
//!
//! [RFC 2231]: https://datatracker.ietf.org/doc/html/rfc2231
use std::fmt::{self, Write};
use super::{hex_encoding, utils, EmailWriter, MAX_LINE_LEN};
/// Encode a string via RFC 2231.
///
/// # Examples
///
/// ```rust
/// # use email_encoding::headers::writer::EmailWriter;
/// # fn main() -> std::fmt::Result {
/// {
/// let input = "invoice.pdf";
///
/// let mut output = String::new();
/// {
/// let mut writer = EmailWriter::new(&mut output, 0, 0, false, 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, 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, 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()?;
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 line
w.write_char(';')?;
w.new_line()?;
} else {
// End of value
break;
}
i += 1;
}
}
} else {
// Needs encoding (Parameter Value Character Set and Language Information)
w.new_line()?;
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 line
w.write_char(';')?;
w.new_line()?;
} else {
// End of value
break;
}
i += 1;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn empty() {
let mut s = "Content-Disposition: attachment;".to_string();
let line_len = 1;
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true, true);
encode("filename", "", &mut w).unwrap();
}
assert_eq!(s, concat!("Content-Disposition: attachment; filename=\"\""));
}
#[test]
fn parameter() {
let mut s = "Content-Disposition: attachment;".to_string();
let line_len = 1;
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true, true);
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_string();
let line_len = 1;
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true, true);
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_string();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true, true);
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_string();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true, true);
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_string();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true, true);
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_string();
let line_len = s.len();
{
let mut w = EmailWriter::new(&mut s, line_len, 0, true, true);
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_string();
let line_len = base_header.len();
for start_offset in &["", "x", "xx", "xxx"] {
let mut filename = start_offset.to_string();
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, false, 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);
}
}
}
}