daaki-message 0.2.0

RFC 5322 email message parser and builder
Documentation
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
//! Address formatting, validation, and related header field helpers.
//!
//! # References
//! - RFC 5322 Section 3.4 (address specification)
//! - RFC 5321 Section 4.1.2 (domain syntax)
//! - RFC 6531 Section 3.3 (internationalized email addresses)
//! - RFC 2047 Section 5 (encoded words in display names)

use super::*;

/// Normalizes line endings to CRLF per RFC 5322 Section 2.1.
///
/// Converts bare `\n` to `\r\n` and bare `\r` to `\r\n`, while leaving
/// existing `\r\n` pairs unchanged. This ensures the message body conforms
/// to the canonical form required by RFC 5322.
///
/// # References
/// - RFC 5322 Section 2.1 (CRLF line endings)
pub(super) fn normalize_line_endings(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\r' => {
                // CR or CRLF → CRLF
                result.push_str("\r\n");
                // Consume a following LF so CRLF counts as one line ending
                if chars.peek() == Some(&'\n') {
                    chars.next();
                }
            }
            '\n' => {
                // Bare LF → CRLF
                result.push_str("\r\n");
            }
            _ => {
                // Preserve all other characters including multi-byte UTF-8
                result.push(c);
            }
        }
    }
    result
}

/// Replaces bare CR and LF characters with spaces to prevent header injection
/// while preserving word separation.
///
/// RFC 5322 Section 2.2.3 allows long header fields to be folded with CRLF
/// followed by whitespace. User-provided values may contain embedded newlines
/// that were intended as word separators. Stripping them entirely would join
/// adjacent words (e.g., "Line1\nLine2" becoming "`Line1Line2`"). Instead, we
/// replace CR/LF with spaces and collapse consecutive whitespace to keep the
/// result clean.
///
/// # References
/// - RFC 5322 Section 2.1 (header line structure)
/// - RFC 5322 Section 2.2.3 (long header fields / folding)
pub(super) fn sanitize_header_value(value: &str) -> String {
    // RFC 5322 Section 2.2.3: SP and HTAB are legal WSP inside field bodies
    // and must not be rewritten or collapsed, because doing so changes the
    // caller's header value.  Replace only disallowed ASCII control bytes with
    // a separating SP, coalescing adjacent control characters so CRLF header
    // injection attempts do not turn into arbitrarily long space runs.
    let mut result = String::with_capacity(value.len());
    let mut last_output_wsp = false;
    for c in value.chars() {
        if c.is_ascii_control() && c != '\t' {
            if !last_output_wsp {
                result.push(' ');
                last_output_wsp = true;
            }
        } else {
            result.push(c);
            last_output_wsp = c == ' ' || c == '\t';
        }
    }
    result
}

/// RFC 2047 encodes text as Base64 encoded words if it contains non-ASCII.
///
/// Returns the original text unchanged if it is pure ASCII and does not
/// contain encoded-word syntax. Otherwise encodes the entire text as one or
/// more `=?UTF-8?B?...?=` encoded words, each at most 75 characters long
/// per RFC 2047 Section 2. Multiple encoded words are separated by a single
/// space so that [`write_header`] can fold at word boundaries.
///
/// Pure-ASCII values that contain `=?` are also encoded because a
/// conforming parser will interpret the pattern as an RFC 2047 encoded-word,
/// causing round-trip data loss (RFC 2047 Section 5).
///
/// # References
/// - RFC 2047 Section 2 (encoded-word syntax, 75-char limit)
/// - RFC 2047 Section 5 (use in message header bodies)
/// - RFC 5322 Section 2.2 (field bodies must be US-ASCII)
pub(crate) fn encode_rfc2047_if_needed(text: &str) -> String {
    // RFC 2047 Section 5: an unencoded `=?` in a header field body can be
    // mis-parsed as the start of an encoded-word. Encode the value to
    // protect the literal text from round-trip corruption.
    //
    // RFC 5322 Section 2.1.1: lines MUST NOT exceed 998 characters. If any
    // whitespace-delimited word is long enough to produce an over-long line
    // (accounting for a minimal header-name prefix and fold indentation),
    // we must encode the value so the resulting encoded-words fit within the
    // line limit. Without this, header emission would either exceed the
    // 998-char limit or insert spaces that corrupt the value.
    let has_overlong_word = text
        .split_whitespace()
        .any(|w| w.len() > HARD_LINE_LIMIT - 2);
    // RFC 5322 Section 2.2: field bodies must be printable US-ASCII.
    // Control characters (0x00-0x1F excluding HTAB, 0x7F) are ASCII but
    // not printable, so they must be encoded just like non-ASCII bytes.
    // HTAB (0x09) is valid WSP per RFC 5322 Section 2.2.
    let has_control_chars = text.bytes().any(|b| (b < 0x20 && b != b'\t') || b == 0x7F);
    if text.bytes().all(|b| b.is_ascii())
        && !has_control_chars
        && !text.contains("=?")
        && !has_overlong_word
    {
        return text.to_string();
    }

    // Max encoded word = 75 chars (RFC 2047 Section 2).
    // Overhead: "=?UTF-8?B?" (10) + "?=" (2) = 12 chars.
    // Max base64 payload: 75 - 12 = 63 chars.
    // 63 base64 chars encodes floor(63/4)*3 = 45 bytes, but we use 42 bytes
    // (= 56 base64 chars, 68 total) to stay conservative. This ensures that
    // even if snap_utf8_chunk_end adjusts the boundary by up to 3 bytes to
    // complete a multi-byte UTF-8 character (45 bytes max → 60 base64 chars
    // + 12 overhead = 72 chars), the result stays well within the 75-char
    // limit (RFC 2047 Section 2).
    let max_raw_bytes: usize = 42;

    let bytes = text.as_bytes();
    let mut words: Vec<String> = Vec::new();
    let mut pos = 0;

    while pos < bytes.len() {
        let chunk_end = snap_utf8_chunk_end(bytes, pos, max_raw_bytes);

        let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes[pos..chunk_end]);
        words.push(format!("=?UTF-8?B?{b64}?="));
        pos = chunk_end;
    }

    // Space-separate: RFC 2047 Section 6.2 says whitespace between adjacent
    // encoded words is collapsed (not part of the decoded text).
    words.join(" ")
}

/// Validates that an address has a syntactically valid email (RFC 5322 Section 3.4,
/// RFC 6531 Section 3.3).
///
/// Enforces:
/// - Exactly one `@` separator (RFC 5322 Section 3.4.1: `addr-spec = local-part "@" domain`)
/// - Non-empty local-part and domain
/// - No whitespace or control characters in unquoted local parts and domain
/// - Non-ASCII (UTF-8) bytes are allowed in local-parts per RFC 6531 Section 3.3
/// - Quoted local parts (`"..."`) are allowed per RFC 5322 Section 3.4.1
/// - Domain must not start or end with `.` (RFC 5321 Section 4.1.2)
pub(crate) fn validate_address(addr: &Address) -> Result<(), Error> {
    let email = &addr.email;
    if email.is_empty() {
        return Err(Error::InvalidAddress("empty email address".into()));
    }
    // RFC 5322 Section 3.4.1: addr-spec = local-part "@" domain.
    // A quoted local-part (`"..."`) may contain `@` as valid qtext
    // (0x40 is in the %d33 / %d35-91 / %d93-126 range), so we must
    // skip past the quoted-string before searching for the `@` separator.
    let at_pos = if email.starts_with('"') {
        // Find the unescaped closing double-quote.
        let bytes = email.as_bytes();
        let mut i = 1;
        while i < bytes.len() {
            if bytes[i] == b'\\' {
                // RFC 5322 Section 3.2.4: skip quoted-pair.
                i += 2;
            } else if bytes[i] == b'"' {
                break;
            } else {
                i += 1;
            }
        }
        // The `@` separator must immediately follow the closing quote.
        if i >= bytes.len() || bytes[i] != b'"' {
            return Err(Error::InvalidAddress(format!(
                "unterminated quoted local-part: {email}"
            )));
        }
        // The very next byte must be '@'.
        let sep = i + 1;
        if sep >= bytes.len() || bytes[sep] != b'@' {
            return Err(Error::InvalidAddress(format!(
                "missing '@' after quoted local-part: {email}"
            )));
        }
        sep
    } else {
        email
            .find('@')
            .ok_or_else(|| Error::InvalidAddress(format!("missing '@' in email: {email}")))?
    };
    // RFC 5322 Section 3.4.1: exactly one '@' separator.
    if email[at_pos + 1..].contains('@') {
        return Err(Error::InvalidAddress(format!(
            "multiple '@' characters in email: {email}"
        )));
    }
    let local = &email[..at_pos];
    let domain = &email[at_pos + 1..];
    if local.is_empty() {
        return Err(Error::InvalidAddress(format!("empty local part: {email}")));
    }
    if domain.is_empty() {
        return Err(Error::InvalidAddress(format!("empty domain part: {email}")));
    }
    // RFC 5321 Section 4.1.2: Domain = sub-domain *("." sub-domain),
    // sub-domain must be non-empty — domain cannot start or end with '.'.
    if domain.starts_with('.') || domain.ends_with('.') {
        return Err(Error::InvalidAddress(format!(
            "domain must not start or end with '.': {email}"
        )));
    }
    // RFC 5321 Section 4.1.2: Each sub-domain between dots must be non-empty,
    // so consecutive dots ("..") indicate an empty label and are invalid.
    if domain.contains("..") {
        return Err(Error::InvalidAddress(format!(
            "domain contains consecutive dots: {email}"
        )));
    }
    // RFC 5322 Section 3.4.1: local-part = dot-atom / quoted-string.
    // If the local part is a quoted-string (starts and ends with `"`),
    // validate the inner content per RFC 5322 Section 3.2.4:
    //   quoted-string = DQUOTE *( qtext / quoted-pair ) DQUOTE
    //   qtext         = %d33 / %d35-91 / %d93-126 (printable US-ASCII except `\` and `"`)
    //   quoted-pair   = "\" ( VCHAR / WSP )
    let is_quoted_local = local.len() >= 2 && local.starts_with('"') && local.ends_with('"');
    if is_quoted_local {
        // Validate the quoted-string content (between the outer quotes).
        let inner = &local.as_bytes()[1..local.len() - 1];
        validate_quoted_string_content(inner, email)?;

        // RFC 5321 Section 4.1.2: validate domain characters.
        validate_domain(domain, email)?;
    } else {
        // RFC 5322 Section 3.4.1: local-part = dot-atom / quoted-string.
        // For an unquoted local-part (dot-atom), each atom must contain
        // only `atext` characters (RFC 5322 Section 3.2.3):
        //   atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" /
        //           "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" /
        //           "`" / "{" / "|" / "}" / "~"
        // The dot (".") separates atoms in a dot-atom but is not itself atext.
        // RFC 6531 Section 3.3: UTF8-non-ascii bytes (>= 0x80) are also
        // permitted in internationalized local-parts.
        for &b in local.as_bytes() {
            if b >= 0x80 {
                // RFC 6531 Section 3.3: non-ASCII (UTF-8) bytes are valid in
                // internationalized local-parts.
                continue;
            }
            if !is_atext(b) && b != b'.' {
                return Err(Error::InvalidAddress(format!(
                    "unquoted local-part contains non-atext character '{}' \
                     (RFC 5322 Section 3.2.3): {email}",
                    char::from(b)
                )));
            }
        }
        // RFC 5321 Section 4.1.2: validate domain characters.
        validate_domain(domain, email)?;
        // RFC 5321 Section 4.1.2: `Dot-string = Atom *("." Atom)` — each
        // atom must be non-empty, so consecutive dots, leading dots, and
        // trailing dots are all invalid in an unquoted local-part.
        if local.contains("..") || local.starts_with('.') || local.ends_with('.') {
            return Err(Error::InvalidAddress(format!(
                "invalid unquoted local-part per RFC 5321 Section 4.1.2 \
                 (Dot-string = Atom *(\".\", Atom)): {email}"
            )));
        }
    }
    Ok(())
}

/// Validates the content between the outer double-quotes of a quoted-string
/// per RFC 5322 Section 3.2.4, extended by RFC 6531 Section 3.3 to allow
/// UTF-8 non-ASCII bytes in internationalized email addresses.
///
/// `quoted-string = DQUOTE *( qtext / quoted-pair ) DQUOTE`
/// where `qtext = %d33 / %d35-91 / %d93-126` (printable US-ASCII except
/// `\` and `"`), and `quoted-pair = "\" ( VCHAR / WSP )`.
/// RFC 6531 Section 3.3 extends qtext to include UTF-8 non-ASCII bytes.
fn validate_quoted_string_content(inner: &[u8], email: &str) -> Result<(), Error> {
    let mut i = 0;
    while i < inner.len() {
        let b = inner[i];
        if b == b'\\' {
            // RFC 5322 Section 3.2.4: quoted-pair = "\" (VCHAR / WSP)
            // VCHAR = %d33-126, WSP = SP / HTAB
            if i + 1 >= inner.len() {
                return Err(Error::InvalidAddress(format!(
                    "quoted local-part has trailing backslash \
                     (RFC 5322 Section 3.2.4): {email}"
                )));
            }
            let next = inner[i + 1];
            if !((0x21..=0x7E).contains(&next) || next == b' ' || next == b'\t') {
                return Err(Error::InvalidAddress(format!(
                    "quoted local-part has invalid quoted-pair \
                     (RFC 5322 Section 3.2.4): {email}"
                )));
            }
            i += 2;
        } else if b == b'"' {
            // Unescaped double-quote inside the quoted-string is invalid.
            return Err(Error::InvalidAddress(format!(
                "quoted local-part contains unescaped double-quote \
                 (RFC 5322 Section 3.2.4): {email}"
            )));
        } else if b == b' ' || b == b'\t' {
            // RFC 5322 Section 3.2.4: WSP (SP / HTAB) is allowed via the
            // optional FWS in the quoted-string production.
            i += 1;
        } else if (0x21..=0x7E).contains(&b) {
            // RFC 5322 Section 3.2.4: qtext = %d33 / %d35-91 / %d93-126.
            // `\` (0x5C) and `"` (0x22) are already handled above, so every
            // remaining byte in 0x21..=0x7E is valid qtext.
            i += 1;
        } else if b >= 0x80 {
            // RFC 6531 Section 3.3 extends RFC 5322 to allow UTF-8
            // non-ASCII bytes in internationalized email local-parts,
            // including inside quoted-strings.
            i += 1;
        } else {
            // Control characters (0x00-0x08, 0x0A-0x1F) and DEL (0x7F)
            // are not valid qtext. RFC 5322 Section 4 defines obs-qtext
            // that includes some of these, but Section 4 says generators
            // MUST NOT produce obsolete constructs.
            return Err(Error::InvalidAddress(format!(
                "quoted local-part contains invalid byte 0x{b:02X} \
                 (RFC 5322 Section 3.2.4 qtext): {email}"
            )));
        }
    }
    Ok(())
}

/// Returns `true` if `bare` is a syntactically valid `msg-id` body
/// (the part between `<` and `>`) per RFC 5322 Section 3.6.4,
/// extended by RFC 6532 Section 3.2 to allow UTF-8 characters.
///
/// `msg-id = "<" id-left "@" id-right ">"`
///
/// `id-left` must be `dot-atom-text`. `id-right` may be either
/// `dot-atom-text` or `no-fold-literal` (RFC 5322 Section 3.6.4).
/// RFC 6532 Section 3.2 extends both `atext` and `dtext` to include
/// UTF-8 non-ASCII.
pub(super) fn is_valid_msg_id(bare: &str) -> bool {
    is_strict_bare_message_id_body(bare)
}

/// Returns `true` if `b` is a valid LDH (Letter-Digit-Hyphen) character per
/// RFC 5321 Section 4.1.2: `sub-domain = Let-dig [Ldh-str]`,
/// `Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig`.
fn is_ldh(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'-'
}

/// Validates a domain per RFC 5322 Section 3.4.1 / RFC 6532 Section 3.2.
///
/// Domain = dot-atom / domain-literal / obs-domain
/// sub-domain = Let-dig [Ldh-str]
/// Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
///
/// RFC 6531 Section 3.3 extends the domain production to allow UTF-8
/// characters in domain labels (internationalized domain names).
/// Non-ASCII bytes (>= 0x80) are accepted per RFC 6531.
///
/// For header-address domain-literals (`[...]`), RFC 5322 Section 3.4.1
/// uses the liberal `domain-literal` / `dtext` grammar rather than SMTP's
/// stricter RFC 5321 Section 4.1.3 `address-literal` productions. RFC 6532
/// Section 3.2 additionally extends `dtext` with UTF-8.
///
/// For dot-atom domains, each ASCII byte in a label must be an LDH
/// character; non-ASCII UTF-8 bytes are allowed for internationalized
/// domain names.
fn validate_domain(domain: &str, email: &str) -> Result<(), Error> {
    // RFC 5322 Section 3.4.1: domain = dot-atom / domain-literal / obs-domain.
    if domain.starts_with('[') && domain.ends_with(']') {
        return validate_domain_literal(domain, email);
    }

    // RFC 5321 Section 4.1.2: Domain = sub-domain *("." sub-domain)
    // Each sub-domain label must be non-empty and consist only of
    // Let-dig / Ldh-str characters (alphanumeric and hyphen) for ASCII
    // bytes. Non-ASCII bytes (>= 0x80) are allowed per RFC 6531
    // Section 3.3 (internationalized domain names).
    for label in domain.split('.') {
        if label.is_empty() {
            // Consecutive dots, leading dot, or trailing dot — already
            // caught earlier, but defend in depth.
            return Err(Error::InvalidAddress(format!(
                "domain contains empty label (RFC 5321 Section 4.1.2): {email}"
            )));
        }
        // DNS labels are limited to 63 octets on the wire (RFC 1035
        // Section 2.3.4). Apply that bound directly to ASCII labels;
        // non-ASCII U-labels may have a different UTF-8 octet length
        // before IDNA mapping, so leave those to higher-level handling.
        if label.is_ascii() && label.len() > 63 {
            return Err(Error::InvalidAddress(format!(
                "domain label exceeds 63-octet ASCII limit \
                 (RFC 1035 Section 2.3.4 / RFC 5321 Section 4.1.2): {email}"
            )));
        }
        for &b in label.as_bytes() {
            // RFC 6531 Section 3.3: non-ASCII bytes are valid in
            // internationalized domain names (U-labels).
            if !b.is_ascii() {
                continue;
            }
            if !is_ldh(b) {
                return Err(Error::InvalidAddress(format!(
                    "domain contains invalid character '{}' \
                     (RFC 5321 Section 4.1.2: sub-domain = Let-dig [Ldh-str]): {email}",
                    char::from(b)
                )));
            }
        }
        // RFC 5321 Section 4.1.2: Ldh-str ends with Let-dig, so labels
        // must not start or end with a hyphen.
        if label.starts_with('-') || label.ends_with('-') {
            return Err(Error::InvalidAddress(format!(
                "domain label must not start or end with a hyphen \
                 (RFC 5321 Section 4.1.2): {email}"
            )));
        }
    }

    Ok(())
}

/// Validates an RFC 5322 `domain-literal` used in message header addresses.
///
/// RFC 5322 Section 3.4.1 defines:
///
/// `domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]`
///
/// and RFC 6532 Section 3.2 extends `dtext` with `UTF8-non-ascii`.
///
/// This is intentionally more liberal than SMTP's RFC 5321 Section 4.1.3
/// `address-literal` syntax. Message headers may therefore contain values
/// such as `user@[10,0,0,1]` even though SMTP envelope paths must reject
/// them unless they are valid RFC 5321 address-literals.
fn validate_domain_literal(domain: &str, email: &str) -> Result<(), Error> {
    let Some(body) = domain.strip_prefix('[').and_then(|s| s.strip_suffix(']')) else {
        return Err(Error::InvalidAddress(format!(
            "domain-literal must be enclosed in '[' and ']' \
             (RFC 5322 Section 3.4.1): {email}"
        )));
    };

    for ch in body.chars() {
        if ch == '[' || ch == ']' || ch == '\\' || ch == '\r' || ch == '\n' {
            return Err(Error::InvalidAddress(format!(
                "domain-literal contains invalid character {ch:?} \
                 (RFC 5322 Section 3.4.1 dtext): {email}"
            )));
        }

        if ch.is_ascii() {
            let byte = ch as u8;
            if byte.is_ascii_control() || byte == b' ' || byte == b'\t' {
                return Err(Error::InvalidAddress(format!(
                    "domain-literal contains invalid ASCII byte 0x{byte:02X} \
                     (RFC 5322 Section 3.4.1 dtext): {email}"
                )));
            }
        }
        // RFC 6532 Section 3.2 extends dtext with UTF8-non-ascii, so
        // non-ASCII characters are accepted as-is in header addresses.
    }

    Ok(())
}

/// Returns `true` if `b` is a valid `atext` character per RFC 5322 Section 3.2.3.
///
/// ```text
/// atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" /
///         "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" /
///         "`" / "{" / "|" / "}" / "~"
/// ```
fn is_atext(b: u8) -> bool {
    b.is_ascii_alphanumeric()
        || matches!(
            b,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'/'
                | b'='
                | b'?'
                | b'^'
                | b'_'
                | b'`'
                | b'{'
                | b'|'
                | b'}'
                | b'~'
        )
}

/// Rejects header names that collide with standard headers the builder
/// already emits, preventing duplicate headers that violate RFC 5322
/// Section 3.6 occurrence limits.
///
/// ftext syntax validation is handled by [`HeaderName::new`] at
/// construction time (RFC 5322 Section 2.2). This function enforces the
/// builder-level policy on top of that.
///
/// # References
/// - RFC 5322 Section 3.6 (field occurrence limits)
/// - RFC 5322 Section 1.2.2 (field names are case-insensitive)
pub(super) fn validate_reserved_header_name(name: &HeaderName) -> Result<(), Error> {
    // RFC 5322 Section 3.6: reject names that collide with standard headers
    // the builder already emits. Comparison is case-insensitive per
    // RFC 5322 Section 1.2.2 ("field names are case-insensitive").
    let lower = name.as_str().to_ascii_lowercase();
    if RESERVED_HEADER_NAMES.contains(&lower.as_str()) {
        return Err(Error::ReservedHeaderName(format!(
            "header '{}' is a standard header managed by the builder \
             (RFC 5322 Section 3.6); use the dedicated OutgoingEmail field instead",
            name.as_str()
        )));
    }
    Ok(())
}

/// Header names the builder emits automatically.
///
/// RFC 5322 Section 3.6 specifies occurrence limits for these headers
/// (most must appear exactly once). Allowing them in `extra_headers` would
/// produce duplicate headers that violate the spec.
pub(super) const RESERVED_HEADER_NAMES: &[&str] = &[
    "from",
    "sender",
    "to",
    "cc",
    "bcc",
    "reply-to",
    "subject",
    "date",
    "message-id",
    "mime-version",
    "content-type",
    "content-transfer-encoding",
    "in-reply-to",
    "references",
];

/// Extra headers whose field bodies are structured syntax rather than free
/// text, so RFC 2047 encoded-words must not be generated there.
///
/// Includes trace fields (RFC 5321), authentication results (RFC 8601), and
/// DKIM/ARC signature headers (RFC 6376, RFC 8617). MIME structured fields
/// such as `Content-Disposition` and top-level `Content-ID` also belong here
/// because RFC 2047 encoded-words are not valid inside MIME parameter values
/// or `msg-id` syntax (RFC 2231 Section 4, RFC 2045 Section 7, and RFC 2047
/// Section 5). RFC 6532 Sections 3.2 and 3.6 allow direct UTF-8 in
/// internationalized headers instead.
pub(super) const STRUCTURED_EXTRA_HEADERS: &[&str] = &[
    "content-disposition",
    "content-id",
    "received",
    "return-path",
    "resent-date",
    "resent-from",
    "resent-sender",
    "resent-to",
    "resent-cc",
    "resent-bcc",
    "resent-reply-to",
    "resent-message-id",
    "dkim-signature",
    "domainkey-signature",
    "arc-seal",
    "arc-message-signature",
    "arc-authentication-results",
    "authentication-results",
];

/// RFC 2047 Section 5: encoded-words are only valid in specific unstructured
/// positions and must not be emitted into structured field bodies.
pub(super) fn is_structured_extra_header(name: &str) -> bool {
    let lower = name.to_ascii_lowercase();
    STRUCTURED_EXTRA_HEADERS.contains(&lower.as_str())
}

/// RFC 5321 Section 4.4 trace headers must be prepended ahead of the
/// ordinary RFC 5322 header block. `Return-Path` comes before `Received`.
pub(super) fn is_trace_extra_header(name: &str) -> bool {
    name.eq_ignore_ascii_case("return-path") || name.eq_ignore_ascii_case("received")
}

/// RFC 5322 Section 3.6.7: a trace block is `[Return-Path] 1*Received`, so
/// at most one `Return-Path` is allowed and it cannot appear without at least
/// one `Received` field.
pub(super) fn validate_trace_headers(
    return_path_headers: &[(String, String)],
    received_headers: &[(String, String)],
) -> Result<(), Error> {
    if return_path_headers.len() > 1 {
        return Err(Error::InvalidTraceHeader(
            "trace header block must contain at most one Return-Path \
             (RFC 5322 Section 3.6.7)"
                .into(),
        ));
    }
    if !return_path_headers.is_empty() && received_headers.is_empty() {
        return Err(Error::InvalidTraceHeader(
            "Return-Path must not appear without at least one Received header \
             (RFC 5322 Section 3.6.7)"
                .into(),
        ));
    }
    Ok(())
}

/// RFC 5322 Section 3.6.7: `Return-Path` uses `path`, which is either an
/// `angle-addr` or the null path `<>`. RFC 5321 Section 4.4 copies the SMTP
/// envelope reverse-path into that header field.
pub(super) fn validate_trace_header_value(name: &str, value: &str) -> Result<(), Error> {
    if name.eq_ignore_ascii_case("return-path") {
        let trimmed = value.trim();
        let Some(inner) = trimmed.strip_prefix('<').and_then(|s| s.strip_suffix('>')) else {
            return Err(Error::InvalidTraceHeader(
                "Return-Path must be an angle-addr or null path \
                 (RFC 5322 Section 3.6.7 / RFC 5321 Section 4.4)"
                    .into(),
            ));
        };

        // RFC 5322 Section 3.6.7 permits an empty null path `<>` (with optional
        // CFWS around the empty brackets) for bounce-like trace headers.
        if inner.trim().is_empty() {
            return Ok(());
        }

        // For the non-empty angle-addr form, generators must emit a strict
        // `addr-spec` between the brackets rather than extra internal CFWS.
        if inner != inner.trim() {
            return Err(Error::InvalidTraceHeader(
                "Return-Path angle-addr must not contain internal surrounding whitespace \
                 (RFC 5322 Section 3.6.7)"
                    .into(),
            ));
        }

        validate_address(&Address {
            name: None,
            email: inner.to_owned(),
        })
        .map_err(|_| {
            Error::InvalidTraceHeader(
                "Return-Path must contain a syntactically valid addr-spec \
                 (RFC 5322 Section 3.6.7 / RFC 5321 Section 4.4)"
                    .into(),
            )
        })?;
    } else if name.eq_ignore_ascii_case("received") {
        // RFC 5322 Section 3.6.7: `received = "Received:" *received-token ";"
        // date-time`. The token list may be empty, but the trailing semicolon
        // and date-time are mandatory.
        let Some((_, date_time)) = value.rsplit_once(';') else {
            return Err(Error::InvalidTraceHeader(
                "Received must end with ';' and a date-time \
                 (RFC 5322 Section 3.6.7)"
                    .into(),
            ));
        };

        if parse_rfc5322_date(date_time.trim()).is_none() {
            return Err(Error::InvalidTraceHeader(
                "Received must end with a syntactically valid date-time \
                 (RFC 5322 Section 3.6.7)"
                    .into(),
            ));
        }
    }
    Ok(())
}

/// RFC 5322 Sections 3.6.6 and 4.5.6 resent fields form a prepended resent block.
pub(super) fn is_resent_extra_header(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "resent-date"
            | "resent-from"
            | "resent-sender"
            | "resent-to"
            | "resent-cc"
            | "resent-bcc"
            | "resent-reply-to"
            | "resent-message-id"
    )
}

/// RFC 5322 Sections 3.6.6 and 4.5.6: resent blocks are composed from the
/// resent field names, each with the same field-body syntax as its base field.
pub(super) fn resent_field_kind(
    name: &str,
    resent_from_mailbox_count: usize,
) -> Result<ResentFieldKind, Error> {
    match name.to_ascii_lowercase().as_str() {
        "resent-date" => Ok(ResentFieldKind::Date),
        "resent-from" => Ok(ResentFieldKind::From {
            mailbox_count: resent_from_mailbox_count,
        }),
        "resent-sender" => Ok(ResentFieldKind::Sender),
        "resent-to" => Ok(ResentFieldKind::To),
        "resent-cc" => Ok(ResentFieldKind::Cc),
        "resent-bcc" => Ok(ResentFieldKind::Bcc),
        "resent-reply-to" => Ok(ResentFieldKind::ReplyTo),
        "resent-message-id" => Ok(ResentFieldKind::MessageId),
        _ => Err(Error::InvalidResentHeader(format!(
            "unknown resent field: {name}"
        ))),
    }
}

/// RFC 5322 Sections 3.6.6 and 4.5.6 reuse the base field-body syntax for
/// resent fields, so builders must reject malformed structured values rather
/// than emitting invalid header bodies.
pub(super) fn validate_resent_header_value(
    name: &str,
    value: &str,
) -> Result<Option<usize>, Error> {
    if name.eq_ignore_ascii_case("resent-date") {
        if parse_rfc5322_date(value).is_none() {
            return Err(Error::InvalidResentHeader(
                "Resent-Date must use date-time syntax \
                 (RFC 5322 Sections 3.3 and 3.6.6)"
                    .into(),
            ));
        }
        return Ok(None);
    }

    if name.eq_ignore_ascii_case("resent-from") {
        let mailbox_count = parse_address_list(value).len();
        if mailbox_count == 0 {
            return Err(Error::InvalidResentHeader(
                "Resent-From must use mailbox-list syntax \
                 (RFC 5322 Sections 3.6.2 and 3.6.6)"
                    .into(),
            ));
        }
        return Ok(Some(mailbox_count));
    }

    if name.eq_ignore_ascii_case("resent-sender") {
        if parse_address_list(value).len() != 1 {
            return Err(Error::InvalidResentHeader(
                "Resent-Sender must use mailbox syntax \
                 (RFC 5322 Sections 3.6.2 and 3.6.6)"
                    .into(),
            ));
        }
        return Ok(None);
    }

    if name.eq_ignore_ascii_case("resent-to") || name.eq_ignore_ascii_case("resent-cc") {
        if parse_address_list(value).is_empty() {
            return Err(Error::InvalidResentHeader(format!(
                "{name} must use address-list syntax \
                 (RFC 5322 Sections 3.6.3 and 3.6.6)"
            )));
        }
        return Ok(None);
    }

    if name.eq_ignore_ascii_case("resent-reply-to") {
        if parse_address_list(value).is_empty() {
            return Err(Error::InvalidResentHeader(
                "Resent-Reply-To must use address-list syntax \
                 (RFC 5322 Sections 3.6.2 and 4.5.6)"
                    .into(),
            ));
        }
        return Ok(None);
    }

    if name.eq_ignore_ascii_case("resent-bcc") {
        // RFC 5322 Sections 3.6.3 and 3.6.6: Resent-Bcc reuses Bcc syntax,
        // which permits an empty field body only when it consists solely of
        // CFWS. Any remaining non-comment content must be a valid address-list.
        if strip_comments(value).trim().is_empty() {
            return Ok(None);
        }
        if parse_address_list(value).is_empty() {
            return Err(Error::InvalidResentHeader(
                "Resent-Bcc must use address-list syntax or be empty/CFWS \
                 (RFC 5322 Sections 3.6.3 and 3.6.6)"
                    .into(),
            ));
        }
        return Ok(None);
    }

    if name.eq_ignore_ascii_case("resent-message-id") {
        let trimmed = value.trim();
        let bare = strip_angle_brackets(trimmed).trim();
        if bare.is_empty()
            || trimmed.matches('<').count() > 1
            || trimmed.matches('>').count() > 1
            || trimmed.contains('<') != trimmed.contains('>')
            || !is_valid_msg_id(bare)
        {
            return Err(Error::InvalidResentHeader(
                "Resent-Message-ID must use msg-id syntax \
                 (RFC 5322 Sections 3.6.4 and 3.6.6)"
                    .into(),
            ));
        }
    }

    Ok(None)
}

/// RFC 5322 Section 3.6.6: each contiguous resent block must contain a valid
/// set of grouped resent fields, but the field order within the block is not
/// otherwise constrained.
pub(super) fn partition_resent_blocks(
    headers: &[PendingResentHeader],
) -> Result<Vec<Vec<(String, String)>>, Error> {
    let boundaries = partition_resent_blocks_from(headers, 0).map_err(|err| match err {
        ResentBlockError::MissingRequiredFields => Error::InvalidResentHeader(
            "resent header blocks must include both Resent-Date and Resent-From \
             (RFC 5322 Section 3.6.6)"
                .into(),
        ),
        ResentBlockError::MissingSender => Error::InvalidResentHeader(
            "multi-mailbox Resent-From requires Resent-Sender \
             (RFC 5322 Section 3.6.6)"
                .into(),
        ),
    })?;

    let mut blocks = Vec::with_capacity(boundaries.len());
    let mut start = 0usize;
    for end in boundaries {
        blocks.push(
            headers[start..end]
                .iter()
                .map(|header| (header.name.clone(), header.value.clone()))
                .collect(),
        );
        start = end;
    }
    Ok(blocks)
}

/// RFC 5322 Sections 3.6.6 and 4.5.6 allow multiple resent blocks so long as
/// each block is grouped, contains each resent field at most once, and
/// satisfies the required-field rules for that resending event.
pub(super) fn partition_resent_blocks_from(
    headers: &[PendingResentHeader],
    start: usize,
) -> Result<Vec<usize>, ResentBlockError> {
    if start == headers.len() {
        return Ok(Vec::new());
    }

    let mut seen_fields = [false; 8];
    let mut has_date = false;
    let mut has_from = false;
    let mut has_sender = false;
    let mut resent_from_mailbox_count = 0usize;
    let mut failure = ResentBlockError::MissingRequiredFields;
    let mut end = start;

    while end < headers.len() {
        let kind = headers[end].kind;
        let slot = kind.slot_index();
        if seen_fields[slot] {
            break;
        }
        seen_fields[slot] = true;

        match kind {
            ResentFieldKind::Date => has_date = true,
            ResentFieldKind::From { mailbox_count } => {
                has_from = true;
                resent_from_mailbox_count = mailbox_count;
            }
            ResentFieldKind::Sender => has_sender = true,
            ResentFieldKind::To
            | ResentFieldKind::Cc
            | ResentFieldKind::Bcc
            | ResentFieldKind::ReplyTo
            | ResentFieldKind::MessageId => {}
        }

        if resent_from_mailbox_count > 1 && !has_sender {
            failure = ResentBlockError::MissingSender;
        }
        end += 1;
    }

    if !(has_date && has_from && (resent_from_mailbox_count <= 1 || has_sender)) {
        return Err(failure);
    }

    let mut rest = partition_resent_blocks_from(headers, end)?;
    rest.insert(0, end);
    Ok(rest)
}

/// Formats an address for a header value (RFC 5322 Section 3.4).
///
/// Non-ASCII display names are RFC 2047 encoded (RFC 5322 Section 2.2,
/// RFC 2047 Section 5). ASCII names containing RFC 5322 specials are
/// wrapped in a quoted-string with backslash-escaping (RFC 5322 Section 3.2.4).
/// Escapes backslashes and double-quotes in a quoted-string per RFC 5322
/// Section 3.2.4 (`quoted-pair = "\" (VCHAR / WSP)`).
pub(super) fn escape_quoted_string(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

pub(super) fn format_address(addr: &Address) -> String {
    match &addr.name {
        // RFC 5322 Section 3.4: display-name is a `phrase` (`1*word`).
        // Whitespace alone does not form a valid word, so treat it as absent.
        Some(name) if !name.trim().is_empty() => {
            if !name.is_ascii() || name.bytes().any(|b| (b < 0x20 && b != b'\t') || b == 0x7F) {
                // Non-ASCII or non-printable display name: RFC 2047 encoded words
                // in phrase context (RFC 2047 Section 5). RFC 5322 Section 2.2
                // requires header field bodies to be printable US-ASCII; HTAB
                // (0x09) is valid WSP. No quoting needed — encoded words replace
                // "text" tokens in the phrase production.
                let encoded = encode_rfc2047_if_needed(name);
                format!("{encoded} <{}>", addr.email)
            } else if name.contains("=?") {
                // RFC 2047 Section 5: an unquoted phrase may contain
                // encoded-words. A display name that literally contains
                // `=?` would be mis-decoded by the parser. Quoting
                // prevents this: RFC 2047 Section 5 says encoded-words
                // MUST NOT appear inside a quoted-string.
                let escaped = escape_quoted_string(name);
                format!("\"{escaped}\" <{}>", addr.email)
            } else if needs_quoting(name) {
                // Escape backslashes and double-quotes (RFC 5322 Section 3.2.4)
                let escaped = escape_quoted_string(name);
                format!("\"{escaped}\" <{}>", addr.email)
            } else {
                format!("{name} <{}>", addr.email)
            }
        }
        _ => addr.email.clone(),
    }
}

/// Returns `true` if a display name must be quoted per RFC 5322 Section 3.2.3.
///
/// Quoting is required when the name contains any RFC 5322 specials:
/// `( ) < > [ ] : ; @ \ , . "`
fn needs_quoting(name: &str) -> bool {
    name.chars().any(|c| {
        matches!(
            c,
            '(' | ')' | '<' | '>' | '[' | ']' | ':' | ';' | '@' | '\\' | ',' | '.' | '"'
        )
    })
}

/// Formats a list of addresses as a comma-separated header value.
pub(super) fn format_address_list(addrs: &[Address]) -> String {
    addrs
        .iter()
        .map(format_address)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Strips surrounding angle brackets from a message-id if present.
///
/// Tolerates callers that pass `<id@host>` instead of bare `id@host`
/// (RFC 5322 Section 3.6.4 — msg-id uses angle brackets, but the API
/// contract stores bare addr-spec).
pub(super) fn strip_angle_brackets(s: &str) -> &str {
    s.strip_prefix('<')
        .and_then(|s| s.strip_suffix('>'))
        .unwrap_or(s)
}

/// Extracts the domain portion from an email address.
///
/// Correctly handles quoted local-parts (RFC 5322 Section 3.4.1)
/// where `@` may appear inside quotes (e.g., `"user@co"@example.com`).
///
/// # References
/// - RFC 5322 Section 3.4.1 (addr-spec: local-part "@" domain)
pub(super) fn extract_domain(email: &str) -> Option<&str> {
    let bytes = email.as_bytes();
    let mut i = 0;
    // Skip quoted local-part if present (RFC 5322 Section 3.2.4)
    if bytes.first() == Some(&b'"') {
        i = 1;
        while i < bytes.len() {
            match bytes[i] {
                b'\\' => i += 2, // quoted-pair: skip next char
                b'"' => {
                    i += 1;
                    break;
                }
                _ => i += 1,
            }
        }
    }
    // Find the @ separator after any quoted local-part
    let at = email[i..].find('@').map(|pos| pos + i)?;
    let domain = &email[at + 1..];
    if domain.is_empty() {
        None
    } else {
        Some(domain)
    }
}