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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
use crate::header::{HeaderParseResult, MessageConformance};
use crate::headermap::HeaderMap;
use crate::strings::IntoSharedString;
use crate::{
    has_lone_cr_or_lf, Header, MailParsingError, MessageID, MimeParameters, Result, SharedString,
};
use charset::Charset;
use std::str::FromStr;

/// Define our own because data_encoding::BASE64_MIME, despite its name,
/// is not RFC2045 compliant, and will not ignore spaces
const BASE64_RFC2045: data_encoding::Encoding = data_encoding_macro::new_encoding! {
    symbols: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
    padding: '=',
    ignore: " \r\n\t",
    wrap_width: 76,
    wrap_separator: "\r\n",
};

#[derive(Debug, Clone, PartialEq)]
pub struct MimePart<'a> {
    /// The bytes that comprise this part, from its beginning to its end
    bytes: SharedString<'a>,
    /// The parsed headers from the start of bytes
    headers: HeaderMap<'a>,
    /// The index into bytes of the first non-header byte.
    body_offset: usize,
    body_len: usize,
    conformance: MessageConformance,
    parts: Vec<Self>,
    /// For multipart, the content the precedes the first boundary
    intro: SharedString<'a>,
    /// For multipart, the content the follows the last boundary
    outro: SharedString<'a>,
}

struct Rfc2045Info {
    encoding: ContentTransferEncoding,
    charset: Charset,
    content_type: Option<MimeParameters>,
    is_text: bool,
    is_multipart: bool,
    attachment_options: Option<AttachmentOptions>,
}

impl Rfc2045Info {
    fn new(headers: &HeaderMap) -> Result<Self> {
        let content_transfer_encoding = headers.content_transfer_encoding()?;

        let encoding = match &content_transfer_encoding {
            Some(cte) => ContentTransferEncoding::from_str(&cte.value)?,
            None => ContentTransferEncoding::SevenBit,
        };

        let content_type = headers.content_type()?;
        let charset = if let Some(ct) = &content_type {
            ct.get("charset")
        } else {
            None
        };
        let charset = charset.unwrap_or_else(|| "us-ascii".to_string());

        let charset = Charset::for_label_no_replacement(charset.as_bytes())
            .ok_or_else(|| MailParsingError::BodyParse(format!("unsupported charset {charset}")))?;

        let (is_text, is_multipart) = if let Some(ct) = &content_type {
            (ct.is_text(), ct.is_multipart())
        } else {
            (true, false)
        };

        let content_disposition = headers.content_disposition()?;
        let attachment_options = match content_disposition {
            Some(cd) => {
                let inline = cd.value == "inline";
                let content_id = headers.content_id()?;
                let file_name = cd.get("filename");

                Some(AttachmentOptions {
                    file_name,
                    inline,
                    content_id: content_id.map(|cid| cid.0),
                })
            }
            None => None,
        };

        Ok(Self {
            encoding,
            charset,
            content_type,
            is_text,
            is_multipart,
            attachment_options,
        })
    }
}

impl<'a> MimePart<'a> {
    /// Parse some data into a tree of MimeParts
    pub fn parse<S>(bytes: S) -> Result<Self>
    where
        S: IntoSharedString<'a>,
    {
        let (bytes, base_conformance) = bytes.into_shared_string();
        Self::parse_impl(bytes, base_conformance, true)
    }

    fn parse_impl(
        bytes: SharedString<'a>,
        base_conformance: MessageConformance,
        is_top_level: bool,
    ) -> Result<Self> {
        let HeaderParseResult {
            headers,
            body_offset,
            overall_conformance: mut conformance,
        } = Header::parse_headers(bytes.clone())?;

        conformance = conformance | base_conformance;

        let body_len = bytes.len();

        if !bytes.is_ascii() {
            conformance.set(MessageConformance::NEEDS_TRANSFER_ENCODING, true);
        }
        {
            let mut prev = 0;
            for idx in memchr::memchr_iter(b'\n', bytes.as_bytes()) {
                if idx - prev > 78 {
                    conformance.set(MessageConformance::LINE_TOO_LONG, true);
                    break;
                }
                prev = idx;
            }
        }
        conformance.set(
            MessageConformance::NON_CANONICAL_LINE_ENDINGS,
            has_lone_cr_or_lf(bytes.as_bytes()),
        );

        if is_top_level {
            conformance.set(
                MessageConformance::MISSING_DATE_HEADER,
                match headers.date() {
                    Ok(Some(_)) => false,
                    _ => true,
                },
            );
            conformance.set(
                MessageConformance::MISSING_MESSAGE_ID_HEADER,
                match headers.message_id() {
                    Ok(Some(_)) => false,
                    _ => true,
                },
            );
            conformance.set(
                MessageConformance::MISSING_MIME_VERSION,
                match headers.mime_version() {
                    Ok(Some(v)) => v.as_str() != "1.0",
                    _ => true,
                },
            );
        }

        let mut part = Self {
            bytes,
            headers,
            body_offset,
            body_len,
            conformance,
            parts: vec![],
            intro: SharedString::Borrowed(""),
            outro: SharedString::Borrowed(""),
        };

        part.recursive_parse()?;

        Ok(part)
    }

    fn recursive_parse(&mut self) -> Result<()> {
        let info = Rfc2045Info::new(&self.headers)?;
        if let Some((boundary, true)) = info
            .content_type
            .as_ref()
            .and_then(|ct| ct.get("boundary").map(|b| (b, info.is_multipart)))
        {
            let boundary = format!("\n--{boundary}");
            let raw_body = self
                .bytes
                .slice(self.body_offset.saturating_sub(1)..self.bytes.len());

            let mut iter = memchr::memmem::find_iter(raw_body.as_bytes(), &boundary);
            if let Some(first_boundary_pos) = iter.next() {
                self.intro = raw_body.slice(0..first_boundary_pos);

                // When we create parts, we ignore the original body span in
                // favor of what we're parsing out here now
                self.body_len = 0;

                let mut boundary_end = first_boundary_pos + boundary.len();

                while let Some(part_start) =
                    memchr::memchr(b'\n', &raw_body.as_bytes()[boundary_end..])
                        .map(|p| p + boundary_end + 1)
                {
                    let part_end = iter
                        .next()
                        .map(|p| {
                            // P is the newline; we want to include it in the raw
                            // bytes for this part, so look beyond it
                            p + 1
                        })
                        .unwrap_or(raw_body.len());

                    let child = Self::parse_impl(
                        raw_body.slice(part_start..part_end),
                        MessageConformance::default(),
                        false,
                    )?;
                    self.conformance |= child.conformance;
                    self.parts.push(child);

                    boundary_end = part_end -
                        1 /* newline we adjusted for when assigning part_end */
                        + boundary.len();

                    if boundary_end + 2 > raw_body.len() {
                        break;
                    }
                    if &raw_body.as_bytes()[boundary_end..boundary_end + 2] == b"--" {
                        if let Some(after_boundary) =
                            memchr::memchr(b'\n', &raw_body.as_bytes()[boundary_end..])
                                .map(|p| p + boundary_end + 1)
                        {
                            self.outro = raw_body.slice(after_boundary..raw_body.len());
                        }
                        break;
                    }
                }
            }
        }

        Ok(())
    }

    pub fn conformance(&self) -> MessageConformance {
        self.conformance
    }

    /// Obtain a reference to the child parts
    pub fn child_parts(&self) -> &[Self] {
        &self.parts
    }

    /// Obtain a mutable reference to the child parts
    pub fn child_parts_mut(&mut self) -> &mut Vec<Self> {
        &mut self.parts
    }

    /// Obtains a reference to the headers
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// Obtain a mutable reference to the headers
    pub fn headers_mut<'b>(&'b mut self) -> &'b mut HeaderMap<'a> {
        &mut self.headers
    }

    /// Get the raw, transfer-encoded body
    pub fn raw_body(&self) -> SharedString {
        self.bytes
            .slice(self.body_offset..self.body_len.max(self.body_offset))
    }

    /// Decode transfer decoding and return the body
    pub fn body(&self) -> Result<DecodedBody> {
        let info = Rfc2045Info::new(&self.headers)?;

        let bytes = match info.encoding {
            ContentTransferEncoding::Base64 => {
                let data = self.raw_body();
                let bytes = data.as_bytes();
                BASE64_RFC2045.decode(bytes).map_err(|err| {
                    let b = bytes[err.position] as char;
                    let region = &bytes[err.position.saturating_sub(8)..err.position + 8];
                    let region = String::from_utf8_lossy(region);
                    MailParsingError::BodyParse(format!(
                        "base64 decode: {err:#} b={b:?} in {region}"
                    ))
                })?
            }
            ContentTransferEncoding::QuotedPrintable => quoted_printable::decode(
                self.raw_body().as_bytes(),
                quoted_printable::ParseMode::Robust,
            )
            .map_err(|err| {
                MailParsingError::BodyParse(format!("quoted printable decode: {err:#}"))
            })?,
            ContentTransferEncoding::SevenBit
            | ContentTransferEncoding::EightBit
            | ContentTransferEncoding::Binary
                if info.is_text =>
            {
                return Ok(DecodedBody::Text(self.raw_body()));
            }
            ContentTransferEncoding::SevenBit
            | ContentTransferEncoding::EightBit
            | ContentTransferEncoding::Binary => {
                return Ok(DecodedBody::Binary(self.raw_body().as_bytes().to_vec()))
            }
        };

        let (decoded, _malformed) = info.charset.decode_without_bom_handling(&bytes);

        if info.is_text {
            Ok(DecodedBody::Text(decoded.to_string().into()))
        } else {
            Ok(DecodedBody::Binary(decoded.as_bytes().to_vec()))
        }
    }

    /// Re-constitute the message.
    /// Each element will be parsed out, and the parsed form used
    /// to build a new message.
    /// This has the side effect of "fixing" non-conforming elements,
    /// but may come at the cost of "losing" the non-sensical or otherwise
    /// out of spec elements in the rebuilt message
    pub fn rebuild(&self) -> Result<Self> {
        let info = Rfc2045Info::new(&self.headers)?;

        let mut children = vec![];
        for part in &self.parts {
            children.push(part.rebuild()?);
        }

        let mut rebuilt = if children.is_empty() {
            let body = self.body()?;
            match body {
                DecodedBody::Text(text) => {
                    let ct = info
                        .content_type
                        .as_ref()
                        .map(|ct| ct.value.as_str())
                        .unwrap_or("text/plain");
                    Self::new_text(ct, text.as_str())
                }
                DecodedBody::Binary(data) => {
                    let ct = info
                        .content_type
                        .as_ref()
                        .map(|ct| ct.value.as_str())
                        .unwrap_or("application/octet-stream");
                    Self::new_binary(ct, &data, info.attachment_options.as_ref())
                }
            }
        } else {
            let ct = info.content_type.ok_or_else(|| {
                MailParsingError::BodyParse(format!(
                    "multipart message has no content-type information!?"
                ))
            })?;
            Self::new_multipart(&ct.value, children, ct.get("boundary").as_deref())
        };

        for hdr in self.headers.iter() {
            // Skip rfc2045 associated headers; we already rebuilt
            // those above
            let name = hdr.get_name();
            if name.eq_ignore_ascii_case("Content-Type")
                || name.eq_ignore_ascii_case("Content-Transfer-Encoding")
                || name.eq_ignore_ascii_case("Content-Disposition")
                || name.eq_ignore_ascii_case("Content-ID")
            {
                continue;
            }

            if let Ok(hdr) = hdr.rebuild() {
                rebuilt.headers_mut().push(hdr);
            }
        }

        Ok(rebuilt)
    }

    /// Write the message content to the provided output stream
    pub fn write_message<W: std::io::Write>(&self, out: &mut W) -> Result<()> {
        let line_ending = if self
            .conformance
            .contains(MessageConformance::NON_CANONICAL_LINE_ENDINGS)
        {
            "\n"
        } else {
            "\r\n"
        };

        for hdr in self.headers.iter() {
            hdr.write_header(out)
                .map_err(|_| MailParsingError::WriteMessageIOError)?;
        }
        out.write_all(line_ending.as_bytes())
            .map_err(|_| MailParsingError::WriteMessageIOError)?;

        if self.parts.is_empty() {
            out.write_all(self.raw_body().as_bytes())
                .map_err(|_| MailParsingError::WriteMessageIOError)?;
        } else {
            let info = Rfc2045Info::new(&self.headers)?;
            let ct = info.content_type.ok_or_else(|| {
                MailParsingError::WriteMessageWtf(
                    "expected to have Content-Type when there are child parts",
                )
            })?;
            let boundary = ct.get("boundary").ok_or_else(|| {
                MailParsingError::WriteMessageWtf("expected Content-Type to have a boundary")
            })?;
            out.write_all(&self.intro.as_bytes())
                .map_err(|_| MailParsingError::WriteMessageIOError)?;
            for p in &self.parts {
                write!(out, "--{boundary}{line_ending}")
                    .map_err(|_| MailParsingError::WriteMessageIOError)?;
                p.write_message(out)?;
            }
            write!(out, "--{boundary}--{line_ending}")
                .map_err(|_| MailParsingError::WriteMessageIOError)?;
            out.write_all(&self.outro.as_bytes())
                .map_err(|_| MailParsingError::WriteMessageIOError)?;
        }
        Ok(())
    }

    /// Convenience method wrapping write_message that returns
    /// the formatted message as a standalone string
    pub fn to_message_string(&self) -> String {
        let mut out = vec![];
        self.write_message(&mut out).unwrap();
        String::from_utf8_lossy(&out).to_string()
    }

    pub fn replace_text_body(&mut self, content_type: &str, content: &str) {
        let mut new_part = Self::new_text(content_type, content);
        self.bytes = new_part.bytes;
        self.body_offset = new_part.body_offset;
        self.body_len = new_part.body_len;
        // Remove any rfc2047 headers that might reflect how the content
        // is encoded. Note that we preserve Content-Disposition as that
        // isn't related purely to the how the content is encoded
        self.headers.remove_all_named("Content-Type");
        self.headers.remove_all_named("Content-Transfer-Encoding");
        // And add any from the new part
        self.headers.append(&mut new_part.headers.headers);
    }

    /// Constructs a new part with textual utf8 content.
    /// quoted-printable transfer encoding will be applied,
    /// unless it is smaller to represent the text in base64
    pub fn new_text(content_type: &str, content: &str) -> Self {
        // We'll probably use qp, so speculatively do the work
        let qp_encoded = quoted_printable::encode(content);

        let (mut encoded, encoding) = if qp_encoded == content.as_bytes() {
            (qp_encoded, None)
        } else if qp_encoded.len() <= BASE64_RFC2045.encode_len(content.len()) {
            (qp_encoded, Some("quoted-printable"))
        } else {
            // Turns out base64 will be smaller; perhaps the content
            // is dominated by non-ASCII text?
            (
                BASE64_RFC2045.encode(content.as_bytes()).into_bytes(),
                Some("base64"),
            )
        };

        if !encoded.ends_with(b"\r\n") {
            encoded.extend_from_slice(b"\r\n");
        }
        let mut headers = HeaderMap::default();

        let mut ct = MimeParameters::new(content_type);
        ct.set(
            "charset",
            if content.is_ascii() {
                "us-ascii"
            } else {
                "utf-8"
            },
        );
        headers.set_content_type(ct);

        if let Some(encoding) = encoding {
            headers.set_content_transfer_encoding(MimeParameters::new(encoding));
        }

        let body_len = encoded.len();
        let bytes =
            String::from_utf8(encoded).expect("transfer encoder to produce valid ASCII output");

        Self {
            bytes: bytes.into(),
            headers,
            body_offset: 0,
            body_len,
            conformance: MessageConformance::default(),
            parts: vec![],
            intro: "".into(),
            outro: "".into(),
        }
    }

    pub fn new_text_plain(content: &str) -> Self {
        Self::new_text("text/plain", content)
    }

    pub fn new_html(content: &str) -> Self {
        Self::new_text("text/html", content)
    }

    pub fn new_multipart(content_type: &str, parts: Vec<Self>, boundary: Option<&str>) -> Self {
        let mut headers = HeaderMap::default();

        let mut ct = MimeParameters::new(content_type);
        match boundary {
            Some(b) => {
                ct.set("boundary", b);
            }
            None => {
                // Generate a random boundary
                let uuid = uuid::Uuid::new_v4();
                let boundary = data_encoding::BASE64_NOPAD.encode(uuid.as_bytes());
                ct.set("boundary", &boundary);
            }
        }
        headers.set_content_type(ct);

        Self {
            bytes: "".into(),
            headers,
            body_offset: 0,
            body_len: 0,
            conformance: MessageConformance::default(),
            parts,
            intro: "".into(),
            outro: "".into(),
        }
    }

    pub fn new_binary(
        content_type: &str,
        content: &[u8],
        options: Option<&AttachmentOptions>,
    ) -> Self {
        let mut encoded = BASE64_RFC2045.encode(content);
        if !encoded.ends_with("\r\n") {
            encoded.push_str("\r\n");
        }
        let mut headers = HeaderMap::default();

        headers.set_content_type(MimeParameters::new(content_type));
        headers.set_content_transfer_encoding(MimeParameters::new("base64"));

        if let Some(opts) = options {
            let mut cd = MimeParameters::new(if opts.inline { "inline" } else { "attachment" });
            if let Some(name) = &opts.file_name {
                cd.set("filename", name);
            }
            headers.set_content_disposition(cd);

            if let Some(id) = &opts.content_id {
                headers.set_content_id(MessageID(id.to_string()));
            }
        }

        let body_len = encoded.len();

        Self {
            bytes: encoded.into(),
            headers,
            body_offset: 0,
            body_len,
            conformance: MessageConformance::default(),
            parts: vec![],
            intro: "".into(),
            outro: "".into(),
        }
    }

    /// Returns a SimplifiedStructure representation of the mime tree,
    /// with the (probable) primary text/plain and text/html parts
    /// pulled out, and the remaining parts recorded as a flat
    /// attachments array
    pub fn simplified_structure(&'a self) -> Result<SimplifiedStructure<'a>> {
        let parts = self.simplified_structure_pointers()?;

        let mut text = None;
        let mut html = None;

        let headers = &self
            .resolve_ptr(parts.header_part)
            .expect("header part to always be valid")
            .headers;

        if let Some(p) = parts.text_part.and_then(|p| self.resolve_ptr(p)) {
            text = match p.body()? {
                DecodedBody::Text(t) => Some(t),
                DecodedBody::Binary(_) => {
                    return Err(MailParsingError::BodyParse(
                        "expected text/plain part to be text, but it is binary".to_string(),
                    ))
                }
            };
        }
        if let Some(p) = parts.html_part.and_then(|p| self.resolve_ptr(p)) {
            html = match p.body()? {
                DecodedBody::Text(t) => Some(t),
                DecodedBody::Binary(_) => {
                    return Err(MailParsingError::BodyParse(
                        "expected text/html part to be text, but it is binary".to_string(),
                    ))
                }
            };
        }

        let mut attachments = vec![];
        for ptr in parts.attachments {
            attachments.push(self.resolve_ptr(ptr).expect("pointer to be valid").clone());
        }

        Ok(SimplifiedStructure {
            text,
            html,
            headers,
            attachments,
        })
    }

    /// Resolve a PartPointer to the corresponding MimePart
    pub fn resolve_ptr(&self, ptr: PartPointer) -> Option<&Self> {
        let mut current = self;
        let mut cursor = ptr.0.as_slice();

        loop {
            match cursor.get(0) {
                Some(&idx) => {
                    current = current.parts.get(idx as usize)?;
                    cursor = &cursor[1..];
                }
                None => {
                    // We have completed the walk
                    return Some(current);
                }
            }
        }
    }

    /// Resolve a PartPointer to the corresponding MimePart, for mutable access
    pub fn resolve_ptr_mut(&mut self, ptr: PartPointer) -> Option<&mut Self> {
        let mut current = self;
        let mut cursor = ptr.0.as_slice();

        loop {
            match cursor.get(0) {
                Some(&idx) => {
                    current = current.parts.get_mut(idx as usize)?;
                    cursor = &cursor[1..];
                }
                None => {
                    // We have completed the walk
                    return Some(current);
                }
            }
        }
    }

    /// Returns a set of PartPointers that locate the (probable) primary
    /// text/plain and text/html parts, and the remaining parts recorded
    /// as a flat attachments array.  The resulting
    /// PartPointers can be resolved to their actual instances for both
    /// immutable and mutable operations via resolve_ptr and resolve_ptr_mut.
    pub fn simplified_structure_pointers(&self) -> Result<SimplifiedStructurePointers> {
        self.simplified_structure_pointers_impl(None)
    }

    fn simplified_structure_pointers_impl(
        &self,
        my_idx: Option<u8>,
    ) -> Result<SimplifiedStructurePointers> {
        let info = Rfc2045Info::new(&self.headers)?;
        let is_inline = info
            .attachment_options
            .as_ref()
            .map(|ao| ao.inline)
            .unwrap_or(true);

        if let Some(ct) = &info.content_type {
            if is_inline {
                if ct.value == "text/plain" {
                    return Ok(SimplifiedStructurePointers {
                        text_part: Some(PartPointer::root_or_nth(my_idx)),
                        html_part: None,
                        header_part: PartPointer::root_or_nth(my_idx),
                        attachments: vec![],
                    });
                }
                if ct.value == "text/html" {
                    return Ok(SimplifiedStructurePointers {
                        html_part: Some(PartPointer::root_or_nth(my_idx)),
                        text_part: None,
                        header_part: PartPointer::root_or_nth(my_idx),
                        attachments: vec![],
                    });
                }
            }

            if ct.value.starts_with("multipart/") {
                let mut text_part = None;
                let mut html_part = None;
                let mut attachments = vec![];

                for (i, p) in self.parts.iter().enumerate() {
                    let part_idx = i.try_into().map_err(|_| MailParsingError::TooManyParts)?;
                    if let Ok(mut s) = p.simplified_structure_pointers_impl(Some(part_idx)) {
                        if text_part.is_none() {
                            if let Some(p) = s.text_part {
                                text_part.replace(PartPointer::root_or_nth(my_idx).append(p));
                            }
                        }
                        if html_part.is_none() {
                            if let Some(p) = s.html_part {
                                html_part.replace(PartPointer::root_or_nth(my_idx).append(p));
                            }
                        }
                        attachments.append(&mut s.attachments);
                    }
                }

                return Ok(SimplifiedStructurePointers {
                    html_part,
                    text_part,
                    header_part: PartPointer::root_or_nth(my_idx),
                    attachments,
                });
            }

            return Ok(SimplifiedStructurePointers {
                html_part: None,
                text_part: None,
                header_part: PartPointer::root_or_nth(my_idx),
                attachments: vec![PartPointer::root_or_nth(my_idx)],
            });
        }

        // Assume text/plain content-type
        Ok(SimplifiedStructurePointers {
            text_part: Some(PartPointer::root_or_nth(my_idx)),
            html_part: None,
            header_part: PartPointer::root_or_nth(my_idx),
            attachments: vec![],
        })
    }
}

/// References the position of a MimePart by encoding the steps in
/// a tree walking operation. The encoding of PartPointer is a
/// sequence of integers that identify the index of a child part
/// by its level within the mime tree, selecting the current node
/// when no more indices remain. eg: `[]` indicates the
/// root part, while `[0]` is the 0th child of the root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PartPointer(Vec<u8>);

impl PartPointer {
    /// Construct a PartPointer that references the root node
    pub fn root() -> Self {
        Self(vec![])
    }

    /// Construct a PartPointer that references either the nth
    /// or the root node depending upon the passed parameter
    pub fn root_or_nth(n: Option<u8>) -> Self {
        match n {
            Some(n) => Self::nth(n),
            None => Self::root(),
        }
    }

    /// Construct a PartPointer that references the nth child
    pub fn nth(n: u8) -> Self {
        Self(vec![n])
    }

    /// Join other onto self, consuming self and producing
    /// a pointer that makes other relative to self
    pub fn append(mut self, mut other: Self) -> Self {
        self.0.append(&mut other.0);
        Self(self.0)
    }
}

#[derive(Debug, Clone)]
pub struct SimplifiedStructurePointers {
    /// The primary text/plain part
    pub text_part: Option<PartPointer>,
    /// The primary text/html part
    pub html_part: Option<PartPointer>,
    /// The "top level" set of headers for the message
    pub header_part: PartPointer,
    /// all other (terminal) parts are attachments
    pub attachments: Vec<PartPointer>,
}

#[derive(Debug, Clone)]
pub struct SimplifiedStructure<'a> {
    pub text: Option<SharedString<'a>>,
    pub html: Option<SharedString<'a>>,
    pub headers: &'a HeaderMap<'a>,
    pub attachments: Vec<MimePart<'a>>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AttachmentOptions {
    pub file_name: Option<String>,
    pub inline: bool,
    pub content_id: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentTransferEncoding {
    SevenBit,
    EightBit,
    Binary,
    QuotedPrintable,
    Base64,
}

impl FromStr for ContentTransferEncoding {
    type Err = MailParsingError;

    fn from_str(s: &str) -> Result<Self> {
        if s.eq_ignore_ascii_case("7bit") {
            Ok(Self::SevenBit)
        } else if s.eq_ignore_ascii_case("8bit") {
            Ok(Self::EightBit)
        } else if s.eq_ignore_ascii_case("binary") {
            Ok(Self::Binary)
        } else if s.eq_ignore_ascii_case("quoted-printable") {
            Ok(Self::QuotedPrintable)
        } else if s.eq_ignore_ascii_case("base64") {
            Ok(Self::Base64)
        } else {
            Err(MailParsingError::InvalidContentTransferEncoding(
                s.to_string(),
            ))
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum DecodedBody<'a> {
    Text(SharedString<'a>),
    Binary(Vec<u8>),
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn msg_parsing() {
        let message = concat!(
            "Subject: hello there\n",
            "From:  Someone <someone@example.com>\n",
            "\n",
            "I am the body"
        );

        let part = MimePart::parse(message).unwrap();
        k9::assert_equal!(message, part.to_message_string());
        assert_eq!(part.raw_body(), "I am the body");
        k9::snapshot!(
            part.body(),
            r#"
Ok(
    Text(
        "I am the body",
    ),
)
"#
        );

        k9::snapshot!(
            part.rebuild().unwrap().to_message_string(),
            r#"
Content-Type: text/plain;\r
\tcharset="us-ascii"\r
Subject: hello there\r
From: Someone <someone@example.com>\r
\r
I am the body\r

"#
        );
    }

    #[test]
    fn mime_encoded_body() {
        let message = concat!(
            "Subject: hello there\n",
            "From: Someone <someone@example.com>\n",
            "Mime-Version: 1.0\n",
            "Content-Type: text/plain\n",
            "Content-Transfer-Encoding: base64\n",
            "\n",
            "aGVsbG8K\n"
        );

        let part = MimePart::parse(message).unwrap();
        k9::assert_equal!(message, part.to_message_string());
        assert_eq!(part.raw_body(), "aGVsbG8K\n");
        k9::snapshot!(
            part.body(),
            r#"
Ok(
    Text(
        "hello
",
    ),
)
"#
        );

        k9::snapshot!(
            part.rebuild().unwrap().to_message_string(),
            r#"
Content-Type: text/plain;\r
\tcharset="us-ascii"\r
Content-Transfer-Encoding: quoted-printable\r
Subject: hello there\r
From: Someone <someone@example.com>\r
Mime-Version: 1.0\r
\r
hello=0A\r

"#
        );
    }

    #[test]
    fn mime_multipart_1() {
        let message = concat!(
            "Subject: This is a test email\n",
            "Content-Type: multipart/alternative; boundary=foobar\n",
            "Mime-Version: 1.0\n",
            "Date: Sun, 02 Oct 2016 07:06:22 -0700 (PDT)\n",
            "\n",
            "--foobar\n",
            "Content-Type: text/plain; charset=utf-8\n",
            "Content-Transfer-Encoding: quoted-printable\n",
            "\n",
            "This is the plaintext version, in utf-8. Proof by Euro: =E2=82=AC\n",
            "--foobar\n",
            "Content-Type: text/html\n",
            "Content-Transfer-Encoding: base64\n",
            "\n",
            "PGh0bWw+PGJvZHk+VGhpcyBpcyB0aGUgPGI+SFRNTDwvYj4gdmVyc2lvbiwgaW4g \n",
            "dXMtYXNjaWkuIFByb29mIGJ5IEV1cm86ICZldXJvOzwvYm9keT48L2h0bWw+Cg== \n",
            "--foobar--\n",
            "After the final boundary stuff gets ignored.\n"
        );

        let part = MimePart::parse(message).unwrap();

        k9::assert_equal!(message, part.to_message_string());

        let children = part.child_parts();
        k9::assert_equal!(children.len(), 2);

        k9::snapshot!(
            children[0].body(),
            r#"
Ok(
    Text(
        "This is the plaintext version, in utf-8. Proof by Euro: €\r
",
    ),
)
"#
        );
        k9::snapshot!(
            children[1].body(),
            r#"
Ok(
    Text(
        "<html><body>This is the <b>HTML</b> version, in us-ascii. Proof by Euro: &euro;</body></html>
",
    ),
)
"#
        );
    }

    #[test]
    fn mutate_1() {
        let message = concat!(
            "Subject: This is a test email\r\n",
            "Content-Type: multipart/alternative; boundary=foobar\r\n",
            "Mime-Version: 1.0\r\n",
            "Date: Sun, 02 Oct 2016 07:06:22 -0700 (PDT)\r\n",
            "\r\n",
            "--foobar\r\n",
            "Content-Type: text/plain; charset=utf-8\r\n",
            "Content-Transfer-Encoding: quoted-printable\r\n",
            "\r\n",
            "This is the plaintext version, in utf-8. Proof by Euro: =E2=82=AC\r\n",
            "--foobar\r\n",
            "Content-Type: text/html\r\n",
            "Content-Transfer-Encoding: base64\r\n",
            "\r\n",
            "PGh0bWw+PGJvZHk+VGhpcyBpcyB0aGUgPGI+SFRNTDwvYj4gdmVyc2lvbiwgaW4g \r\n",
            "dXMtYXNjaWkuIFByb29mIGJ5IEV1cm86ICZldXJvOzwvYm9keT48L2h0bWw+Cg== \r\n",
            "--foobar--\r\n",
            "After the final boundary stuff gets ignored.\r\n"
        );

        let mut part = MimePart::parse(message).unwrap();
        k9::assert_equal!(message, part.to_message_string());
        fn munge(part: &mut MimePart) {
            let headers = part.headers_mut();
            headers.push(Header::with_name_value("X-Woot", "Hello"));
            headers.insert(0, Header::with_name_value("X-First", "at the top"));
            headers.retain(|hdr| !hdr.get_name().eq_ignore_ascii_case("date"));
        }
        munge(&mut part);

        let re_encoded = part.to_message_string();
        k9::snapshot!(
            re_encoded,
            r#"
X-First: at the top\r
Subject: This is a test email\r
Content-Type: multipart/alternative; boundary=foobar\r
Mime-Version: 1.0\r
X-Woot: Hello\r
\r
--foobar\r
Content-Type: text/plain; charset=utf-8\r
Content-Transfer-Encoding: quoted-printable\r
\r
This is the plaintext version, in utf-8. Proof by Euro: =E2=82=AC\r
--foobar\r
Content-Type: text/html\r
Content-Transfer-Encoding: base64\r
\r
PGh0bWw+PGJvZHk+VGhpcyBpcyB0aGUgPGI+SFRNTDwvYj4gdmVyc2lvbiwgaW4g \r
dXMtYXNjaWkuIFByb29mIGJ5IEV1cm86ICZldXJvOzwvYm9keT48L2h0bWw+Cg== \r
--foobar--\r
After the final boundary stuff gets ignored.\r

"#
        );

        eprintln!("part before mutate:\n{part:#?}");

        part.child_parts_mut().retain(|part| {
            let ct = part.headers().content_type().unwrap().unwrap();
            ct.value == "text/html"
        });

        eprintln!("part with html removed is:\n{part:#?}");

        let re_encoded = part.to_message_string();
        k9::snapshot!(
            re_encoded,
            r#"
X-First: at the top\r
Subject: This is a test email\r
Content-Type: multipart/alternative; boundary=foobar\r
Mime-Version: 1.0\r
X-Woot: Hello\r
\r
--foobar\r
Content-Type: text/html\r
Content-Transfer-Encoding: base64\r
\r
PGh0bWw+PGJvZHk+VGhpcyBpcyB0aGUgPGI+SFRNTDwvYj4gdmVyc2lvbiwgaW4g \r
dXMtYXNjaWkuIFByb29mIGJ5IEV1cm86ICZldXJvOzwvYm9keT48L2h0bWw+Cg== \r
--foobar--\r
After the final boundary stuff gets ignored.\r

"#
        );
    }

    #[test]
    fn replace_text_body() {
        let mut part = MimePart::new_text_plain("Hello 👻\r\n");
        let encoded = part.to_message_string();
        k9::snapshot!(
            &encoded,
            r#"
Content-Type: text/plain;\r
\tcharset="utf-8"\r
Content-Transfer-Encoding: base64\r
\r
SGVsbG8g8J+Ruw0K\r

"#
        );

        part.replace_text_body("text/plain", "Hello 🚀\r\n");
        let encoded = part.to_message_string();
        k9::snapshot!(
            &encoded,
            r#"
Content-Type: text/plain;\r
\tcharset="utf-8"\r
Content-Transfer-Encoding: base64\r
\r
SGVsbG8g8J+agA0K\r

"#
        );
    }

    #[test]
    fn construct_1() {
        let input_text = "Well, hello there! This is the plaintext version, in utf-8. Here's a Euro: €, and here are some emoji 👻 🍉 💩 and this long should be long enough that we wrap it in the returned part, let's see how that turns out!\r\n";

        let part = MimePart::new_text_plain(input_text);

        let encoded = part.to_message_string();
        k9::snapshot!(
            &encoded,
            r#"
Content-Type: text/plain;\r
\tcharset="utf-8"\r
Content-Transfer-Encoding: quoted-printable\r
\r
Well, hello there! This is the plaintext version, in utf-8. Here's a Euro: =\r
=E2=82=AC, and here are some emoji =F0=9F=91=BB =F0=9F=8D=89 =F0=9F=92=A9 a=\r
nd this long should be long enough that we wrap it in the returned part, le=\r
t's see how that turns out!\r

"#
        );

        let parsed_part = MimePart::parse(encoded.clone()).unwrap();
        k9::assert_equal!(encoded.as_str(), parsed_part.to_message_string().as_str());
        k9::assert_equal!(part.body().unwrap(), DecodedBody::Text(input_text.into()));
        k9::snapshot!(
            parsed_part.simplified_structure_pointers(),
            "
Ok(
    SimplifiedStructurePointers {
        text_part: Some(
            PartPointer(
                [],
            ),
        ),
        html_part: None,
        header_part: PartPointer(
            [],
        ),
        attachments: [],
    },
)
"
        );
    }

    #[test]
    fn construct_2() {
        let msg = MimePart::new_multipart(
            "multipart/mixed",
            vec![
                MimePart::new_text_plain("plain text"),
                MimePart::new_html("<b>rich</b> text"),
                MimePart::new_binary(
                    "application/octet-stream",
                    &[0, 1, 2, 3],
                    Some(&AttachmentOptions {
                        file_name: Some("woot.bin".to_string()),
                        inline: false,
                        content_id: Some("woot.id".to_string()),
                    }),
                ),
            ],
            Some("my-boundary"),
        );
        k9::snapshot!(
            msg.to_message_string(),
            r#"
Content-Type: multipart/mixed;\r
\tboundary="my-boundary"\r
\r
--my-boundary\r
Content-Type: text/plain;\r
\tcharset="us-ascii"\r
\r
plain text\r
--my-boundary\r
Content-Type: text/html;\r
\tcharset="us-ascii"\r
\r
<b>rich</b> text\r
--my-boundary\r
Content-Type: application/octet-stream\r
Content-Transfer-Encoding: base64\r
Content-Disposition: attachment;\r
\tfilename="woot.bin"\r
Content-ID: <woot.id>\r
\r
AAECAw==\r
--my-boundary--\r

"#
        );

        k9::snapshot!(
            msg.simplified_structure_pointers(),
            "
Ok(
    SimplifiedStructurePointers {
        text_part: Some(
            PartPointer(
                [
                    0,
                ],
            ),
        ),
        html_part: Some(
            PartPointer(
                [
                    1,
                ],
            ),
        ),
        header_part: PartPointer(
            [],
        ),
        attachments: [
            PartPointer(
                [
                    2,
                ],
            ),
        ],
    },
)
"
        );
    }

    #[test]
    fn funky_headers() {
        let message = concat!(
            "Subject\r\n",
            "Other:\r\n",
            "Content-Type: multipart/alternative; boundary=foobar\r\n",
            "Mime-Version: 1.0\r\n",
            "Date: Sun, 02 Oct 2016 07:06:22 -0700 (PDT)\r\n",
            "\r\n",
            "The body.\r\n"
        );

        let part = MimePart::parse(message).unwrap();
        assert!(part
            .conformance()
            .contains(MessageConformance::MISSING_COLON_VALUE));
    }
}